【问题标题】:Python Pandas Pivot tables to pie chartPython Pandas 数据透视表到饼图
【发布时间】:2014-04-27 23:15:52
【问题描述】:

使用总数的百分比(数据透视表中所有数据的总和)将以下数据透视表中的所有非零值更改为饼图的最佳方法是什么?

import pandas as pd
import matplotlib.pyplot as plt

df=pd.DataFrame({'axis1': ['Unix','Window','Apple','Linux'],
                 'A': [3,0,1,10],
                 'B': [1,0,0,0],
                 'C': [0,30,0,20],
                 'D': [1,0,12,0],
                 }).set_index(['axis1'])

输出:

>>> df
         A  B   C   D
axis1                
Unix     3  1   0   1
Window   0  0  30   0
Apple    1  0   0  12
Linux   10  0  20   0

[4 rows x 4 columns]

所以基本上我想从存在值的数据透视表中创建一个饼图,并使用诸如“Unix A”之类的标签,其值为表中所有内容的 3/sum=%。

【问题讨论】:

    标签: python-3.x matplotlib pandas


    【解决方案1】:

    您可以使用 matplotlib 绘制饼图(例如,参见 http://matplotlib.org/1.2.1/examples/pylab_examples/pie_demo.html)。

    首先堆叠您的数据(因此不同的列成为索引级别,请参阅stack docs),然后仅选择正数:

    In [13]: s = df.stack()
    
    In [14]: s = s[s>0]
    
    In [15]: s
    Out[15]: 
    axis1    
    Unix    A     3
            B     1
            D     1
    Window  C    30
    Apple   A     1
            D    12
    Linux   A    10
            C    20
    dtype: int64
    

    然后您可以使用 matplotlib pie 绘制此图(对于标签,我将两个级别的索引粘贴到列表理解中):

    In [16]: fig, ax = plt.subplots()
        ...: ax.pie(s, labels=["{0} {1}".format(l1, l2) for l1, l2 in s.index], 
        ...:        autopct='%1.1f%%')
    

    导致此输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-08
      相关资源
      最近更新 更多