【问题标题】:Show text annotations only above the line, not below仅在行上方而不是下方显示文本注释
【发布时间】:2020-03-26 09:48:53
【问题描述】:

我试图让 matplotlib 中此折线图中的文本注释显示在线上方。我正在使用adjustText 库来排斥行中的文本,但如图所示,一些文本位于行下方。我的代码基于接受的答案here

如何让每个注释出现在线上方,并通过灰线连接到它的点?他们中的一些人已经是这样了,但其他人不是。

x = list(df_usa['date'][61:-1].str.slice(5,)) # strings
x_range = np.arange(0, len(x))
y = list(df_usa['growth_factor'][61:-1])

plt.figure(figsize=(20,6))
plt.plot(x, y, color="red", alpha=0.5)
plt.xticks(np.arange(0, len(x), 5))

texts = [plt.text(x_range[i], y[i], round(y[i], 2)) for i in range(len(x))]

f = interpolate.interp1d(x_range, y)
f_x = np.arange(min(x_range), max(x_range), 0.005)
f_y = f(f_x)

# Generate non-overlapping data point labels
adjust_text(texts, x=f_x, y=f_y,
            only_move={'points': 'y', 'text': 'y'},
            force_points=0.15,
            autoalign='y',
            arrowprops=dict(arrowstyle="-", color="gray", lw=0.5))

plt.show()

【问题讨论】:

    标签: python matplotlib annotations


    【解决方案1】:

    当前的方法“禁止”沿曲线的点。扩展也可以是禁止曲线下方的点带。

    由于您的帖子似乎不包含测试数据,这里是链接帖子示例的改编:

    import matplotlib.pyplot as plt
    from adjustText import adjust_text
    import numpy as np
    from scipy import interpolate
    
    together = [(0, 1.0, 0.4), (25, 1.0127692669427917, 0.41), (50, 1.016404709797609, 0.41), (75, 1.1043426359673716, 0.42), (100, 1.1610446924342996, 0.44), (125, 1.1685687930691457, 0.43), (150, 1.3486407784550272, 0.45), (250, 1.4013999168008104, 0.45)]
    together.sort()
    
    text = [x for (x,y,z) in together]
    eucs = [y for (x,y,z) in together]
    covers = [z for (x,y,z) in together]
    
    p1 = plt.plot(eucs,covers,color="black", alpha=0.5)
    y0, y1 = plt.ylim()
    plt.ylim(y0, y1+.1*(y1-y0))
    texts = []
    for x, y, s in zip(eucs, covers, text):
        texts.append(plt.text(x, y, s))
    
    f = interpolate.interp1d(eucs, covers)
    x = np.arange(min(eucs), max(eucs), 0.0005)
    y = f(x)
    
    # optionally show the band of "forbidden" points
    # plt.scatter(x=np.tile(x, 5), y=np.concatenate([y-eps for eps in np.linspace(0, 0.01, 5) ]), alpha=.1)
    
    plt.xlabel("Proportional Euclidean Distance")
    plt.ylabel("Percentage Timewindows Attended")
    plt.title("Test plot")
    adjust_text(texts, x=np.tile(x, 5), y=np.concatenate([y-eps for eps in np.linspace(0, 0.01, 5) ]), autoalign='y',
                only_move={'points':'y', 'text':'y'}, force_points=.3,
                arrowprops=dict(arrowstyle="->", color='r', lw=0.5))
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 2017-12-08
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      相关资源
      最近更新 更多