Python 如何设置Matplotlib轴图例的字体大小?

Python 如何设置Matplotlib轴图例的字体大小?,python,matplotlib,font-size,legend,Python,Matplotlib,Font Size,Legend,我有这样一个代码: import matplotlib.pyplot as plt from matplotlib.pyplot import * from matplotlib.font_manager import FontProperties fontP = FontProperties() fontP.set_size('xx-small') fig=plt.figure() ax1=fig.add_subplot(111) plot([1,2,3], label="test1") a

我有这样一个代码:

import matplotlib.pyplot as plt
from matplotlib.pyplot import *
from matplotlib.font_manager import FontProperties

fontP = FontProperties()
fontP.set_size('xx-small')
fig=plt.figure()
ax1=fig.add_subplot(111)
plot([1,2,3], label="test1")
ax1.legend(loc=0, ncol=1, bbox_to_anchor=(0, 0, 1, 1),
           prop = fontP,fancybox=True,shadow=False,title='LEGEND')
plt.show()

从图中可以看出,Fontsize中的设置不影响图例标题字体大小


如何将图例标题的字体大小设置为较小的大小?

我不知道如何为单个绘图设置字体大小,但我总是全局设置:

plt.rc('legend',**{'fontsize':6})

我通常是这样做的。一旦绘图完成,我将执行以下操作

plt.legend(loc=0, numpoints=1)
leg = plt.gca().get_legend()
ltext  = leg.get_texts()
plt.setp(ltext, fontsize='small') 

我不知道这是否适用于您

以下是如何更改图例列表和/或图例标题的字体大小:

legend=plt.legend(list,loc=(1.05,0.05), title=r'$\bf{Title}$') #Legend: list, location, Title (in bold)
legend.get_title().set_fontsize('6') #legend 'Title' fontsize
plt.setp(plt.gca().get_legend().get_texts(), fontsize='12') #legend 'list' fontsize

这肯定是一个老问题,但也让我感到沮丧,其他答案根本没有改变图例标题fontsize,而是改变了文本的其余部分。因此,在我的头撞上matplotlib文档一段时间后,我想到了这个

legend = ax1.legend(loc=0, ncol=1, bbox_to_anchor=(0, 0, 1, 1),
           prop = fontP,fancybox=True,shadow=False,title='LEGEND')

plt.setp(legend.get_title(),fontsize='xx-small')
从Matplotlib 3.0.3开始,还可以使用全局设置

plt.rcParams['legend.title_fontsize'] = 'xx-small'
这是最快的:

plt.legend(loc=2,prop={'size':6})

我的头也撞到了它,下面是另一种更流畅的方式:

leg = ax.legend()
leg.set_title('A great legend',prop={'size':14})

受当前顶级答案的启发,我找到了一种稍微自然一点的方法来更改图例中的字体大小。
fontsize
参数设置每个数据标签的字体大小,
title\u fontsize
参数设置标题的字体大小(如果为图例提供标题)

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0,1,2],[2,1,2],label='test_data (fs=12)')
ax.legend(fontsize=12, title='TITLE (fs=30)',title_fontsize=30)
给出这样一个数字:

现在是2021年,使用matplotlib 3.4.2,您可以使用

plt.legend(title="My Title", fontsize=10, title_fontsize=15)

其中,
fontsize
是图例中项目的字体大小,
title\u fontsize
是图例标题的字体大小。更多信息请参见

在ipython笔记本中,我只需执行setp(gca().get_legend().get_Text(),fontsize='small')。您能帮我将您提出的代码与我的合并吗?当我把这段代码添加到我的代码中时,我看到了一些错误。具体来说:回溯(最近一次调用last):在legend=plt.legend(list,loc=(1.05,0.05),title=r'$\bf{title}$)#legend:list,location,title(粗体)文件“C:\Python26\Lib\site packages\matplotlib\pyplot.py”,第2800行,在legend ret=gca()中。legend(*args,**kwargs)文件“C:\Python26\Lib\site packages\matplotlib\matplotlib\axes\axes.py”,第4494行,图例标签中)]TypeError:zip参数#2必须支持迭代我注意到这些命令在使用IPython控制台的Spyder中不起作用,但在标准python(v2.7)控制台中效果很好。在IPython中,它给出了“NameError:name'gca'未定义”。就我所知,这是所有选项中最干净的一个。不幸的是,这个选项没有改变标题大小。这应该是更新(2021)的首要答案,请参阅