pandas 做图显示中文标签

pandas 做图显示中文标签

对于数据集,直接做图时,

#coding:utf-8 
from pandas import DataFrame 
df = DataFrame({"score":[80, 90]}, index=["张三","李四"])
ax = df.plot(kind = 'bar', rot = 0)

中文标签显示不出来,如图:

pandas 做图显示中文标签_第1张图片

代码

可以利用FontProperties解决,办法如下:

#coding:utf-8 
from pandas import DataFrame 
import pandas as pd 
import matplotlib.pyplot as plt 
from matplotlib.font_manager import FontProperties 

font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)  #size可不用指定
# linux 的中文字体 /usr/share/fonts/simhei/simhei.ttf

df = DataFrame({"score":[80, 90]}, index=["张三","李四"]) 
ax = df.plot(kind = 'bar', rot = 0) 
labels = [label.decode("utf-8") for label in df.index.values] 
ax.set_xticklabels(labels, fontproperties=font) 
plt.show()

效果如图:
pandas 做图显示中文标签_第2张图片

改进

这里要重新指定label,比较麻烦,要是多的话真吃不消。能否不再重新指定xticklables,直接更改其字体,像参考链接2中的那样:

当然可以,用如下代码能省不少事呢….

#coding:utf-8 
from pandas import DataFrame 
import pandas as pd 
import matplotlib.pyplot as plt 
from matplotlib.font_manager import FontProperties 

font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14) 

df = DataFrame({"score":[80, 90]}, index=["张三","李四"]) 
ax = df.plot(kind = 'bar', rot = 0) 
for label in ax.get_xticklabels() : 
    label.set_fontproperties(font) 
plt.show()

进阶

若有不同的中文标签显示不出来怎么办,看这个例子,用循环来做。

           山东省          江苏省
19953872.18  4057.390000
19965960.42  6004.210000
19976650.02  6680.340000
19987162.20  7199.950000
19997662.10  7697.820000
20008542.44  8582.727627

from pandas import DataFrame 
import pandas as pd 
import matplotlib.pyplot as plt 
from matplotlib.font_manager import FontProperties 

font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14) 

df = DataFrame({"山东省": [3872.18, 5960.42, 6650.02, 7162.2, 7662.1, 8542.44] , 
            "江苏省": [4057.39, 6004.21, 6680.34, 7199.95, 7697.82, 8582.727627]},
            index=["1995年", "1996年", "1997年", "1998年", "1999年", "2000年"])

ax = df.plot(color=["g", "r"],style=["--","-"], title=u"山东江苏GDP(单位:亿元)")
labels = ax.get_xticklabels()+ax.legend().texts+[ax.title]
for label in labels : 
    label.set_fontproperties(font) 
plt.show()

参考链接:

  1. python中matplotlib绘图中文显示问题
    http://blog.chinaunix.net/uid-26611383-id-3521248.html
  2. Display non ascii (Japanese) characters in pandas plot legend
    http://stackoverflow.com/questions/23197124/display-non-ascii-japanese-characters-in-pandas-plot-legend
  3. Set Font Properties to Tick Labels with Matplot Lib
    http://stackoverflow.com/questions/7257372/set-font-properties-to-tick-labels-with-matplot-lib
  4. Python-Matplotlib安装及简单使用
    http://my.oschina.net/bery/blog/203595

你可能感兴趣的:(python,pandas做图,中文标签,pandas,python)