解决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的问题,而是实数的无限精度跟计算机的有限内存之间的矛盾。 举个例子,假如说我...

在Python中如何传递任意数量的实参的示例代码

1 用法 在定义函数时,加上这样一个形参 "*形参名",就可以传递任意数量的实参啦: def make_tags(* tags): '''为书本打标签''' print('标...

python multiprocessing模块用法及原理介绍

一 multiprocessing模块介绍 python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu\_count\(\)查看),在python中大部分...

python监控文件或目录变化

本文实例实现的功能是监控一个文件或目录的变化,如果有变化,把文件上传备份至备份主机,并且要监控上传过程是否有问题等,具体内容如下 #!/usr/bin/env python #co...

Python错误处理操作示例

本文实例讲述了Python错误处理操作。分享给大家供大家参考,具体如下: 同java一样,在python中也有try...except...finaly的错误处理机制 try: p...