【问题标题】:Draw points and lines in legend text?在图例文本中绘制点和线?
【发布时间】:2012-11-14 15:43:02
【问题描述】:

是否有可能将线条和点放入 matplotlib 中的图例文本中? 我有类似以下的想法

x=np.linspace(0,10,100)
ys=np.sin(x)
yc=np.cos(x)
pl.plot(x,ys,'--',label='sin')
pl.plot(x,yc,':',label='derivative of --')
pl.legend()
pl.show()

除了 -- 应该有相同的符号和相应的颜色,就像在图例标签 sin 前面一样。

【问题讨论】:

    标签: matplotlib legend


    【解决方案1】:

    在阅读了 matplotlib 源代码之后,我终于找到了一个非常适合我的解决方案,并且不需要任何位置调整等,因为它使用了 matplotlibs 内部 V- 和 HPackers。

    import numpy as np
    import pylab as pl
    
    x=np.linspace(0,10,100)
    ys=np.sin(x)
    yc=np.cos(x)
    
    pl.plot(x,ys,'--',label='sin')
    pl.plot(x,yc,':',label='derivative of')
    leg=pl.legend()
    
    # let the hacking begin
    legrows = leg.get_children()[0].get_children()[1]\
                 .get_children()[0].get_children()
    symbol  = legrows[0].get_children()[0]
    childs  = legrows[1].get_children().append(symbol)
    
    pl.show()
    

    结果如下:

    【讨论】:

      【解决方案2】:

      这有点小技巧,但它实现了您的目标并以适当的顺序将所有部分(即图例和文本)放置在情节上。

      import pylab
      
      pl.plot(x,ys,'--',label='sin', color='green')
      pl.plot(x,yc,':',label='derivative of --',color='blue')
      line1= pylab.Line2D(range(10), range(10), marker='None', linestyle='--',linewidth=2.0, color="green")
      line2= pylab.Line2D(range(10), range(10), marker='None', linestyle=':',linewidth=2.0, color="blue")
      leg = pl.legend((line1,line2),('sin','derivative of      '),numpoints=1, loc=1)
      pylab.text(9.4, 0.73, '- -', color='green')
      leg.set_zorder(2)
      pl.show()
      

      我没有依赖线条的默认颜色,而是将它们设置为可以在图例中专门引用它们。图例中第二行的“导数”文本中留有额外的空格,因此我们可以将文本(又名sin 行的相应符号/颜色)放在其顶部。然后指定文本的符号/颜色并将其与图例中的文本对齐。最后,您通过zorder 指定将文本设置在顶部的顺序。

      【讨论】:

      • 不幸的是,这个解决方案严重依赖于使用的后端,它需要微调符号位置才能在正确的位置。此外,空间被剥离,例如在 TkAgg 后端没有为符号留下空间。我希望有一个更通用的解决方案。尽管如此,这是一个很好的方法,我将以此作为自己实验的起点。
      • 如果空格被剥离,请通过rc('text', usetex=True)'$\text{sin}$','$\text{derivative of \,\,\,\,\,}$ 使用LaTeX 强制为符号使用空格。
      猜你喜欢
      • 2017-09-11
      • 2016-03-19
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多