解决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将多个excel文件合并到同一个文件的方法

使用python将多个excel文件合并到同一个文件的方法

应用场景:使用pandas把多个相同结构的Excel文件合并为一个。 原始数据:   相关代码: import os import pandas as pd # 将文...

Python程序设计入门(5)类的使用简介

一、类的定义和使用 python定义一个类的基本语法是: 复制代码 代码如下:class classname([基类一,基类二...]):     [def...

Python使用sort和class实现的多级排序功能示例

本文实例讲述了Python使用sort和class实现的多级排序功能。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- import random cl...

Python使用QQ邮箱发送邮件报错smtplib.SMTPAuthenticationError

Python使用QQ邮箱发送邮件报错smtplib.SMTPAuthenticationError

最新在学习Python的基础入门系列课程,今天学习到使用python 的内置库smtplib发送邮件内容。 使用Python发送邮件步骤简单: 创建SMTP连接 使用邮箱和密码...

python 3.6.2 安装配置方法图文教程

python 3.6.2 安装配置方法图文教程

Windows下Python(pip)环境搭建(3.6)图解,供大家参考,具体内容如下 1、下载最新的Python安装:3.6.2 2、安装时不要选择默认,自定义安装(customiz...