在Python中,如何用中文标记绘制散点图?

时间:2020-06-23 14:53:58

标签: python matplotlib scatter-plot

如果坐标(x,y)及其对应的中文z如下:

import matplotlib.pyplot as plt 
x = [1, 2, 3, 4, 5]
y = [5, 4, 3, 2, 1]
z = ["一", "二", "三", "四", "五"]
plt.scatter(x, y)
plt.show()

然后它将绘图:

enter image description here

请告诉我如何绘制对应的中文,即将z作为散点图的坐标。

例如:

enter image description here

谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

来自this website

这是因为matplotlib使用的字体无法正确解码字符。要解决该问题,我们应该添加适当的字体并更新matplotlib字体缓存。

  1. 找到matplotlib字体文件夹:
import matplotlib
print(matplotlib.matplotlib_fname())

这是matplotlib配置文件的位置,您将获得类似.../matplotlib/mpl-data/matplotlibrc

的信息。

字体文件夹为.../matplotlib/mpl-data/fonts/ttf,将您的ttf文件放在此处。

  1. ttf文件中获取ttc(如果已经有ttf文件则跳过)

对于macOS,系统中文字体为'Heiti',嵌入在ttc文件中(ttc是多个ttf文件的集合)。在ttc中获取系统/System/Library/Fonts/STHeiti Medium.ttc文件,将其复制出来并将其转换为ttf。这是一个在线ttc转换器:

https://transfonter.org/ttc-unpack
  1. 重建Matplotlib缓存
import matplotlib.font_manager
matplotlib.font_manager._rebuild()

重新启动Jupyter / ipython内核,然后通过字体管理器的matplotlib功能测试ttflist是否可以加载字体

[f for f in matplotlib.font_manager.fontManager.ttflist if 'Heiti' in f.name]

'Heiti'更改为您自己的字体名称。如果您在上方看到字体对象。您可以使用新字体了。

  1. 在Matplotlib中使用适当的字体
matplotlib.rcParams['font.family'] = ['Heiti TC']

这将告诉matplotlib使用特定字体作为默认字体。