admin管理员组

文章数量:1594755

Ubuntu16.04 下python的matplotlib库加入中文字体

    • 一、首先安装微软雅黑字体
      • 1.下载或者拷贝微软雅黑字体
      • 2.将待安装的字体复制到Ubuntu下面的字体位置`/usr/share/fonts`
      • 3.给权限
    • 二、将中文字体加入到程序中

一、首先安装微软雅黑字体

1.下载或者拷贝微软雅黑字体

2.将待安装的字体复制到Ubuntu下面的字体位置/usr/share/fonts

如果字体文件较多可以新建一个文件夹

sudo mkdir ms
sudo cp msyh.ttf /usr/share/fonts/ms

3.给权限

sudo chmod 777 /usr/share/fonts/ms/msyh.ttf

自此,字体安装完成

二、将中文字体加入到程序中

在程序中加入如下代码即可:

from matplotlib import font_manager

my_font = font_manager.FontProperties(fname="/usr/share/fonts/ms/msyh.ttf") # 加入中文到matplotlib

例子:

# coding=utf-8
import random
from matplotlib import font_manager
from matplotlib import pyplot as plt

my_font = font_manager.FontProperties(fname="/usr/share/fonts/ms/msyh.ttf") # 加入中文到matplotlib

x = range(0,60)
y = [random.randint(20,35) for i in x)]

plt.plot(x,y)

_x_ticks = ["10时{}分".format(i) for i in x ]
plt.xticks(x,_x_ticks,rotation=90,fontproperties=my_font) # 坐标轴就可以加入中文了

plt.show()

本文标签: 微软中文字体matplotlibPython