如何在 matplotlib 中制作自定义图例 [英] How to make custom legend in matplotlib

查看:56
本文介绍了如何在 matplotlib 中制作自定义图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前以这种方式使用 matplotlib 生成我的图例:

I currently generate my legend with matplotlib this way:

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.但是我的图例中有重复的信息.

Which somehow works see 1. But I have duplicated information in my legend.

我更愿意将图例分开.这样我就有了对应于时间 t 的不同颜色的线.一条法线作为我的分析解决方案,一个点代表我的模拟结果.

I would prefer to seperate the legend. So that I have different colored lines corresponding to the time t. And a normal line as my Analytical solution an dots for the results of my simulation.

类似的东西

--(红线)t = 25

--(red line) t = 25

--(蓝线)t = 50

--(blue line) t = 50

--(绿线)t = 500

--(green line) t = 500

o 模拟

-- 解析解

现在有人知道我如何使用 matplotlib 实现这一目标吗?

Does anyone now how I could achieve this with matplotlib?

推荐答案

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

You can chose the artists and labels to display in the legend as follows. You'll need to create custom artists for the elements in the legend that are not actually plotted.

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()

这篇关于如何在 matplotlib 中制作自定义图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆