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

后端 未结 3 1174
难免孤独
难免孤独 2020-12-20 20:56

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 fak

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-20 21:57

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

提交回复
热议问题