The Solution of matplotlib Chinese Gibber in ubuntu system

  • 2020-06-03 09:10:54
  • OfStack

When drawing with matplotlib under ubuntu, Chinese characters on the image cannot be displayed. Here's my solution:

1. Download Chinese font simhei. ttf, url for http: / / fontzone net/download/simhei

2. Search for the installation location of matplotlib fonts

$locate -b '\mpl-data'

Get the path/usr/share/matplotlib/mpl - data fonts/ttf below this directory, enter the directory, the simhei. Just downloaded ttf font is copied to the directory, pay attention to whether the permissions and ownership and other font 1, I was to root users, so use root copied by the user.

3. Delete the buffer file of current user matplotlib (if you did not go directly to Step 4)

$cd ~/.cache/matplotlib
$rm -rf *.*

Adjust fonts in your code

#!/usr/bin/env python
"""a demo of matplotlib"""
import matplotlib as mpl
from matplotlib import pyplot as plt
mpl.rcParams[u'font.sans-serif'] = ['simhei']
mpl.rcParams['axes.unicode_minus'] = False
years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]
gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3]
# create 1 The deputy chart ,x Axis is year ,y Axis is gdp
plt.plot(years, gdp, color='green', marker='o', linestyle='solid')
# add 1 A title 
plt.title(u' In the name of GDP')
# to y Shaft mark 
plt.ylabel(u'10 $ ')
Where #coding:utf-8 describes the file encoding format mpl.rcParams[u'font. sans-serif '] = ['simhei'] Display Chinese in simhei font mpl. rcParams[' axes. unicode_minus'] = False this is used to display the minus sign normally plt. (u' as GDP') It is better to have no less of u here

Related articles: