如何更改matplotlib绘图上所有元素(记号、标签、标题)的字体大小?

我知道如何更改勾号标签大小,这是通过以下方式完成的:

import matplotlib 
matplotlib.rc('xtick', labelsize=20) 
matplotlib.rc('ytick', labelsize=20) 

但一个人如何改变其他人呢?


当前回答

这里有一种完全不同的方法,可以非常好地改变字体大小:

更改图形大小!

我通常使用这样的代码:

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
x = np.linspace(0,6.28,21)
ax.plot(x, np.sin(x), '-^', label="1 Hz")
ax.set_title("Oscillator Output")
ax.set_xlabel("Time (s)")
ax.set_ylabel("Output (V)")
ax.grid(True)
ax.legend(loc=1)
fig.savefig('Basic.png', dpi=300)

图形尺寸越小,字体相对于绘图就越大。这也会放大标记。注意,我还设置了dpi或每英寸点数。我从AMTA(美国模特教师协会)论坛的帖子中了解到这一点。上述代码示例:

其他回答

您可以使用plt.rcParams[“font.size”]在matplotlib中设置font_size,也可以使用plt.rcParams[“font-family”]在matplotlib设置font_family。请尝试以下示例:

import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')

label = [1,2,3,4,5,6,7,8]
x = [0.001906,0.000571308,0.0020305,0.0037422,0.0047095,0.000846667,0.000819,0.000907]
y = [0.2943301,0.047778308,0.048003167,0.1770876,0.532489833,0.024611333,0.157498667,0.0272095]


plt.ylabel('eigen centrality')
plt.xlabel('betweenness centrality')
plt.text(0.001906, 0.2943301, '1 ', ha='right', va='center')
plt.text(0.000571308, 0.047778308, '2 ', ha='right', va='center')
plt.text(0.0020305, 0.048003167, '3 ', ha='right', va='center')
plt.text(0.0037422, 0.1770876, '4 ', ha='right', va='center')
plt.text(0.0047095, 0.532489833, '5 ', ha='right', va='center')
plt.text(0.000846667, 0.024611333, '6 ', ha='right', va='center')
plt.text(0.000819, 0.157498667, '7 ', ha='right', va='center')
plt.text(0.000907, 0.0272095, '8 ', ha='right', va='center')
plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams["font.size"] = "50"
plt.plot(x, y, 'o', color='blue')

评论中提到了这一点,但值得自己回答:

同时修改figsize=和dpi=以调整图形大小和所有文本标签的比例:

fig, ax = plt.subplots(1, 1, figsize=(8, 4), dpi=100)

(或更短:)

fig, ax = plt.subplots(figsize=(8, 4), dpi=100)

这有点棘手:

figsize实际上控制了文本相对于绘图范围的比例(以及绘图的纵横比)。dpi调整笔记本中图形的大小(保持文本的相对比例和绘图纵横比不变)。

matplotlib.rcParams.update({'font.size': 22})

对rcParams的更改是非常精细的,大多数时候,您只需要缩放所有字体大小,以便在您的图形中更好地看到它们。图形大小是一个很好的技巧,但您必须为所有图形携带它。另一种方法(不是纯粹的matplotlib,或者如果你不使用seaborn,可能会过度使用)是用seaborn设置字体比例:

sns.set_context('paper', font_scale=1.4)

免责声明:我知道,如果你只使用matplotlib,那么你可能不想安装一个完整的模块来缩放你的绘图(我的意思是为什么不),或者如果你使用seaborn,那么你对选项有更多的控制权。但有一种情况是,您的数据科学虚拟环境中有seaborn,但在本笔记本中没有使用它。无论如何,还有另一个解决方案。

这里有一种完全不同的方法,可以非常好地改变字体大小:

更改图形大小!

我通常使用这样的代码:

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
x = np.linspace(0,6.28,21)
ax.plot(x, np.sin(x), '-^', label="1 Hz")
ax.set_title("Oscillator Output")
ax.set_xlabel("Time (s)")
ax.set_ylabel("Output (V)")
ax.grid(True)
ax.legend(loc=1)
fig.savefig('Basic.png', dpi=300)

图形尺寸越小,字体相对于绘图就越大。这也会放大标记。注意,我还设置了dpi或每英寸点数。我从AMTA(美国模特教师协会)论坛的帖子中了解到这一点。上述代码示例: