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

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

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

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


当前回答

更新:请参阅答案底部,以获得更好的方法。更新#2:我也找到了更改图例标题字体的方法。更新#3:Matplotlib 2.0.0中存在一个错误,导致对数轴的刻度标签恢复为默认字体。应该在2.0.1中修复,但我在答案的第二部分中包含了解决方法。

这个答案适用于任何试图更改所有字体(包括图例)的人,也适用于任何尝试为每件事使用不同字体和大小的人。它不使用rc(这似乎对我不起作用)。这很麻烦,但我个人无法掌握任何其他方法。它基本上结合了ryggyr在这里的答案和SO上的其他答案。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager

# Set the font dictionaries (for plot title and axis titles)
title_font = {'fontname':'Arial', 'size':'16', 'color':'black', 'weight':'normal',
              'verticalalignment':'bottom'} # Bottom vertical alignment for more space
axis_font = {'fontname':'Arial', 'size':'14'}

# Set the font properties (for use in legend)   
font_path = 'C:\Windows\Fonts\Arial.ttf'
font_prop = font_manager.FontProperties(fname=font_path, size=14)

ax = plt.subplot() # Defines ax variable by creating an empty plot

# Set the tick labels font
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontname('Arial')
    label.set_fontsize(13)

x = np.linspace(0, 10)
y = x + np.random.normal(x) # Just simulates some data

plt.plot(x, y, 'b+', label='Data points')
plt.xlabel("x axis", **axis_font)
plt.ylabel("y axis", **axis_font)
plt.title("Misc graph", **title_font)
plt.legend(loc='lower right', prop=font_prop, numpoints=1)
plt.text(0, 0, "Misc text", **title_font)
plt.show()

这种方法的好处是,通过使用多个字体字典,您可以为各种标题选择不同的字体/大小/权重/颜色,为勾号标签选择字体,为图例选择字体,所有这些都是独立的。


更新:

我已经找到了一种稍微不同的、不那么杂乱的方法,它消除了字体字典,并允许在系统中使用任何字体,甚至是.otf字体。要为每件事使用单独的字体,只需编写更多类似font_path和font_prop的变量。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import matplotlib.ticker
# Workaround for Matplotlib 2.0.0 log axes bug https://github.com/matplotlib/matplotlib/issues/8017 :
matplotlib.ticker._mathdefault = lambda x: '\\mathdefault{%s}'%x 

# Set the font properties (can use more variables for more fonts)
font_path = 'C:\Windows\Fonts\AGaramondPro-Regular.otf'
font_prop = font_manager.FontProperties(fname=font_path, size=14)

ax = plt.subplot() # Defines ax variable by creating an empty plot

# Define the data to be plotted
x = np.linspace(0, 10)
y = x + np.random.normal(x)
plt.plot(x, y, 'b+', label='Data points')

for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontproperties(font_prop)
    label.set_fontsize(13) # Size here overrides font_prop

plt.title("Exponentially decaying oscillations", fontproperties=font_prop,
          size=16, verticalalignment='bottom') # Size here overrides font_prop
plt.xlabel("Time", fontproperties=font_prop)
plt.ylabel("Amplitude", fontproperties=font_prop)
plt.text(0, 0, "Misc text", fontproperties=font_prop)

lgd = plt.legend(loc='lower right', prop=font_prop) # NB different 'prop' argument for legend
lgd.set_title("Legend", prop=font_prop)

plt.show()

希望这是一个全面的答案

其他回答

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

更改图形大小!

我通常使用这样的代码:

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

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

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

您可以使用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文档中,

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页面上找到可用财产的完整列表。