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?
但是,一个人如何改变其他人呢?
9 个解决方案
#1
312
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对象所指定的字体,字体。
Alternatively, you could also use the rcParams
update
method as suggested in this answer:
或者,您也可以使用本答案中建议的rcParams更新方法:
matplotlib.rcParams.update({'font.size': 22})
You can find a full list of available properties on the Customizing matplotlib page.
您可以在定制的matplotlib页面上找到可用属性的完整列表。
#2
143
matplotlib.rcParams.update({'font.size': 22})
#3
133
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)
#4
83
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 rc
method on matplotlib
:
注意,您还可以在matplotlib上设置调用rc方法的大小:
import matplotlib
SMALL_SIZE = 8
matplotlib.rc('font', size=SMALL_SIZE)
matplotlib.rc('axes', titlesize=SMALL_SIZE)
# and so on ...
#5
53
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.0 that'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中有一个bug,它会导致对数轴的刻度标记恢复到默认字体。应该在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的答案和其他答案结合在一起。
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_path
and font_prop
like variables.
我已经设计出了一种稍微不同的、不那么杂乱的方法,可以去掉字体字典,并且允许系统上的任何字体,甚至是.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()
Hopefully this is a comprehensive answer
希望这是一个全面的答案。
#6
13
Here is a totally different approach 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
[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)
The smaller you make the figure size, the larger the font is relative to the plot. This also upscales the markers. Note I also set the dpi
or dot per inch. I learned this from a posting the AMTA (American Modeling Teacher of America) forum. Example: Figure from above code
尺寸越小,字体与情节的关系就越大。这也增加了标记。注意,我也设置了dpi或点每英寸。我从美国模特教师协会的论坛上了解到这一点。例子:从上面的代码。
#7
5
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)
#8
1
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教授的观点,最简单的方法就是改变图形的大小,这允许保留默认字体。我只需要用一个bbox_英寸选项来补充这一点,当把图形保存为pdf时,因为轴标签被剪切了。
import matplotlib.pyplot as plt
plt.figure(figsize=(4,3))
plt.savefig('Basic.pdf', bbox_inches='tight')
#9
0
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. This changes will only apply to the current script. So
这是对马吕斯·瑞特根的回答。您可以使用所有修改创建一个单独的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。在同一个文件夹中。
{
"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": ""
}
#1
312
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对象所指定的字体,字体。
Alternatively, you could also use the rcParams
update
method as suggested in this answer:
或者,您也可以使用本答案中建议的rcParams更新方法:
matplotlib.rcParams.update({'font.size': 22})
You can find a full list of available properties on the Customizing matplotlib page.
您可以在定制的matplotlib页面上找到可用属性的完整列表。
#2
143
matplotlib.rcParams.update({'font.size': 22})
#3
133
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)
#4
83
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 rc
method on matplotlib
:
注意,您还可以在matplotlib上设置调用rc方法的大小:
import matplotlib
SMALL_SIZE = 8
matplotlib.rc('font', size=SMALL_SIZE)
matplotlib.rc('axes', titlesize=SMALL_SIZE)
# and so on ...
#5
53
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.0 that'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中有一个bug,它会导致对数轴的刻度标记恢复到默认字体。应该在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的答案和其他答案结合在一起。
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_path
and font_prop
like variables.
我已经设计出了一种稍微不同的、不那么杂乱的方法,可以去掉字体字典,并且允许系统上的任何字体,甚至是.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()
Hopefully this is a comprehensive answer
希望这是一个全面的答案。
#6
13
Here is a totally different approach 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
[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)
The smaller you make the figure size, the larger the font is relative to the plot. This also upscales the markers. Note I also set the dpi
or dot per inch. I learned this from a posting the AMTA (American Modeling Teacher of America) forum. Example: Figure from above code
尺寸越小,字体与情节的关系就越大。这也增加了标记。注意,我也设置了dpi或点每英寸。我从美国模特教师协会的论坛上了解到这一点。例子:从上面的代码。
#7
5
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)
#8
1
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教授的观点,最简单的方法就是改变图形的大小,这允许保留默认字体。我只需要用一个bbox_英寸选项来补充这一点,当把图形保存为pdf时,因为轴标签被剪切了。
import matplotlib.pyplot as plt
plt.figure(figsize=(4,3))
plt.savefig('Basic.pdf', bbox_inches='tight')
#9
0
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. This changes will only apply to the current script. So
这是对马吕斯·瑞特根的回答。您可以使用所有修改创建一个单独的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。在同一个文件夹中。
{
"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": ""
}