关于python:如何在matplotlib图上更改字体大小

How to change the font size on a matplotlib plot

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

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

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

但如何改变其余的呢?


From the Matplotlib Documentation,

1
2
3
4
5
font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 22}

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

本集所有项目的成分均由KWARGS Object,EDOCX1〕〔0〕具体说明。

另一方面,你也可以使用rcParams〔1〕update所建议的方法:

ZZU1

黄金

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

你可以在Matplotlib页上找到一份完整的可用性能清单。


ZZU1


如果你想改变方程式只为了一个已经创建的特定图形,试试这个:

1
2
3
4
5
6
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)


如果你是一个像我一样的控制错误,你可能想解释你所有的事情,如果:

1
2
3
4
5
6
7
8
9
10
11
12
13
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

注:您还可以将尺寸设置为rcmatplotlib方法:

1
2
3
4
5
6
7
import matplotlib

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

# and so on ...


Update:see the bottom of the answer for a slightly better way of doing it.最新版本:2:我已经把传奇故事的标题改了太多。Update 350;3:There is a bug in Matplotlib 2.0.0 that's causing tick labels for lograthmic axes to revert to the default font.应在2.0.1内确定,但我已将工作人员包括在答复的第二部分。

这个答案是,任何人都想改变所有的深渊,包括传奇,任何人都想利用不同的深渊和尺寸。It doesn't use RC(which doesn't seem to work for me).这是一个累积的积分,但我不能用任何其他方法去抓。这基本上是Ryggyr和其他人在这里的答案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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()

这一方法的好处是,通过有几种不同的字典,你可以选择不同的字符串/sizes/weights/colors for the various titles,choose the font for the tick labels,and choose the font for the legend,all independently.

更新:

我工作的方式略有不同,但用字典的方式却不尽相同,甚至在你的系统上也不尽相同。要为每件事分离铸铁,就写得更多,像变量一样。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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()

希望这是一个全面的答案


这是一种完全不同的方法,工作的出乎意料的效果是改变现状的尺寸:

改变形状!

我通常都会用这个代码

1
2
3
4
5
6
7
8
9
10
11
12
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)

小的你制作的图案大小,大的图案与圆点相对应。这也是最新的标记。注1也包括dpi或按Inch计算的点数。我从美国模特教师论坛上学到了这一点。Example from above code:enter image description here


使用EDOCX1


Based on the above stuff:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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)

这是一个扩展到Marius Retegan Answer。您可以将JSON文件与您的所有更改分开,而不是装载到RCPARMS.Update。变更只适用于当前的脚本。So

1
2
3
4
5
import json
from matplotlib import pyplot as plt, rcParams

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

并保存此示例 File.json在同一个文档中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
 "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":""
}

你可以使用font_sezematplotlib中,也可以使用plt.rcParams["font.family"]font_family中。Try this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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')

我完全同意Huster教授的看法,即程序的简单方式是改变形状的尺寸,使之保持不变。我只是需要用一个BBOX NCES选项来补充这个选项,因为AXIS标签被切割了。

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