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()
编辑
要添加两个修补程序,可以执行以下操作:
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])
这里有一个解决方案,让您控制图例线的宽度和样式(在a lot of other things之间)。
更多选项,请看这个matplotlib gallery sample。
你检查过Legend Guide了吗?
为了实用,我引用了guide中的示例。
编辑
要添加两个修补程序,可以执行以下操作:
我添加了一些代码来构建来自https://stackoverflow.com/users/2029132/gabra的答案和来自https://stackoverflow.com/users/5946578/brady-forcier的注释。在这里,我通过a'for'循环手动向图例添加元素。
首先,我创建了一本字典,里面有我的传奇名字和想要的颜色。我实际上是在加载数据时这样做的,但这里我只是明确定义:
然后我循环遍历字典,并为每个条目定义一个补丁并附加到一个列表“patch list”。然后我用这个列表来创建我的传奇。
这是我的输出:
我不担心图例条目是按特定顺序排列的,但是您可以通过
这是我的第一个回答,因此,对于任何错误/失礼,请提前道歉。
相关问题 更多 >
编程相关推荐