解决pandas 作图无法显示中文的问题

yipeiwu_com5年前Python基础

最近开始使用 pandas 处理可视化数据,挖掘信息。但是在作图时遇到,无法显示中文的问题。

下面这段代码是统计 fujian1.csv 文件中 City 所在列中各个城市出现次数的代码。可是作图直方图时在 x 轴上无法显示中文。

import pandas as pd
# Reading data locally
df = pd.read_csv('fujian1.csv', encoding='gbk')
counts = df['City'].value_counts()
counts[counts > 1000].plot(kind = 'bar')

查了一些资料,找到的原因是 matplotlib 包默认只支持 ASCII 码,不支持 unicode 码。

解决方法,就是需要将 matplotlib 的安装目录下的 matplotlibrc 配置文件修改一下,将font.family 部分(大概在139行左右)注释去掉,并且在 font.serif 和 font.sans-serif 支持字体加上一个中文字体,如 SimHei:

font.family   : sans-serif
#font.style   : normal
#font.variant  : normal
#font.weight   : medium
#font.stretch  : normal
# note that font.size controls default text sizes. To configure
# special text sizes tick labels, axes, labels, title, etc, see the rc
# settings for axes and ticks. Special text sizes can be defined
# relative to font.size, using the following values: xx-small, x-small,
# small, medium, large, x-large, xx-large, larger, or smaller
#font.size   : 12.0
font.serif   : SimHei, Bitstream Vera Serif, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
font.sans-serif  : SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#font.cursive  : Apple Chancery, Textile, Zapf Chancery, Sand, cursive
#font.fantasy  : Comic Sans MS, Chicago, Charcoal, Impact, Western, fantasy
#font.monospace  : Bitstream Vera Sans Mono, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace

最终实现了正常显示中文。

以上这篇解决pandas 作图无法显示中文的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python检测一个对象是否为字符串类的方法

目的   测试一个对象是否是字符串 方法 Python的字符串的基类是basestring,包括了str和unicode类型。一般可以采用以下方法: 复制代码 代码如下: def isA...

Python UnboundLocalError和NameError错误根源案例解析

如果代码风格相对而言不是那么的pythonic,或许很少碰到这类错误。当然并不是不鼓励使用一些python语言的技巧。如果遇到这这种类型的错误,说明我们对python中变量引用相关部分有...

Python Sqlite3以字典形式返回查询结果的实现方法

sqlite3本身并没有像pymysql一样原生提供字典形式的游标。 cursor = conn.cursor(pymysql.cursors.DictCursor) 但官方文...

浅谈Pycharm调用同级目录下的py脚本bug

浅谈Pycharm调用同级目录下的py脚本bug

环境:python3.5,pycharm2017.2.3 目录结构 a.py t=5 b.py from a import t print(t) 平台显示 出现红色波浪线警...

python自动化测试之setUp与tearDown实例

本文实例讲述了python自动化测试之setUp与tearDown的用法,分享给大家供大家参考。具体如下: 实例代码如下: class RomanNumeralConverter(o...