How to display Chinese in matplotlib plot
My work-around is like this:
import pandas as pdimport matplotlib.pyplot as pltimport matplotlib.font_manager as fmfont = fm.FontProperties(fname='c:\\windows\\fonts\\simsun.ttc') # speicify fontax = most_active_posts.plot(x = 'title',y = 'active_span',kind = 'barh')ax.set_xticklabels(most_active_posts['title'].str.decode('utf-8'), fontproperties=font)plt.show()
Basically, you need to specify a valid font for Chinese characters.
I find a python library designed for fixing Chinese display in pip. You can download it using the command in your terminal:
pip install pyplotz
And you can write the following code instead(full code):
from pyplotz.pyplotz import PyplotZpltz = PyplotZ()pltz.enable_chinese()most_active_posts.plot(x='title',y='active_span',kind='bar')pltz.xticks(np.arange(len(df.cn)),df.cn,rotation=360)pltz.legend()pltz.show()
And it can help you handle matplotlib Chinese font for you! This is the github page:
https://github.com/201528015329004/pyplotz
And there are some handy examples:
https://github.com/201528015329004/pyplotz/blob/master/examples/quick_start.ipynb
- Enter the directory
Lib\site-packages\matplotlib\mpl-data
, and edit the filematplotlibrc
. - Locate
font.family
andfont.sans-serif
then uncomment both of them and insetMicrosoft YaHei
afterfont.sans-serif
.