【问题标题】:How to change fontsize of individual legend entries in pyplot?如何更改 pyplot 中单个图例条目的字体大小?
【发布时间】:2015-10-18 01:25:35
【问题描述】:

我想要做的是控制 pyplot 中图例中各个条目的字体大小。也就是说,我希望第一个条目是一个大小,第二个条目是另一个。这是我尝试的解决方案,但不起作用。

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1,5,0.5)
plt.figure(1)
plt.plot(x,x,label='Curve 1')
plt.plot(x,2*x,label='Curve 2')
leg = plt.legend(loc = 0, fontsize = 'small')
leg.get_texts()[0].set_fontsize('medium')
plt.show()

我的期望是所有图例条目的默认大小都是“小”。然后我得到一个 Text 对象的列表,并将仅单个 Text 对象的字体大小更改为 medium。但是,由于某种原因,这会将所有 Text 对象的字体大小更改为中等,而不仅仅是我实际更改的单个字体。我觉得这很奇怪,因为我可以以这种方式单独设置其他属性,例如文本颜色。

最终,我只需要一些方法来更改单个条目的图例字体大小。

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

    如果您为绘图中的文本渲染激活 LaTeX,则可以使用更简单的方法。您可以毫不费力地实现这一目标,在“导入”之后使用额外的命令行:

    plt.rc('text', usetex=True)
    

    现在您可以通过在要使用 LaTeX 处理的字符串的开头指定 r 来更改任何特定字符串的大小,并在其中添加所需的 size command for LaTeX\small, \Large, \Huge, 等)。 例如:

    r'\Large Curve 1'
    

    查看您修改后的代码。只做了很小的改动!

    import numpy as np
    import matplotlib.pyplot as plt
    
    plt.rc('text', usetex=True) #Added LaTeX processing
    
    x = np.arange(1,5,0.5)
    plt.figure(1)
    #Added LaTeX size commands on the formatted String
    plt.plot(x,x,label=r'\Large Curve 1')
    plt.plot(x,2*x,label=r'\Huge Curve 2')
    plt.legend(loc = 0, fontsize = 'small')
    #leg.get_texts()[0].set_fontsize('medium')
    plt.show()
    

    所以你得到了这个:

    【讨论】:

      【解决方案2】:

      似乎每个图例条目的字体由matplotlib.font_manager.FontProperties 的实例管理。问题是:每个条目都没有自己的FontProperties...它们都共享同一个。这是通过写作来验证的:

      >>> t1, t2 = leg.get_texts()
      >>> t1.get_fontproperties() is t2.get_fontproperties()
      True
      

      所以如果你改变了第一个条目的大小,第二个条目的大小也会随之自动改变。

      解决此问题的“技巧”是为每个图例条目创建一个独特的 FontProperties 实例:

      x = np.arange(1,5,0.5)
      plt.figure(1)
      plt.plot(x,x,label='Curve 1')
      plt.plot(x,2*x,label='Curve 2')
      leg = plt.legend(loc = 0, fontsize = 'small')
      
      t1, t2 = leg.get_texts()
      # here we create the distinct instance
      t1._fontproperties = t2._fontproperties.copy()
      t1.set_size('medium')
      
      plt.show()
      

      现在大小是正确的:

      【讨论】:

      • 不确定何时添加,但这也适用于我(matplotlib 1.5.3):t1.set_fontproperties(t1.get_fontproperties())。这样做的好处是不依赖于受保护的文本属性(即_fontproperties)。请注意,即使您将 FontProperties 分配给您从中获取它们的同一对象(在这种情况下为t1),它仍然会在内部进行复制。另见this
      猜你喜欢
      • 2016-08-18
      • 2011-10-28
      • 2018-09-06
      • 2021-07-19
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      相关资源
      最近更新 更多