首页 > 解决方案 > 我想在 python 的饼图中绘制 2 个变量

问题描述

我想在一个条形图中绘制 2 个变量,所以图表如下所示:

图表

我尝试了这段代码,取自另一篇文章,但它给出了一个奇怪的图表:

data1 = df_master['doggo']
data2 = df_master['floofer']

# create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(1, 2)

plt.figure(0)
ax1.pie(data1)

plt.figure(1)
ax2.pie(data2)

plt.show();

第二张图表

数据框具有以下内容:

tweet_id                         2321 non-null object
in_reply_to_status_id_x          68 non-null float64
in_reply_to_user_id_x            68 non-null float64
timestamp                        2321 non-null object
text                             2321 non-null object
expanded_urls                    2271 non-null object
name                             1601 non-null object
doggo                            2321 non-null int64
floofer                          2321 non-null int64
pupper                           2321 non-null int64
puppo                            2321 non-null int64
rating                           2321 non-null float64

知道如何使它工作吗?

标签: pythonmatplotlibseaborn

解决方案


您没有包含数据框的样本。请下次做。我生成了一个如下所示的随机 df:

   pupper  floofer  doggo  puppo
0       3        3      4      5
1       6        2      3      7
2       4        8      6      0
3       2        5      5      6
4       7        4      5      3

然后我将数据放入“”格式中melt

# put the data into the long format
df = df.melt(var_name='source')

现在它有更多行,但只有两列。来源和价值。

   source  value
0  pupper      3
1  pupper      6
2  pupper      4
3  pupper      2
4  pupper      7
395  puppo      5
396  puppo      6
397  puppo      4
398  puppo      2
399  puppo      9

然后,我对每个源的值求和并将其传递给plt.pie

plt.pie(df.groupby('source')['value'].sum())

我会把剩下的留给你。阅读饼图并随意玩弄爆炸颜色阴影等。


推荐阅读