问题描述
我正在尝试使用以下代码段将图例添加到我的情节中:
I am trying to add the legend to my plot with this snippet:
import matplotlib.pylab as plt
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
axes.set_xlabel('x (m)')
axes.set_ylabel('y (m)')
for i, representative in enumerate(representatives):
axes.plot([e[0] for e in representative], [e[1] for e in representative], color='b', label='Representatives')
axes.scatter([e[0] for e in intersections], [e[1] for e in intersections], color='r', label='Intersections')
axes.legend()
我以这个情节结束
显然,图中的项目是重复的.如何更正此错误?
Obviously, the items are duplicated in the plot. How can I correct this error?
推荐答案
正如 docs 所说,虽然很容易错过:
As the docs say, although it's easy to miss:
如果 label 属性为空字符串或以_"开头,则这些艺术家将被忽略.
If label attribute is empty string or starts with "_", those artists will be ignored.
因此,如果我在循环中绘制类似的线条并且我只想要图例中的一个示例线条,我通常会执行类似的操作
So if I'm plotting similar lines in a loop and I only want one example line in the legend, I usually do something like
ax.plot(x, y, label="Representatives" if i == 0 else "")
其中 i
是我的循环索引.
where i
is my loop index.
单独构建它们看起来不太好,但我经常希望使标签逻辑尽可能接近线条图.
It's not quite as nice to look at as building them separately, but often I want to keep the label logic as close to the line drawing as possible.
(请注意,matplotlib
开发人员自己倾向于使用 "_nolegend_"
来表示明确.)
(Note that the matplotlib
developers themselves tend to use "_nolegend_"
to be explicit.)
这篇关于matplotlib 中图例中的重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2