如何更改 matplotlib 图上所有元素(刻度、标签、标题)的字体大小?
我知道如何更改刻度标签大小,这是通过以下方式完成的:
import matplotlib
matplotlib.rc('xtick', labelsize=20)
matplotlib.rc('ytick', labelsize=20)
但是如何改变其余的呢?
font = {'family' : 'normal',
'weight' : 'bold',
'size' : 22}
matplotlib.rc('font', **font)
这会将所有项目的字体设置为 kwargs 对象 font
指定的字体。
或者,您也可以使用 this answer 中建议的 rcParams
update
方法:
matplotlib.rcParams.update({'font.size': 22})
或者
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 22})
您可以在 Customizing matplotlib page 上找到可用属性的完整列表。
如果您像我一样是控制狂,您可能需要明确设置所有字体大小:
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 ...
plt.rc('axes', titlesize=BIGGER_SIZE)
plt.rc('axes', titlesize=SMALL_SIZE, labelsize=MEDIUM_SIZE)
如果您只想更改已创建的特定绘图的字体大小,请尝试以下操作:
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)
ax=plt.gca()
。
ax.get_legend().get_texts()
,因为 ax.legend()
在返回 ax.get_legend()
的值的基础上使用默认参数重绘整个图例。
matplotlib.rcParams.update({'font.size': 22})
更新:请参阅答案的底部以获得更好的方法。
更新#2:我也想出了更改图例标题字体。< br> 更新 #3: 有一个 bug in 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)
https://i.stack.imgur.com/uEjJN.png
bbox_inches
参数 fig.savefig('Basic.png', bbox_inches="tight")
保存图形
plt.tight_layout()
plt.figure(figsize=(4,3), dpi=300)
时使用 dpi=XXX 参数来实现相同的结果而不保存
您可以使用 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')
https://i.stack.imgur.com/cX0sy.png
使用plt.tick_params(labelsize=14)
这是我通常在 Jupyter Notebook 中使用的内容:
# Jupyter Notebook settings
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:95% !important; }</style>"))
%autosave 0
%matplotlib inline
%load_ext autoreload
%autoreload 2
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
# Imports for data analysis
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', 2500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.max_colwidth', 2000)
pd.set_option('display.width', 2000)
pd.set_option('display.float_format', lambda x: '%.3f' % x)
#size=25
size=15
params = {'legend.fontsize': 'large',
'figure.figsize': (20,8),
'axes.labelsize': size,
'axes.titlesize': size,
'xtick.labelsize': size*0.75,
'ytick.labelsize': size*0.75,
'axes.titlepad': 25}
plt.rcParams.update(params)
对 rcParams
的更改非常精细,大多数情况下您只需要缩放所有字体大小,以便在您的图中更好地看到它们。数字大小是一个很好的技巧,但是您必须为所有数字携带它。另一种方法(不是纯粹的 matplotlib,或者如果你不使用 seaborn 可能会矫枉过正)是使用 seaborn 设置字体比例:
sns.set_context('paper', font_scale=1.4)
免责声明:我知道,如果您只使用 matplotlib,那么您可能不想安装整个模块来缩放您的绘图(我的意思是为什么不这样做),或者如果您使用 seaborn,那么您可以更好地控制选项。但是在这种情况下,您的数据科学虚拟环境中有 seaborn,但在此笔记本中没有使用它。无论如何,还有另一个解决方案。
基于以上内容:
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 教授的观点,最简单的方法是改变图形的大小,这样可以保持默认字体。在将图形保存为 pdf 时,我只需要使用 bbox_inches 选项来补充它,因为轴标签已被剪切。
import matplotlib.pyplot as plt
plt.figure(figsize=(4,3))
plt.savefig('Basic.pdf', bbox_inches='tight')
这是 Marius Retegan answer 的扩展。您可以使用所有修改创建一个单独的 JSON 文件,然后使用 rcParams.update 加载它。更改将仅适用于当前脚本。所以
import json
from matplotlib import pyplot as plt, rcParams
s = json.load(open("example_file.json")
rcParams.update(s)
并将此“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": ""
}
我只是想指出 Herman Schaaf's 和 Pedro M Duarte's 答案都有效,但您必须在实例化 subplots()
之前这样做,这些设置不会影响已经实例化的对象。我知道这不是一个脑筋急转弯,但是当我在调用 subplots() 后尝试使用这些更改时,我花了很多时间弄清楚为什么这些答案对我不起作用。
例如:
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 6,})
fig, ax = plt.subplots()
#create your plot
plt.show()
或者
SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 12
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
fig, ax = plt.subplots()
#create your plot
plt.show()
评论中提到了它,但值得自己回答:
修改both figsize=
和 dpi=
一起调整图形大小和所有文本标签的比例:
fig, ax = plt.subplots(1, 1, figsize=(8, 4), dpi=100)
(或更短:)
fig, ax = plt.subplots(figsize=(8, 4), dpi=100)
这有点棘手:
figsize 实际上控制文本相对于绘图范围的比例(以及绘图的纵横比)。 dpi 调整笔记本中图形的大小(保持文本的相对比例和绘图纵横比不变)。
我由@ryggyr 编写了答案的修改版本,它允许对单个参数进行更多控制并适用于多个子图:
def set_fontsizes(axes,size,title=np.nan,xlabel=np.nan,ylabel=np.nan,xticks=np.nan,yticks=np.nan):
if type(axes) != 'numpy.ndarray':
axes=np.array([axes])
options = [title,xlabel,ylabel,xticks,yticks]
for i in range(len(options)):
if np.isnan(options[i]):
options[i]=size
title,xlabel,ylabel,xticks,yticks=options
for ax in axes.flatten():
ax.title.set_fontsize(title)
ax.xaxis.label.set_size(xlabel)
ax.yaxis.label.set_size(ylabel)
ax.tick_params(axis='x', labelsize=xticks)
ax.tick_params(axis='y', labelsize=yticks)
不定期副业成功案例分享
'family'
、'weight'
等元素的更多选项?import matplotlib.pyplot as plt
开始的,因此您可能需要指出pyplot
也有rc
。您可以执行plt.rc(...
而无需更改您的导入。for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(22)
之类的操作来影响单个图中的文本大小。