【问题标题】:matplotlib legend: Including markers and lines from two different graphs in one linematplotlib 图例:在一行中包含来自两个不同图形的标记和线条
【发布时间】:2014-02-07 10:10:10
【问题描述】:

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

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 行。我该怎么做?

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

    您只需要更直接地使用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()
    

    【讨论】:

      【解决方案2】:

      你可以试试

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

      或者如果你想要一个穷人的解决方案,你可以在你的绘图范围之外绘制一些东西并只标记那个图。 比如

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

      对另一个标签做同样的事情,然后强制你的情节不包括p5,例如,像这样

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

      【讨论】:

        【解决方案3】:

        我通常通过使用我感兴趣的绘图属性创建虚拟线来解决这个问题。不过,我认为@tcaswell 的解决方案更好。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-10-16
          • 2018-02-15
          • 1970-01-01
          • 2019-05-07
          • 1970-01-01
          • 2012-07-10
          • 2020-07-25
          相关资源
          最近更新 更多