为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Matplotlib中制作自定义图例

如何在Matplotlib中制作自定义图例

绝地无双 2019-12-26 10:53:55
我目前以这种方式使用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 = 500o Simulaton-分析解决方案现在有人可以使用matplotlib实现此目标吗?
查看完整描述

1 回答

?
开心每一天1111

TA贡献1836条经验 获得超13个赞

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


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


查看完整回答
反对 回复 2019-12-26
  • 1 回答
  • 0 关注
  • 685 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信