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

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

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

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


当前回答

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

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

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

(或更短:)

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

这有点棘手:

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

其他回答

我完全同意Huster教授的观点,即最简单的方法是改变图形的大小,这样可以保持默认字体。我只需要在将图形保存为pdf时使用bbox_inches选项来补充这一点,因为轴标签被剪切了。

import matplotlib.pyplot as plt
plt.figure(figsize=(4,3))
plt.savefig('Basic.pdf', bbox_inches='tight')

基于以上内容:

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

fontPath = "/usr/share/fonts/abc.ttf"
font = fm.FontProperties(fname=fontPath, size=10)
font2 = fm.FontProperties(fname=fontPath, size=24)

fig = plt.figure(figsize=(32, 24))
fig.text(0.5, 0.93, "This is my Title", horizontalalignment='center', fontproperties=font2)

plot = fig.add_subplot(1, 1, 1)

plot.xaxis.get_label().set_fontproperties(font)
plot.yaxis.get_label().set_fontproperties(font)
plot.legend(loc='upper right', prop=font)

for label in (plot.get_xticklabels() + plot.get_yticklabels()):
    label.set_fontproperties(font)

如果你像我一样是一个控制狂,你可能需要明确设置所有字体大小:

import matplotlib.pyplot as plt

SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 12

plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE)  # fontsize of the figure title

注意,您还可以在matplotlib上设置调用rc方法的大小:

import matplotlib

SMALL_SIZE = 8
matplotlib.rc('font', size=SMALL_SIZE)
matplotlib.rc('axes', titlesize=SMALL_SIZE)

# and so on ...

从matplotlib文档中,

font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 22}

matplotlib.rc('font', **font)

这将所有项目的字体设置为kwargs对象font指定的字体。

或者,您也可以使用rcParams更新方法,如以下答案所示:

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

or

import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 22})

您可以在Customizing matplotlib页面上找到可用财产的完整列表。

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

更改图形大小!

我通常使用这样的代码:

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(美国模特教师协会)论坛的帖子中了解到这一点。上述代码示例: