熊猫图表制作饼图时如何去除楔形上的标签文本

36

在pandas绘图教程的饼状图示例http://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html,生成以下图表:

enter image description here

使用以下代码:

import matplotlib.pyplot as plt
plt.style.use('ggplot')
import numpy as np
np.random.seed(123456)


import pandas as pd
df = pd.DataFrame(3 * np.random.rand(4, 2), index=['a', 'b', 'c', 'd'], columns=['x', 'y'])

f, axes = plt.subplots(1,2, figsize=(10,5))
for ax, col in zip(axes, df.columns):
    df[col].plot(kind='pie', autopct='%.2f', labels=df.index,  ax=ax, title=col, fontsize=10)
    ax.legend(loc=3)

plt.show()

我想从两个子图中删除文本标签(a,b,c,d),因为对于我的应用程序,这些标签太长了,所以我只想在图例中显示它们。

阅读了这篇文章:如何为 matplotlib 饼图添加图例?,我发现可以使用matplotlib.pyplot.pie,但即使我仍然使用 ggplot,绘图效果也不如 fancy。

f, axes = plt.subplots(1,2, figsize=(10,5))
for ax, col in zip(axes, df.columns):
    patches, text, _ = ax.pie(df[col].values, autopct='%.2f')
    ax.legend(patches, labels=df.index, loc='best')

输入图像描述

我的问题是,是否有一种方法可以同时满足我想要从两个方面得到的东西?明确地说,我想要 Pandas 的花哨效果,但删除楔形图中的文本。

谢谢

2个回答

60
您可以关闭图表中的标签,然后在调用legend时定义它们。
df[col].plot(kind='pie', autopct='%.2f', labels=['','','',''],  ax=ax, title=col, fontsize=10)
ax.legend(loc=3, labels=df.index)
或者
... labels=None ...

在此输入图像描述


2
有没有办法去掉每个图形左侧的额外x和y? - SaTa
1
这里有一个解决方案,与Python Matplotlib Pyplot饼图相关,可以删除左侧的标签。 - SaTa

14

使用pandas,您仍然可以使用matplotlib.pyplot.pie关键字labeldistance来删除楔形标签。
例如:df.plot.pie(subplots=True, labeldistance=None, legend=True)

来自docs:
labeldistancefloatNone,可选,默认值:1.1
绘制饼图标签的径向距离。如果设置为None,则不绘制标签,但将其存储供legend()使用。

上下文:

import matplotlib.pyplot as plt
plt.style.use('ggplot')
import numpy as np
np.random.seed(123456)


import pandas as pd
df = pd.DataFrame(3 * np.random.rand(4, 2), index=['a', 'b', 'c', 'd'], columns=['x', 'y'])

df.plot.pie(subplots=True, figsize=(10,5), autopct='%.2f', fontsize=10, labeldistance=None);

plt.show()

输出:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接