简体   繁体   English

如何更改 matplotlib (python) 中的字体?

[英]How to change fonts in matplotlib (python)?

It sounds as an easy problem but I do not find any effective solution to change the font (not the font size) in a plot made with matplotlib in python.这听起来是一个简单的问题,但我没有找到任何有效的解决方案来在 python 中使用 matplotlib 制作的图中更改字体(而不是字体大小)。

I found a couple of tutorials to change the default font of matplotlib by modifying some files in the folders where matplotlib stores its default font - see this blog post - but I am looking for a less radical solution since I would like to use more than one font in my plot (text, label, axis label, etc).我找到了几个教程,通过修改 matplotlib 存储其默认字体的文件夹中的一些文件来更改 matplotlib 的默认字体 - 请参阅此博客文章- 但我正在寻找一个不太激进的解决方案,因为我想使用多个我的图中的字体(文本、标签、轴标签等)。

Say you want Comic Sans for the title and Helvetica for the x label.假设标题需要 Comic Sans,x 标签需要 Helvetica。

csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}

plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()

You can also use rcParams to change the font family globally.您还可以使用rcParams全局更改字体系列。

 import matplotlib.pyplot as plt
 plt.rcParams["font.family"] = "cursive"
 # This will change to your computer's default cursive font

The list of matplotlib's font family arguments is here . matplotlib 的字体系列参数列表在这里

I prefer to employ:我更喜欢雇用:

from matplotlib import rc
#rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('font',**{'family':'serif','serif':['Times']})
rc('text', usetex=True)
import pylab as plb
plb.rcParams['font.size'] = 12

or或者

import matplotlib.pyplot as mpl
mpl.rcParams['font.size'] = 12

The Helvetica font does not come included with Windows, so to use it you must download it as a .ttf file. Helvetica 字体不包含在 Windows 中,因此要使用它,您必须将其下载为 .ttf 文件。 Then you can refer matplotlib to it like this (replace "crm10.ttf" with your file):然后你可以像这样引用 matplotlib(用你的文件替换“crm10.ttf”):

import os
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This is the default font')

plt.show()

print(fpath) will show you where you should put the .ttf. print(fpath)会告诉你应该把 .ttf 放在哪里。

You can see the output here: https://matplotlib.org/gallery/api/font_file.html你可以在这里看到输出: https : //matplotlib.org/gallery/api/font_file.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM