如何制作自定义图例

50

我目前是通过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})

一些方法可行,参见1。但我图例中有重复信息。
我希望将图例分开。所以我需要不同颜色的线对应于时间t。并且普通线作为我的解析解,并且用点来表示模拟结果。
类似于:
-- (红线) t = 25
-- (蓝线) t = 50
-- (绿线) t = 500
o 模拟结果
-- 解析解
请问有人知道我如何在matplotlib中实现这个?
当前图像如下:The current image
2个回答

90
您可以按照以下方式选择要在图例中显示的艺术家和标签。对于实际上没有绘制的图例元素,您需要创建自定义艺术家。请注意保留HTML标记。
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()

Example plot


2
这可能是一个英语语言问题,但是你所说的“artist”是什么意思? - LWZ
1
@Mr.Squig. 模块artist,类Artist. - Mad Physicist
现在使用多个点创建图例条目的方法已经不再适用了。一种解决方案是通过括号将多个Line2D艺术家分组(Line2D((0),(0)...), Line2D((1),(0),... ),然后使用handler_map={tuple: HandlerTuple(ndivide=None)}。更多信息请参见:https://matplotlib.org/stable/gallery/text_labels_and_annotations/legend_demo.html - lyinch

0
您可以在legend()函数中传递句柄和标签来创建自定义图例;您可以传递任何Line2DPathCollection等对象,并将它们作为句柄传递,并按您喜欢的方式进行标记。这些句柄甚至不必与原始子图有关,因此可以从头开始创建。
以下是一个工作示例:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

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

fig, ax = plt.subplots()
ax.plot(x, 1*x**2, 'ro-')
ax.plot(x, 2*x**2, 'bo-')
ax.plot(x, 3*x**2, 'go-')

# list of proxy artists
handles = [Line2D([0], [0], c='r'), Line2D([0], [0], c='b'), Line2D([0], [0], c='g'), 
           Line2D([0], [0], c='k'), Line2D([0], [0], c='k', marker='o', linestyle='')]
# its labels
labels = ["t = 25", "t = 50", "t = 500", 'Simulation', 'Analytic']
ax.legend(handles, labels);

result


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接