Solve the problem of Chinese garbled characters in matplotlib

Please indicate the source for reprint: http://blog.csdn.net/jinixin/article/details/77811680


matplotlib is a well-known Python drawing library, but its support in Chinese is not satisfactory. The following provides a method to solve the garbled characters of Chinese legends.



first step

After installing matplotlib, execute in the Python environment:

import matplotlib
print matplotlib.matplotlib_fname()

The execution result on this machine is "/Users/root/xxx/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc " ;



second step

Copy any font file (I chose "SimHei.ttf") to "/Users/root/xxx/lib/python2.7/site-packages/matplotlib/mpl-data/fonts/ttf" according to the above path Under contents;

I also uploaded a copy of the "SimHei.ttf" font file to Baidu Cloud, the extraction code is "4uhw", click here to download;



third step

Referring to the above path, edit the "/Users/root/xxx/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc" file and change "font.family" to "SimHei";


the fourth step

Delete all "xx.cache" files under the local " home directory/.matplotlib/ " (here, "/Users/root/.matplotlib/");



Remark

To run matplotlib successfully on Linux, you need to add the following code when importing the matplotlib library:

import matplotlib
matplotlib.use('Agg') # Adapt to Linux
from matplotlib import pyplot


After the above four steps are completed, the Chinese on the matplotlib legend can be displayed normally. This method can be successful on both Mac and Ubuntu; I suggest that you can also consider using the front-end drawing library to avoid the pit of matplotlib and have better interactivity , such as "ECharts", etc.



Reference link:

Solve matplotlib Chinese garbled



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325441343&siteId=291194637