python - matplotlib 图例 : Including markers and lines from two different graphs in one line

标签 python matplotlib legend

我一直在做一些线性回归,想在图例中的同一条线上绘制标记(原始数据)和线(回归)。为简单起见,这里有一个假的回归:

from pylab import *
ax = subplot(1,1,1)
p1, = ax.plot([1,2,3,4,5,6],'r-', label="line 1")
p2, = ax.plot([6,5,4,3,2,1],'b-', label="line 2")

p3, = ax.plot([1.2,1.8,3.1,4.1,4.8,5.9],'ro', label="dots 1")
p4, = ax.plot([6.1,5.1,3.8,3.1,1.9,0.9],'bo', label="dots 2")

ax.legend(loc='center right',numpoints=1)
show()

所以我希望图例由 2 行组成,每行显示一条线和一个点,而不是 4 行。我该怎么做?

最佳答案

你只需要更直接地使用legend。参见 Matplotlib - How to make the marker face color transparent without making the line transparentuser guide .

ax.legend([(p1, p3), (p2, p4)], ['set 1', 'set 2'])
plt.draw()

关于python - matplotlib 图例 : Including markers and lines from two different graphs in one line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21624818/

相关文章:

python - Pinax 如何添加新页面?

python - 将 python 结果返回到 html

r - 如何在 ggplot2 中分割图例

r - 将带有指数的数字转换为 R 中美丽图例的绘图命令

python - 图例中的额外标记

python Mechanize 没有正确解析表单

python - 在 Python 中使用 setattr() 向字典添加键

python - 从一个文件的提取内容创建文件

python - plt.show() 第二次使用时什么都不做

python - 如何在右侧绘制 yticks 并保留经典的左侧