Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display Chinese in matplotlib plot

Here, I have a plot work to do with pandas, like this :

most_active_posts.plot(x = 'title',y = 'active_span',kind = 'barh')

most_active_posts is an object of dataframe with index, I want a simple two-dimensional plot with two columns, one is 'title' and the other is 'active_span'.

title is type of string, which contains Chinese characters, while active_span is type of integer .

How can I display Chinese characters normally?

like image 216
joe Avatar asked Dec 15 '22 02:12

joe


2 Answers

My work-around is like this:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
font = fm.FontProperties(fname='c:\\windows\\fonts\\simsun.ttc')  # speicify font
ax = 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.

like image 61
zaxliu Avatar answered Dec 17 '22 16:12

zaxliu


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 PyplotZ
pltz = 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()

The result is like this

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

like image 26
Ray Avatar answered Dec 17 '22 16:12

Ray