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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3899980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:16:22  来源:igfitidea点击:

How to change the font size on a matplotlib plot

pythonmatplotlibfont-size

提问by Herman Schaaf

How does one change the font size for all elements (ticks, labels, title) on a matplotlib plot?

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

I know how to change the tick label sizes, this is done with:

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

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

But how does one change the rest?

但是如何改变其余的呢?

采纳答案by Herman Schaaf

From the matplotlib documentation,

matplotlib 文档中

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

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

This sets the font of all items to the font specified by the kwargs object, font.

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

Alternatively, you could also use the rcParamsupdatemethod as suggested in this answer:

或者,您也可以使用此答案中rcParamsupdate建议的方法:

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

or

或者

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

You can find a full list of available properties on the Customizing matplotlib page.

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

回答by Marius Retegan

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

回答by ryggyr

If you want to change the fontsize for just a specific plot that has already been created, try this:

如果您只想更改已创建的特定绘图的字体大小,请尝试以下操作:

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)

回答by binaryfunt

Update:See the bottom of the answer for a slightly better way of doing it.
Update #2:I've figured out changing legend title fonts too.
Update #3:There is a bug in Matplotlib 2.0.0that's causing tick labels for logarithmic axes to revert to the default font. Should be fixed in 2.0.1 but I've included the workaround in the 2nd part of the answer.

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

This answer is for anyone trying to change all the fonts, including for the legend, and for anyone trying to use different fonts and sizes for each thing. It does not use rc (which doesn't seem to work for me). It is rather cumbersome but I could not get to grips with any other method personally. It basically combines ryggyr's answer here with other answers on SO.

这个答案适用于任何试图更改所有字体(包括图例)的人,以及任何试图为每件事使用不同字体和大小的人。它不使用 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()

The benefit of this method is that, by having several font dictionaries, you can choose different fonts/sizes/weights/colours for the various titles, choose the font for the tick labels, and choose the font for the legend, all independently.

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



UPDATE:

更新:

I have worked out a slightly different, less cluttered approach that does away with font dictionaries, and allows any font on your system, even .otf fonts. To have separate fonts for each thing, just write more font_pathand font_proplike variables.

我已经找到了一种稍微不同的、不那么混乱的方法,它消除了字体词典,并允许您系统上的任何字体,甚至 .otf 字体。要为每个事物使用单独的字体,只需编写更多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()

Hopefully this is a comprehensive answer

希望这是一个全面的答案

回答by nvd

Based on the above stuff:

基于以上内容:

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)

回答by Prof Huster

Here is a totally differentapproach that works surprisingly well to change the font sizes:

这是一种完全不同的方法,可以很好地改变字体大小:

Change the figure size!

改变图形大小

I usually use code like this:

我通常使用这样的代码:

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)

The smalleryou make the figure size, the largerthe font is relative to the plot. This also upscales the markers. Note I also set the dpior dot per inch. I learned this from a posting the AMTA (American Modeling Teacher of America) forum. Example from above code: enter image description here

较小你做图的大小,更大的字体是相对于情节。这也放大了标记。注意我还设置了dpi或每英寸点数。我从 AMTA(美国模特教师协会)论坛的帖子中了解到这一点。上面代码的例子:在此处输入图片说明

回答by Pedro M Duarte

If you are a control freak like me, you may want to explicitly set all your font sizes:

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

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

Note that you can also set the sizes calling the rcmethod on matplotlib:

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

import matplotlib

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

# and so on ...

回答by Pedro M Duarte

I totally agree with Prof Huster that the simplest way to proceed is to change the size of the figure, which allows keeping the default fonts. I just had to complement this with a bbox_inches option when saving the figure as a pdf because the axis labels were cut.

我完全同意 Huster 教授的观点,最简单的方法是更改​​图形的大小,这样可以保留默认字体。在将图形另存为 pdf 时,我只需要使用 bbox_inches 选项对此进行补充,因为轴标签已被剪切。

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

回答by Michael H.

This is an extension to Marius Retegan answer. You can make a separate JSON file with all your modifications and than load it with rcParams.update. The changes will only apply to the current script. So

这是 Marius Retegan答案的扩展。您可以使用所有修改制作一个单独的 JSON 文件,然后使用 rcParams.update 加载它。更改将仅适用于当前脚本。所以

import json
from matplotlib import pyplot as plt, rcParams

s = json.load(open("example_file.json")
rcParams.update(s)

and save this 'example_file.json' in the same folder.

并将此“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": ""
}

回答by Andrey Nikishaev

Use plt.tick_params(labelsize=14)

plt.tick_params(labelsize=14)