How to change legend size with matplotlib.pyplot
这里的问题很简单:我正在尝试使用
1 2 3 4 5 6 | plot.figure() plot.scatter(k, sum_cf, color='black', label='Sum of Cause Fractions') plot.scatter(k, data[:, 0], color='b', label='Dis 1: cf = .6, var = .2') plot.scatter(k, data[:, 1], color='r', label='Dis 2: cf = .2, var = .1') plot.scatter(k, data[:, 2], color='g', label='Dis 3: cf = .1, var = .01') plot.legend(loc=2) |
您可以通过调整
1 | plot.legend(loc=2, prop={'size': 6}) |
这将使用与
Keyword arguments:
1
2
3
4 prop: [ None | FontProperties | dict ]
A matplotlib.font_manager.FontProperties instance. If prop is a
dictionary, a new instance will be created with prop. If None, use
rc settings.
从1.2.1版开始,也可以使用关键字
这应该做
1 2 3 4 | import pylab as plot params = {'legend.fontsize': 20, 'legend.handlelength': 2} plot.rcParams.update(params) |
然后再做图。
还有很多其他rcParam,它们也可以在matplotlibrc文件中设置。
大概也可以通过
除了点的大小,还有一些命名的fontsizes:
1 2 3 4 5 6 7 | xx-small x-small small medium large x-large xx-large |
用法:
1 | pyplot.legend(loc=2, fontsize = 'x-small') |
使用
方法1:调用图例时指定字体大小(重复)
1 2 | plt.legend(fontsize=20) # using a size in points plt.legend(fontsize="x-large") # using a named size |
使用此方法,可以在创建时为每个图例设置字体大小(允许您拥有多个具有不同字体大小的图例)。但是,每次创建图例时,都必须手动键入所有内容。
(注意:@ Mathias711在他的答案中列出了可用的命名字体大小)
方法2:在rcParams中指定字体大小(方便)
1 2 | plt.rc('legend',fontsize=20) # using a size in points plt.rc('legend',fontsize='medium') # using a named size |
使用此方法可以设置默认的图例字体大小,除非使用方法1另行指定,否则所有图例将自动使用该图例。这意味着您可以在代码开头设置图例字体大小,而不必担心为每个图例设置它。
如果您使用命名尺寸,例如
有多种设置可用于调整图例大小。我发现最有用的两个是:
-
labelspacing:以字体大小的倍数设置标签条目之间的间距。例如,使用10点字体,
legend(..., labelspacing=0.2) 会将条目之间的间距减小到2点。我安装的默认值约为0.5。 -
prop:可以完全控制字体大小等。您可以使用
legend(..., prop={'size':8}) 设置8点字体。我安装的默认值约为14点。
此外,图例文档还列出了许多其他填充和间距参数,包括:
也可以使用matplotlibrc文件将这些值设置为所有图形的默认值。
在我的安装中,FontProperties仅更改文本大小,但它仍然太大且隔开。我在
1 | pyplot.rcParams.update({'legend.labelspacing':0.25}) |
我不确定如何将其指定给pyplot.legend函数-传递
1 | prop={'labelspacing':0.25} |
要么
1 | prop={'legend.labelspacing':0.25} |
返回错误。