Python 如何在熊猫图中显示中文?
在这里,我有一个与熊猫有关的绘图工作,如下所示:Python 如何在熊猫图中显示中文?,python,pandas,matplotlib,fonts,chinese-locale,Python,Pandas,Matplotlib,Fonts,Chinese Locale,在这里,我有一个与熊猫有关的绘图工作,如下所示: most_active_posts.plot(x = 'title',y = 'active_span',kind = 'barh') 大多数活跃的帖子是带有索引的数据框对象,我想要一个简单的二维图,有两列,一列是'title',另一列是'active\u span' title是字符串类型,包含中文字符,而active\u span是整数类型 如何才能正常显示汉字?我想您希望汉字成为绘图右侧的标签 我只是抓取了一些随机字符: In [40]:
most_active_posts.plot(x = 'title',y = 'active_span',kind = 'barh')
大多数活跃的帖子
是带有索引的数据框对象,我想要一个简单的二维图,有两列,一列是'title'
,另一列是'active\u span'
title
是字符串类型,包含中文字符,而active\u span
是整数类型
如何才能正常显示汉字?我想您希望汉字成为绘图右侧的标签 我只是抓取了一些随机字符:
In [40]: df
Out[40]:
0 title
0 0 뉵
1 1 뉑
2 2 늘
3 3 度
[4 rows x 2 columns]
我认为没有办法从df.plot()
设置y\u标签,但是可以从返回的轴
对象设置它们:
In [47]: ax = df.plot(kind='barh')
In [48]: ax.set_yticklabels(df['title'].str.decode('utf-8'))
Out[48]:
[<matplotlib.text.Text at 0x1152abfd0>,
<matplotlib.text.Text at 0x1152a3910>,
<matplotlib.text.Text at 0x111c5e790>,
<matplotlib.text.Text at 0x111c5ef10>]
In [49]: plt.draw()
[47]中的:ax=df.plot(kind='barh')
在[48]中:ax.set_-yticklabels(df['title'].str.decode('utf-8'))
出[48]:
[,
,
,
]
In[49]:plt.draw()
图如下:
我实际上无法保存文件并显示字符。目前不知道为什么,但这可能会让你开始
输入目录Lib\site packages\matplotlib\mpl data
,然后编辑文件matplotlibrc
李>
找到font.family
和font.sans serif
,然后取消对它们的注释,并在font.sans serif
之后插入Microsoft YaHei
我的工作是这样的:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
font = fm.FontProperties(fname='c:\\windows\\fonts\\simsun.ttc') # speicify font
ax = most_active_posts.plot(x = 'title',y = 'active_span',kind = 'barh')
ax.set_xticklabels(most_active_posts['title'].str.decode('utf-8'), fontproperties=font)
plt.show()
基本上,您需要为汉字指定一个有效的字体。我找到了一个python库,用于修复pip中的中文显示。您可以使用终端中的命令下载:
pip install pyplotz
您可以编写以下代码(完整代码):
它可以帮助您处理matplotlib中文字体!这是github页面:
这里有一些方便的例子:
如果您使用熊猫,您可以使用getxticklabels
获取标签,然后使用setxticklabels
设置标签
import matplotlib.font_manager as mfm
import matplotlib.pyplot as plt
font_path = "/System/Library/Fonts/STHeiti Light.ttc"
prop = mfm.FontProperties(fname=font_path)
df = pd.read_csv("data.txt"]
figure, ax = plt.subplots(figsize=(12, 4))
tmp = df.boxplot(by='shop', column='buy', ax=ax)
ax.set_xticklabels(tmp.get_xticklabels(), fontproperties=prop)
plt.show()
嗨,朋友!我按照你的建议试过了,不幸的是问题仍然存在。我的情况是这样的,我的情况更像这样:s1=系列([u'\UUU3010\u676d\u5dde\U30111\U7f8 8 8 8 8-D4\u901a\U9011a\U10 10 10 10\U7 7 7 7 7 7 7 7 7 8 8.1我的情况是我的情况,我的情况是这样的情况很多很多很多很多:s1=S:s1=系列([10 10 10.1\u901a\u901a\u4fe1\U9011a\U1a\U4 fe1\U1\1\U516 C\u516c\u516c\u516c\u516c\u516c\u516c\U53C\U53f1\U53f1\U53f1\U53f1\U53f1\U53f1\U531\U53f1\u516c\U538此解决方案也适用于
import matplotlib.font_manager as mfm
import matplotlib.pyplot as plt
font_path = "/System/Library/Fonts/STHeiti Light.ttc"
prop = mfm.FontProperties(fname=font_path)
df = pd.read_csv("data.txt"]
figure, ax = plt.subplots(figsize=(12, 4))
tmp = df.boxplot(by='shop', column='buy', ax=ax)
ax.set_xticklabels(tmp.get_xticklabels(), fontproperties=prop)
plt.show()