gpt4 book ai didi

python - Matplotlib 如何设置图例的字体类型

转载 作者:太空狗 更新时间:2023-10-30 01:05:11 34 4
gpt4 key购买 nike

我想更改 Matplotlib 中图例文本的字体类型。我知道我可以做这样的事情:

plt.legend(prop={'family': 'Arial'})

但我想使用中文字体,但我不知道应该在上面的行中输入什么姓氏。但是我确实有一个针对该中文字体类型的 fontproperties 对象。但是,我还没有找到设置图例字体属性的方法。

所以两个问题:

  1. 如何查找特定字体的家族名称
  2. 如何设置图例的字体属性

最佳答案

通过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()

enter image description here

在 Ubuntu 上,您可以通过运行使新字体对您的系统可用

fc-cache -f -v /path/to/fonts/directory

我不确定它在其他操作系统上是如何完成的,或者 fc-cache 在其他 Unix 上的通用性如何。


一旦你安装了你的字体以便你的操作系统知道它们,你可以使 matplotlib 到 regenerate its fontList通过删除 ~/.cache/fontconfig~/.cache/matplotlib 中的文件。


~/.cache/matplotlib/fontList.json 文件为您提供了一个人类可读的列表,其中包含 matplotlib 知道的所有字体。在那里,您会找到如下所示的条目:

{
"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"
},

请注意,fname 是底层 ttf 文件的路径,并且还有一个 name 属性。你可以specify the FontProperties object通过 ttf 文件的路径:

font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS_Bold.ttf")

或按名称:

font = font_manager.FontProperties(family='Comic Sans MS',
weight='bold',
style='normal', size=16)

如果您不想在系统范围内安装您的字体,您可以通过 fname 路径指定 FontProperties 对象,从而绕过调用 fc-cache 和乱用 ~/.cache

关于python - Matplotlib 如何设置图例的字体类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47112522/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com