【问题标题】:Plot pie chart and table of pandas dataframe绘制熊猫数据框的饼图和表格
【发布时间】:2016-11-15 05:29:50
【问题描述】:

我必须使用 matplotlib 并排绘制饼图和表格。

为了绘制饼图,我使用以下代码:

import matplotlib.pyplot as plt
df1.EventLogs.value_counts(sort=False).plot.pie()
plt.show()

为了绘制表格,我使用以下代码:

%%chart table --fields MachineName --data df_result2

df_result2 是一个包含 MachineName 列表的表。

不确定我们是否可以将饼图和表格并排放置。任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    看代码:

    import pandas as pd
    import matplotlib.pyplot as plt
    from pandas.tools.plotting import table
    
    # sample data
    raw_data = {'officer_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
            'jan_arrests': [4, 24, 31, 2, 3],
            'feb_arrests': [25, 94, 57, 62, 70],
            'march_arrests': [5, 43, 23, 23, 51]}
    df = pd.DataFrame(raw_data, columns = ['officer_name', 'jan_arrests', 'feb_arrests', 'march_arrests'])
    df['total_arrests'] = df['jan_arrests'] + df['feb_arrests'] + df['march_arrests']
    
    plt.figure(figsize=(16,8))
    # plot chart
    ax1 = plt.subplot(121, aspect='equal')
    df.plot(kind='pie', y = 'total_arrests', ax=ax1, autopct='%1.1f%%', 
     startangle=90, shadow=False, labels=df['officer_name'], legend = False, fontsize=14)
    
    # plot table
    ax2 = plt.subplot(122)
    plt.axis('off')
    tbl = table(ax2, df, loc='center')
    tbl.auto_set_font_size(False)
    tbl.set_fontsize(14)
    plt.show()
    

    【讨论】:

    • 怎么保存为jpg?
    • 大家好,仅供参考,您需要将包 'pandas.tools.plotting' 更改为 'pandas.plotting' 才能运行
    • 有没有办法在图中增加total_arrestsMolly 之间的距离,使它们不重叠?或者也许将total_arrests 重新定位在饼图的底部?
    • 我可以在饼图中显示实际计数而不是百分比吗?
    • plt.subplot(121, aspect='equal') 为什么正好是 121
    【解决方案2】:

    一个非常简单的解决方案 df.whatever.value_counts().plot(kind='pie')

    【讨论】:

    • OP 要求的是不同的东西。他们已经知道如何绘制饼图。看问题的第二行代码,和你写的一样。
    • 有没有办法删除小元素,只将它们标记为“其他”?
    • 如何添加百分比文字?
    • @SharkDeng 试试这个来添加这个参数 -> autopct='%1.1f%%' (单精度)
    猜你喜欢
    • 2020-05-31
    • 2013-08-16
    • 2018-03-19
    • 2016-01-07
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    相关资源
    最近更新 更多