pandas给每个分类添加标识:做图显示中文标签
pandas给每个分类添加标识:做图显示中文标签山东省 江苏省 1995年 3872.18 4057.390000 1996年 5960.42 6004.210000 1997年 6650.02 6680.340000 1998年 7162.20 7199.950000 1999年 7662.10 7697.820000 2000年 8542.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.1
对于数据集 直接做图时
#coding:utf-8 from pandas import DataFrame df = DataFrame({"score":[80 90]} index=["张三" "李四"]) ax = df.plot(kind = 'bar' rot = 0) 1 2 3 4
中文标签显示不出来 如图:
代码
可以利用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() 1 2 3 4 5 6 7 8 9 10 11 12 13 14
效果如图:
改进
这里要重新指定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() 1 2 3 4 5 6 7 8 9 10 11 12 13
进阶
若有不同的中文标签显示不出来怎么办,看这个例子,用循环来做。
山东省 江苏省 1995年 3872.18 4057.390000 1996年 5960.42 6004.210000 1997年 6650.02 6680.340000 1998年 7162.20 7199.950000 1999年 7662.10 7697.820000 2000年 8542.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()