【问题标题】:pandas pie chart plot remove the label text on the wedgepandas 饼图 plot 删除楔形上的标签文本
【发布时间】:2015-07-15 14:15:04
【问题描述】:

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

使用此代码:

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

我的问题是,有没有一种方法可以将我想要的东西从双方结合起来?需要明确的是,我想要熊猫的花哨,但从楔子中删除文本。

谢谢

【问题讨论】:

    标签: pandas matplotlib legend pie-chart


    【解决方案1】:

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

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

    ... labels=None ...
    

    【讨论】:

    • 有没有办法去掉每幅图左侧多余的 x 和 y?
    • Here 是一个解决方案。
    【解决方案2】:

    使用 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()
    

    Output:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多