为多行打印设置图例(在python中)

2024-09-28 16:57:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我在同一个图形中绘制了几条线,我想根据它的内容命名这组线。在这些行上,我还打算用误差条来绘制平均值。但出现了两个主要问题:

1)我的传说并不像我所想的那样出现(即使试图在数字范围之外画出一个额外的点,我也不能给他们一个名字-解决方法)

2)带有平均值和误差条的曲线图没有重叠。有时在前面,有时在其他曲线后面。

我该怎么做才能把它修好?我可以在Matlab(same problem for Matlab)中完成,但找不到python的答案enter image description here

这是我日常工作的一部分:

    UYavg = np.nanmean(UYbvall,0)
    yerr = np.nanstd(UYbvall,0)
    plt.figure()
    for i in range(71):
        plt.plot(LTbvall[i],UYbvall[i],'r-')
    l1 = plt.plot([-2,-1],[1,2],'r-')
    l2 = plt.plot(LTbvall[3],UYavg,'b*-')
    plt.errorbar(LTbvall[2],UYavg, yerr = yerr,ecolor='b')
    plt.xlabel('Tempo (LT)')
    plt.xlim(0,24)
    plt.ylabel('Uy (m/s)')
    plt.title('Vento neutro zonal calculado pelo modelo NWM (BV)')
    plt.legend((l1,l2),('Perfis COPEX','Media'), loc = 'best')

编辑: 答案必须类似于Multiple lines in a plotmake-custom-legend-in-matplotlib


Tags: 答案inl1forplotnp绘制plt
3条回答

基于另一个问题(make-custom-legend-in-matplotlibforce-errorbars-to-render-last-with-matplotlib),我说得对。 第二个错误不应该发生,我认为zorder选项可能有错误。如果我只为错误栏选择较大的数字,则错误栏的绘图将继续隐藏。所以我必须为for循环中的行的zorder设置一个负数。

解决问题的方法是:

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
for i in range(71):
    ax.plot(LTbvall[i],UXbvall[i],'-',color ='#C0C0C0',label = 'Perfis COPEX',zorder = -32)
ax.plot(LTbvall[3],UXavg,'b*-', label = u'média')
ax.errorbar(LTbvall[3],UXavg, yerr = yerr,ecolor='b',zorder = 10)
#Get artists and labels for legend and chose which ones to display
handles, labels = ax.get_legend_handles_labels()
display = (0,71)
ax.set_xlabel('Tempo (LT)')
ax.set_xlim(0,24)
ax.set_ylabel('Ux (m/s)')
ax.set_title('Vento neutro meridional calculado pelo modelo NWM (BV)')
ax.legend([handle for i,handle in enumerate(handles) if i in display],
      [label for i,label in enumerate(labels) if i in display], loc = 'best')
fig.savefig(path[9] + 'Uxbvall_LT_nwm')
plt.clf() 
plt.gcf()
plt.close()

输出如下:

enter image description here

我很惊讶当你试图创建你的传奇时没有收到错误信息。plt.plot命令总是返回一个元组,因此您应该捕获l1, = plt.plot(...)。那能修好吗?

我发现最简单的解决方案是在创建时给线标签。尝试以下操作,您将看到图例上同时显示两行:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3], color='red', label='line one')
plt.plot([4, 6, 8], color='blue', label='line two')
plt.legend()
plt.show()

相关问题 更多 >