【问题标题】:Plotting multiple pie charts in a single figure在单个图中绘制多个饼图
【发布时间】:2021-04-21 02:33:19
【问题描述】:

这些是我的专栏:

SeniorCitizen  Partner   Dependent
Yes            Yes       No  
No             Yes       No 
No             No        Yes
Yes            No        No

我想在单个图形或工作表中绘制所有这些列的单独饼图。这是我的代码:

ax1 = df2['SeniorCitizen'].value_counts().plot(kind='pie', figsize=(5,5), fontsize=10, 
                                              labels = ['No', 'Yes'], autopct='%1.0f%%')
ax1.set_title('% of Senior Citizens', fontsize = 12)
plt.show()

ax2 = df2['Partner'].value_counts().plot(kind='pie', figsize=(5,5), fontsize=10, autopct='%1.0f%%')
ax2.set_title('% of People with and without partner', fontsize = 12)
plt.show()

ax2 = df2['Dependents'].value_counts().plot(kind='pie', figsize=(5,5), fontsize=10, autopct='%1.0f%%')
ax2.set_title('% of People with and without dependent', fontsize = 12)
plt.show()

输出一个接一个地出现在一条直线上。我认为有一个叫做 subplots 的概念,可以让它以水平的形式出现。

谁能帮忙解释和代码? 像这样的东西:

【问题讨论】:

    标签: python pandas matplotlib jupyter-notebook


    【解决方案1】:

    是的,有matplotlib.pyplot.subplots

    import matplotlib.pyplot as plt
    
    # If you want a 2 by 2 grid of plots, do:
    fig, axes = plt.subplots(2,2)
    
    # "axes" will be a list of all the matplotlib.axes.Axes objects
    
    # For one 4-long row of plots:
    fig, axes = plt.subplots(1, 4)
    
    # And one 4-tall column:
    fig, axes = plt.subplot(4, 1)
    
    # etc
    

    您的代码可以适应:

    
    fig, axes = plt.subplots(1, 3)
    
    axes[0].plot(df2['SeniorCitizen'].value_counts(), kind='pie', figsize=(5,5), fontsize=10, 
                                                  labels = ['No', 'Yes'], autopct='%1.0f%%')
    axes[0].set_title('% of Senior Citizens', fontsize = 12)
    
    axes[1].plot(df2['Partner'].value_counts(), kind='pie', figsize=(5,5), fontsize=10, autopct='%1.0f%%')
    axes[1].set_title('% of People with and without partner', fontsize = 12)
    
    axes[2].plot(df2['Dependents'].value_counts(), kind='pie', figsize=(5,5), fontsize=10, autopct='%1.0f%%')
    axes[2].set_title('% of People with and without dependent', fontsize = 12)
    
    plt.show()
    

    【讨论】:

    • 谢谢。但它只显示了一个图表,其中的值组合在一起......它应该看起来像图片......
    • @OmanBilal 我已经编辑了我的代码来调用Axes 对象的plot 方法,它现在可以工作了吗?
    • 错误:'Line2D' 对象没有属性 'kind'...我相信 ax.plot 不适用于此。有什么想法吗?
    • 您需要将 ax=axes[2] 传递给数据框的绘图方法
    猜你喜欢
    • 2014-02-09
    • 1970-01-01
    • 2019-02-13
    • 2014-03-06
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 2014-05-12
    相关资源
    最近更新 更多