[英]Matplotlib how to set legend's font type
I want to change the font type of the legend texts in Matplotlib. 我想在Matplotlib中更改图例文本的字体类型。 I know I can do something like this:
我知道我可以做这样的事情:
plt.legend(prop={'family': 'Arial'})
But I want to use a Chinese font type and I have no idea what is the family name I should put in the line above. 但是我想使用中文字体类型,我不知道应该在上面的行中输入什么姓。 But I do have a fontproperties object to that Chinese font type.
但是我确实有该中文字体类型的fontproperties对象。 However, I haven't found a way to set the fontproperties of the legend.
但是,我还没有找到一种设置图例的fontproperties的方法。
So two questions: 有两个问题:
Pass the FontProperties object (such as font
below) to ax.legend
via the prop
parameter: 通过
prop
参数将FontProperties对象(例如下面的font
)传递给ax.legend
:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.font_manager as font_manager
fig, ax = plt.subplots()
x = np.linspace(-10, 10, 100)
ax.plot(np.sin(x)/x, label='Mexican hat')
font = font_manager.FontProperties(family='Comic Sans MS',
weight='bold',
style='normal', size=16)
ax.legend(prop=font)
plt.show()
On Ubuntu, you can make new fonts available to your system by running 在Ubuntu上,您可以通过运行以下命令使新字体对系统可用
fc-cache -f -v /path/to/fonts/directory
I'm not sure how it is done on other OSes, or how universal fc-cache
is on other flavors of Unix. 我不确定在其他操作系统上是如何完成的,或者在其他类型的Unix上通用的
fc-cache
是否如此。
Once you've installed your font(s) so that your OS knows about them, you can cause matplotlib to regenerate its fontList by deleting the files in ~/.cache/fontconfig
and ~/.cache/matplotlib
. 安装好字体后,操作系统便会知道它们,您可以通过删除
~/.cache/fontconfig
和~/.cache/matplotlib
的文件,使matplotlib重新生成其fontList 。
The ~/.cache/matplotlib/fontList.json
file gives you a humanly-readable list of all the fonts matplotlib knows about. ~/.cache/matplotlib/fontList.json
文件为您提供了matplotlib知道的所有字体的可读列表。 There, you'll find entries that look like this: 在这里,您将找到如下所示的条目:
{
"weight": "bold",
"stretch": "normal",
"fname": "/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS_Bold.ttf",
"_class": "FontEntry",
"name": "Comic Sans MS",
"style": "normal",
"size": "scalable",
"variant": "normal"
},
Notice that the fname
is the path to the underlying ttf file, and that there is a name
property as well. 请注意,
fname
是基础ttf文件的路径,并且还有一个name
属性。 You can specify the FontProperties object by the path to the ttf file: 您可以通过ttf文件的路径指定FontProperties对象 :
font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS_Bold.ttf")
or by name: 或按名称:
font = font_manager.FontProperties(family='Comic Sans MS',
weight='bold',
style='normal', size=16)
If you do not wish to install your font system-wide, you can specify the FontProperties
object by fname
path, thus by-passing the need to call fc-cache
and messing with ~/.cache
. 如果您不希望在系统范围内安装字体,则可以按
fname
路径指定FontProperties
对象,从而无需调用fc-cache
并与~/.cache
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.