如何更改matplotlib绘图上所有元素(记号、标签、标题)的字体大小?
我知道如何更改勾号标签大小,这是通过以下方式完成的:
import matplotlib
matplotlib.rc('xtick', labelsize=20)
matplotlib.rc('ytick', labelsize=20)
但一个人如何改变其他人呢?
如何更改matplotlib绘图上所有元素(记号、标签、标题)的字体大小?
我知道如何更改勾号标签大小,这是通过以下方式完成的:
import matplotlib
matplotlib.rc('xtick', labelsize=20)
matplotlib.rc('ytick', labelsize=20)
但一个人如何改变其他人呢?
当前回答
这是马里乌斯·雷特根回答的延伸。您可以使用所有修改创建一个单独的JSON文件,然后使用rcParams.update加载它。这些更改仅适用于当前脚本。所以
import json
from matplotlib import pyplot as plt, rcParams
s = json.load(open("example_file.json")
rcParams.update(s)
并将此“example_file.json”保存在同一文件夹中。
{
"lines.linewidth": 2.0,
"axes.edgecolor": "#bcbcbc",
"patch.linewidth": 0.5,
"legend.fancybox": true,
"axes.color_cycle": [
"#348ABD",
"#A60628",
"#7A68A6",
"#467821",
"#CF4457",
"#188487",
"#E24A33"
],
"axes.facecolor": "#eeeeee",
"axes.labelsize": "large",
"axes.grid": true,
"patch.edgecolor": "#eeeeee",
"axes.titlesize": "x-large",
"svg.fonttype": "path",
"examples.directory": ""
}
其他回答
matplotlib.rcParams.update({'font.size': 22})
我通过@ryggyr编写了一个修改版本的答案,它允许对单个参数进行更多控制,并在多个子地块上工作:
def set_fontsizes(axes,size,title=np.nan,xlabel=np.nan,ylabel=np.nan,xticks=np.nan,yticks=np.nan):
if type(axes) != 'numpy.ndarray':
axes=np.array([axes])
options = [title,xlabel,ylabel,xticks,yticks]
for i in range(len(options)):
if np.isnan(options[i]):
options[i]=size
title,xlabel,ylabel,xticks,yticks=options
for ax in axes.flatten():
ax.title.set_fontsize(title)
ax.xaxis.label.set_size(xlabel)
ax.yaxis.label.set_size(ylabel)
ax.tick_params(axis='x', labelsize=xticks)
ax.tick_params(axis='y', labelsize=yticks)
对rcParams的更改是非常精细的,大多数时候,您只需要缩放所有字体大小,以便在您的图形中更好地看到它们。图形大小是一个很好的技巧,但您必须为所有图形携带它。另一种方法(不是纯粹的matplotlib,或者如果你不使用seaborn,可能会过度使用)是用seaborn设置字体比例:
sns.set_context('paper', font_scale=1.4)
免责声明:我知道,如果你只使用matplotlib,那么你可能不想安装一个完整的模块来缩放你的绘图(我的意思是为什么不),或者如果你使用seaborn,那么你对选项有更多的控制权。但有一种情况是,您的数据科学虚拟环境中有seaborn,但在本笔记本中没有使用它。无论如何,还有另一个解决方案。
这是马里乌斯·雷特根回答的延伸。您可以使用所有修改创建一个单独的JSON文件,然后使用rcParams.update加载它。这些更改仅适用于当前脚本。所以
import json
from matplotlib import pyplot as plt, rcParams
s = json.load(open("example_file.json")
rcParams.update(s)
并将此“example_file.json”保存在同一文件夹中。
{
"lines.linewidth": 2.0,
"axes.edgecolor": "#bcbcbc",
"patch.linewidth": 0.5,
"legend.fancybox": true,
"axes.color_cycle": [
"#348ABD",
"#A60628",
"#7A68A6",
"#467821",
"#CF4457",
"#188487",
"#E24A33"
],
"axes.facecolor": "#eeeeee",
"axes.labelsize": "large",
"axes.grid": true,
"patch.edgecolor": "#eeeeee",
"axes.titlesize": "x-large",
"svg.fonttype": "path",
"examples.directory": ""
}
使用plt.tick_params(labelsize=14)