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

yipeiwu_com6年前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实现mqtt的发布和订阅

需要安装的python库 使用python编写程序进行测试MQTT的发布和订阅功能。首先要安装:pip install paho-mqtt 测试发布(pub) 我的MQTT部署在阿里云的...

再谈Python中的字符串与字符编码(推荐)

再谈Python中的字符串与字符编码(推荐)

本节内容: 1.前言 2.相关概念 3.Python中的默认编码 4.Python2与Python3中对字符串的支持 5.字符编码转换 一、前言 Python中的字符编码是个老...

在django中,关于session的通用设置方法

最近发现session的知识有点脱节了,默认设置愣是搞半天,看来忘了不少。今天把一些通用设置贴上来,以备随时回顾。 配置文件中设置默认操作(通用配置): SESSION_CO...

python单元测试unittest实例详解

本文实例讲述了python单元测试unittest用法。分享给大家供大家参考。具体分析如下: 单元测试作为任何语言的开发者都应该是必要的,因为时隔数月后再回来调试自己的复杂程序时,其实也...

python数据结构之二叉树的统计与转换实例

python数据结构之二叉树的统计与转换实例

一、获取二叉树的深度就是二叉树最后的层次,如下图: 实现代码:复制代码 代码如下:def getheight(self):     &n...