熊猫饼状图删除楔形上的标签文本

问题描述 投票:17回答:2

熊猫绘图教程http://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html上的饼图示例生成下图:

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9PeTJtUC5wbmcifQ==” alt =“在此处输入图像描述”>

使用此代码:

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),因为对于我的应用程序来说,这些标签很长,所以我只想在图例中显示它们。

阅读此:How to add a legend to matplotlib pie chart?之后,我想出了一种使用matplotlib.pyplot.pie的方法,但即使我仍在使用ggplot,该图也不太理想。

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')

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9pVEpJaC5wbmcifQ==” alt =“在此处输入图像描述”>

我的问题是,有没有一种方法可以将我想要的东西从两侧结合起来?明确地说,我想让熊猫出奇,但是要删除楔形文字。

谢谢

pandas matplotlib legend pie-chart
2个回答
32
投票

您可以关闭图表中的标签,然后在对legend的调用中定义它们:

df[col].plot(kind='pie', autopct='%.2f', labels=['','','',''],  ax=ax, title=col, fontsize=10)
ax.legend(loc=3, labels=df.index)

... labels=None ...

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9jRlZmbi5wbmcifQ==” alt =“在此处输入图像说明”>


0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.