为groupby中的唯一结果生成饼图子图?

2024-04-26 09:33:44 发布

您现在位置:Python中文网/ 问答频道 /正文

为数据帧中的唯一值生成饼图的最佳方法是什么?在

我有一个按县显示服务数量的数据框。我想为每个县制作一组饼图,显示该县的服务数量。我尝试过各种不同的方法,但没有成功。在

这是我的数据

打印(mdfgroup)

    County     Service    ServiceCt
0   Alamance    Literacy          1
1   Alamance   Technical          1
2   Alamance  Vocational          4
3    Chatham    Literacy          3
4    Chatham   Technical          2
5    Chatham  Vocational          1
6     Durham    Literacy          1
7     Durham   Technical          1
8     Durham  Vocational          1
9     Orange    Literacy          1
10      Wake    Literacy          2
11      Wake   Technical          2

所以阿拉曼斯会有一张图表,上面有识字、技术、职业的切片;查塔姆、达勒姆等的图表。切片大小将基于ServiceCt。在

我已经尝试了很多不同的方法,但我不确定什么是最有效的。我试过了,但下面并没有按县划分,也没有生成任何图表。在

^{pr2}$

这将引发一个错误:

TypeError: len() of unsized object

然后生成一个空白的绘图框

(我还不能嵌入图像,所以这里是链接) Blank Plot Box

理想的情况下,我希望它们都是次情节,但在这个阶段,我会采取一系列单独的情节。我发现的其他示例不处理键(县)的唯一值。在


Tags: 数据方法数量图表切片情节countywake
2条回答

使用matplotlib

一种常见的方法是迭代列的groupby。这里要迭代的列是"Country"。您可以首先创建一个子批次网格,其中至少包含与您具有唯一国家/地区相同数量的子批次。然后您可以同时迭代子批次和组。
最后可能有一些空的子批次;这些子批次可以设置为不可见。在

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"Country" : list("AAACCCDDDOWW"),
                   "Service" : list("LTV")*4,
                   "ServiceCt" : list(map(int, "114321111122"))})

cols = 3
g = df.groupby("Country")
rows = int(np.ceil(len(g)/cols))

fig, axes = plt.subplots(ncols=cols, nrows=rows)

for (c, grp), ax in zip(g, axes.flat):
    ax.pie(grp.ServiceCt, labels=grp.Service)
    ax.set_title(c)

if len(g) < cols*rows:    
    for ax in axes.flatten()[len(g):]:
        ax.axis("off")

plt.show()

enter image description here

使用seaborn

这个案例实际上非常适合与seaborn的FacetGrid一起使用。在

^{pr2}$

enter image description here

使用熊猫

最后,我们可以使用熊猫在一条线上完成所有任务。在

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"Country" : list("AAACCCDDDOWW"),
                   "Service" : list("LTV")*4,
                   "ServiceCt" : list(map(int, "114321111122"))})


df.pivot("Service", "Country", "ServiceCt").plot.pie(subplots=True, legend=False)

plt.show()

enter image description here

这就是你想要的吗?在

Ncounties = len(mdfgroup.County.unique())
fig, axs = plt.subplots(1, Ncounties, figsize=(3*Ncounties,3), subplot_kw={'aspect':'equal'})
for ax,(groupname,subdf) in zip(axs,mdfgroup.groupby('County')):
    ax.pie(subdf.ServiceCt, labels=subdf.Service)
    ax.set_title(groupname)

enter image description here

相关问题 更多 >