【问题标题】:I want to plot 2 variables in a pie chart in python我想在 python 的饼图中绘制 2 个变量
【发布时间】:2019-10-06 19:15:13
【问题描述】:

我想在一个条形图中绘制 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

知道如何让它工作吗?

【问题讨论】:

  • 请显示您的df_master 数据框的内容。
  • @Diziet Asahi 我展示了内容。

标签: python matplotlib seaborn


【解决方案1】:

您没有包含数据框的样本。请下次做。我生成了一个如下所示的随机 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将数据放入“long”格式。

# 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())

剩下的交给你。阅读 pie charts 并随意使用 explodecolorsshadow 等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 2014-02-24
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    • 2021-04-21
    相关资源
    最近更新 更多