matplotlib 如何制作自定义图例

k0pti3hp  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(119)

我现在用matplotlib这样生成我的图例:

if t==25:
    l1,l2 = ax2.plot(x320,vTemp320,'or',x320,vAnaTemp320,'-r')
elif t==50:
    l3,l4 = ax2.plot(x320,vTemp320,'ob',x320,vAnaTemp320,'-b')
else:
    l5,l6 = ax2.plot(x320,vTemp320,'og',x320,vAnaTemp320,'-g')
plt.legend((l1,l2,l3,l4,l5,l6), ('t=25 Simulation', 't=25 Analytical','t=50 Simulation', 't=50 Analytical','t=500 Simulation', 't=500 Analytical'),
   bbox_to_anchor=(-.25, 1), loc=2, borderaxespad=0.,prop={'size':12})

但我在图例中重复了信息。
我更喜欢把图例分开,这样我就有不同颜色的线对应于时间t,一条正常的线作为我的分析解,一个点作为我的模拟结果。
类似的东西
--(红线)t = 25
--(蓝线)t = 50
--(绿色线)t = 500
o模拟
--分析解决方案
有没有人知道我如何用matplotlib实现这一点?

u4dcyp6a

u4dcyp6a1#

您可以选择要在图例中显示的艺术家和标签,如下所示。您需要为图例中实际上未打印的元素创建自定义艺术家。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,10,31)

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

#Plot analytic solution
ax.plot(x,1*x**2, color='r', label="t = 25")
ax.plot(x,2*x**2, color='b', label="t = 50")
ax.plot(x,3*x**2, color='g', label="t = 500")

#Plot simulation
ax.plot(x,1*x**2, color='r', linestyle='', marker='o')
ax.plot(x,2*x**2, color='b', linestyle='', marker='o')
ax.plot(x,3*x**2, color='g', linestyle='', marker='o')

#Get artists and labels for legend and chose which ones to display
handles, labels = ax.get_legend_handles_labels()
display = (0,1,2)

#Create custom artists
simArtist = plt.Line2D((0,1),(0,0), color='k', marker='o', linestyle='')
anyArtist = plt.Line2D((0,1),(0,0), color='k')

#Create legend from custom artist/label lists
ax.legend([handle for i,handle in enumerate(handles) if i in display]+[simArtist,anyArtist],
          [label for i,label in enumerate(labels) if i in display]+['Simulation', 'Analytic'])

plt.show()

相关问题