如何更改matplotlib图上的字体大小

如何更改matplotlib图上所有元素(刻度,标签,标题)的字体大小?

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

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

但是如何改变其余呢?

从matplotlib文档中 ,

 font = {'family' : 'normal', 'weight' : 'bold', 'size' : 22} matplotlib.rc('font', **font) 

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

或者,您也可以使用此答案中build议的rcParams update方法:

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

您可以在自定义matplotlib页面上find可用属性的完整列表。

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

如果你想改变字体大小只是一个已经创build的特定情节,试试这个:

 import matplotlib.pyplot as plt ax = plt.subplot(111, xlabel='x', ylabel='y', title='title') for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(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() 

这种方法的好处在于,通过使用多个字体字典,您可以为各种标题select不同的字体/大小/权重/颜色,为刻度标签select字体,并为所有图例select字体。


更新:

我已经制定了一个稍微不同的,不那么混乱的方法,取消字体字典,并允许您的系统上的任何字体,甚至.otf字体。 为了让每个东西都有独立的字体,只font_prop像variables一样写更多的font_pathfont_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 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 ... 

这是一个完全不同的方法,令人惊讶地改变字体大小:

改变数字大小

我通常使用这样的代码:

 import matplotlib.pyplot as plt import numpy as np [enter image description here][1]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或点。 我从美国美国模特老师论坛发帖了解到这一点。 例如: 从上面的代码图

基于以上的东西:

 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) 

我完全同意Huster教授所说,最简单的方法就是改变graphics的大小,这样可以保留默认的字体。 我只需要用bbox_inches选项来补充这一点,因为将图标保存为pdf是因为轴标签已被剪切。

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