使用一个 `plot` 调用绘制多条曲线时的一个图例条目 [英] One legend entry when plotting several curves using one `plot` call
问题描述
我正在通过使用一个 plot
调用绘制多条曲线来创建网格:
I am creating a grid by plotting several curves using one plot
call as:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.array([[0,1], [0,1], [0,1]])
y = np.array([[0,0], [1,1], [2,2]])
ax.plot([0,1],[0,2], label='foo', color='b')
ax.plot(x.T, y.T, label='bar', color='k')
ax.legend()
plt.show()
生成的图例具有与曲线一样多的条"条目(请参见下文).我希望每个 plot
调用只有一个图例条目(在这种情况下,只有一个"bar").
The resulting legend has as many 'bar' entries as there are curves (see below). I wish that have only one legend entry per plot
call (in this case only one time 'bar').
我想要这样我可以有其他绘图命令(例如绘制foo"曲线的命令),如果它们有标签,它们的曲线自动包含在图例中.我特别想避免在构建图例时手动选择手柄,而是使用matplotlib的功能通过在绘制时通过是/否包括标签来处理此问题.我该如何实现?
I want this such that I can have other plot commands (e.g. the one plotting the 'foo' curve) whose curves are automatically included in the legend if they have a label. I specifically want to avoid hand-selecting the handles when constructing the legend, but rather use matplotlib's feature to deal with this by yes/no including a label when plotting. How can I achieve this?
推荐答案
这里是一种可能的解决方案:您可以使用下划线不会产生图例条目的事实.因此,将除第一个标签以外的所有标签设置为 "_"
会抑制这些标签出现在图例中.
Here is one possible solution: You may use the fact that underscores do not produce legend entries. So setting all but the first label to "_"
suppresses those to appear in the legend.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.array([[0,1], [0,1], [0,1]])
y = np.array([[0,0], [1,1], [2,2]])
ax.plot([0,1],[0,2], label='foo', color='b')
lines = ax.plot(x.T, y.T, label='bar', color='k')
plt.setp(lines[1:], label="_")
ax.legend()
plt.show()
这篇关于使用一个 `plot` 调用绘制多条曲线时的一个图例条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!