matplotlib legend: Including markers and lines from two different graphs in one line

我只是一个虾纸丫 提交于 2019-11-28 07:52:51

问题


I've been doing some linear regression and want to plot the markers (original data) and the lines (regression) on the same line in the legend. For simplicity, here's a fake regression:

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()

So I want the legend to consist of 2 lines, each showing a line and a dot, instead of 4 lines. How can I do that?


回答1:


You just need to use legend a bit more directly. See Matplotlib - How to make the marker face color transparent without making the line transparent and user guide.

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



回答2:


You can just try with

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

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

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

or if you want a poor man's solution, you can plot something outside your plotting range and label only that plot. For instance

p5 = ax.plot(ones(2)*1e6,ones(2)*1e6,'r-o', label="dots 1")

do the same for the other label and then force your plot not to include p5, for example, like this

ax.set_xlim(0,10);ax.set_ylim(0,10)



回答3:


I usually solve this problem by creating dummy lines with the plot properties that I am interested in showing. However, I think @tcaswell's solution is better.

from matplotlib.lines import Line2D

def create_dummy_line(**kwds):
    return Line2D([], [], **kwds)

# your code here

# Create the legend
lines = [
    ('name A', {'color': 'red', 'linestyle': '-', 'marker': 'o'}),
    ('name B', {'color': 'blue', 'linestyle': '-', 'marker': 'o'}),
]
ax.legend(
    # Line handles
    [create_dummy_line(**l[1]) for l in lines],
    # Line titles
    [l[0] for l in lines],
    loc='center right'
)


来源:https://stackoverflow.com/questions/21624818/matplotlib-legend-including-markers-and-lines-from-two-different-graphs-in-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!