简体   繁体   English

如何在 Python 中的 Matplotlib 中绘制嵌套饼图?

[英]How can I draw a nested pie graph in Matplotlib in Python?

I have a problem about drawing a nested pie graph in Matplotlib in Python.我在 Python 中的 Matplotlib 中绘制嵌套饼图时遇到问题。 I wrote some codes to handle with this process but I have an issue related with design and label我写了一些代码来处理这个过程,但我有一个与设计和 label 相关的问题

I'd like to draw a kind of this nested pie graph.我想画一种这种嵌套的饼图。 (from the uppermost layer of the nested to its innermost is SEX, ALIGN with covering their counts) (从嵌套的最上层到最里面是SEX,ALIGN用覆盖它们的计数)

Here is my dataframe which is shown below.这是我的 dataframe,如下所示。

ALIGN   SEX count
2   Bad Characters  Male Characters 1542
5   Good Characters Male Characters 1419
3   Good Characters Female Characters   714
0   Bad Characters  Female Characters   419
8   Neutral Characters  Male Characters 254
6   Neutral Characters  Female Characters   138
1   Bad Characters  Genderless Characters   9
4   Good Characters Genderless Characters   4
7   Neutral Characters  Genderless Characters   3
9   Reformed Criminals  Male Characters 2

Here is my code snippets related with showing nested pie graph which is shown below.这是我与显示嵌套饼图相关的代码片段,如下所示。

fig, ax = plt.subplots(figsize=(24,12))
size = 0.3

ax.pie(dc_df_ALIGN_SEX.groupby('SEX')['count'].sum(), radius=1,
       labels=dc_df_ALIGN_SEX['SEX'].drop_duplicates(),
       autopct='%1.1f%%',
       wedgeprops=dict(width=size, edgecolor='w'))

ax.pie(dc_df_ALIGN_SEX['count'], radius=1-size, labels = dc_df_ALIGN_SEX["ALIGN"],
       wedgeprops=dict(width=size, edgecolor='w'))

ax.set(aspect="equal", title='Pie plot with `ax.pie`')
plt.show()

How can I design 4 row and 4 column and put each one in each slot and showing labels in legend area?如何设计 4 行 4 列并将每一个放在每个插槽中并在图例区域显示标签?

Since the question has been changed, I'm posting a new answer.由于问题已更改,因此我发布了一个新答案。

First, I slightly simplified your DataFrame:首先,我稍微简化了您的 DataFrame:

import pandas as pd

df = pd.DataFrame([['Bad', 'Male', 1542],
                   ['Good', 'Male', 1419],
                   ['Good', 'Female', 714],
                   ['Bad', 'Female', 419],
                   ['Neutral', 'Male', 254],
                   ['Neutral', 'Female', 138], 
                   ['Bad', 'Genderless', 9], 
                   ['Good', 'Genderless', 4],
                   ['Neutral', 'Genderless', 3], 
                   ['Reformed', 'Male', 2]])
df.columns = ['ALIGN', 'SEX', 'n']

For the numbers in the outer ring, we can use a simple groupby , as you did:对于外环中的数字,我们可以像您一样使用简单的groupby

outer = df.groupby('SEX').sum()

But for the numbers in the inner ring, we need to group by both categorical variables, which results in a MultiIndex:但是对于内环中的数字,我们需要按两个分类变量进行分组,这会产生一个 MultiIndex:

inner = df.groupby(['SEX', 'ALIGN']).sum()
inner
                     n
SEX         ALIGN   
Female      Bad      419
            Good     714
            Neutral  138
Genderless  Bad        9
            Good       4
            Neutral    3
Male        Bad     1542
            Good    1419
            Neutral  254
            Reformed   2

We can extract the appropriate labels from the MultiIndex with its get_level_values() method:我们可以使用它的get_level_values()方法从 MultiIndex 中提取适当的标签:

inner_labels = inner.index.get_level_values(1)

Now you can turn the above values into one-dimensional arrays and plug them into your plot calls:现在您可以将上述值转换为一维 arrays 并将它们插入您的 plot 调用中:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(24,12))
size = 0.3

ax.pie(outer.values.flatten(), radius=1,
       labels=outer.index,
       autopct='%1.1f%%',
       wedgeprops=dict(width=size, edgecolor='w'))

ax.pie(inner.values.flatten(), radius=1-size, 
       labels = inner_labels,
       wedgeprops=dict(width=size, edgecolor='w'))

ax.set(aspect="equal", title='Pie plot with `ax.pie`')
plt.show()

嵌套饼图

You define the function percentage_growth(l) in a way that supposes its argument l to be a list (or some other one-dimensional object).您定义 function percent_growth percentage_growth(l)的方式假设它的参数l是一个列表(或其他一些一维对象)。 But then (to assign colors ) you call this function on dc_df_ALIGN_SEX , which is apparently your DataFrame.但是然后(分配colors )你在 dc_df_ALIGN_SEX 上调用这个dc_df_ALIGN_SEX ,这显然是你的 DataFrame。 So the function (in the first iteration of its loop) tries to evaluate dc_df_ALIGN_SEX[0] , which throws the key error, because that is not a proper way to index the DataFrame.因此 function(在其循环的第一次迭代中)尝试评估dc_df_ALIGN_SEX[0] ,这会引发关键错误,因为这不是索引 DataFrame 的正确方法。

Perhaps you want to do something like percentage_growth(dc_df_ALIGN_SEX['count']) instead?也许您想做类似percentage_growth(dc_df_ALIGN_SEX['count'])事情?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM