如何手动创建图例 [英] How to manually create a legend
问题描述
我正在使用 matlibplot,我想手动向图例添加颜色和标签的项目.我正在向图中添加数据以指定会导致大量重复.
我的想法是:
ax2.legend(self.labels,colorList[:len(self.labels)])plt.legend()
其中 self.labels 是我想要图例标签的项目数量,它需要大颜色列表的一个子集.然而,当我运行它时,这没有任何结果.
我错过了什么吗?
谢谢
您是否检查了
编辑
要添加两个补丁,您可以这样做:
import matplotlib.patches 作为 mpatches导入 matplotlib.pyplot 作为 pltred_patch = mpatches.Patch(color='red', label='红色数据')blue_patch = mpatches.Patch(color='blue', label='蓝色数据')plt.legend(handles=[red_patch, blue_patch])
I am using matlibplot and I would like to manually add items to the legend that are a color and a label. I am adding data to to the plot to specifying there would lead to a lot of duplicates.
My thought was to do:
ax2.legend(self.labels,colorList[:len(self.labels)])
plt.legend()
Where self.labels is the number of items I want legend lables for that takes a subset of the large color list. However this yields nothing when I run it.
Am I missing anything?
Thanks
Have you checked the Legend Guide?
For practicality, I quote the example from the guide.
Not all handles can be turned into legend entries automatically, so it is often necessary to create an artist which can. Legend handles don’t have to exists on the Figure or Axes in order to be used.
Suppose we wanted to create a legend which has an entry for some data which is represented by a red color:
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])
plt.show()
Edit
To add two patches you can do this:
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
red_patch = mpatches.Patch(color='red', label='The red data')
blue_patch = mpatches.Patch(color='blue', label='The blue data')
plt.legend(handles=[red_patch, blue_patch])
这篇关于如何手动创建图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!