pandas 作圖無法顯示中文

最近開始使用 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.seriffont.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

最終實現了正常顯示中文。

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章