【问题标题】:Make a pie in matplotlib from a column从一列在 matplotlib 中制作一个饼图
【发布时间】:2019-02-15 22:03:44
【问题描述】:

我有一个df,它有很多列。我需要使用users 列制作馅饼,并根据number 列显示。

users  number   col1  col2
user1   1        12    abc
user2   34       13    ..
user3   56       12
user4   45       ..
user5   4
user1   3
user5   11
user1   3

如何根据用户在数字列中的百分比来做饼图?这样可以清楚谁的数字占整体的百分比更高。如果你需要澄清问我。谢谢

我做到了:

plt.pie(x['users'],x['number'])

但它说:

ValueError: could not convert string to float: 'user11'

【问题讨论】:

标签: python pandas matplotlib statistics pandas-groupby


【解决方案1】:

pie 函数只取 1 个值作为每个饼的大小,你必须明确指定标签为 'label = x['users']' 你可以找到更详细的参数理解 @987654321 @!

因此,您的代码将是这样的:

plt.pie(x['number'],labels = x['users'])

【讨论】:

    【解决方案2】:

    这是一个最小的工作解决方案,它采用一列并根据您的示例数据框以用户方式绘制它们的总和。虽然这可能不是最聪明的方法,但它可以满足您的需求。

    import pandas as pd
    
    df = pd.DataFrame({'number': [1,34,56,45,4, 3, 11, 3], 
                      'users':['user1','user2','user3','user4','user5', 'user1','user5','user1']})
    df1 = df.groupby(['users']).sum().reset_index()
    df1 = df1.set_index('users')
    plot = df1.plot.pie(y='number', figsize=(6, 6))
    

    输出

    【讨论】:

    • user1,user2.. 是列而不是索引。我无法让它在我的示例中起作用。
    • 奇怪。它对我有用,但我仍然编辑。试试新的答案,让我知道
    • 我的数据集中存在更多列会使事情变得复杂吗?
    • 使用plot = df.plot.pie(y='number', figsize=(6, 6))有什么收获
    • 我得到了一个包含数据集 158 的所有行的饼图。这不是我想要的。解决方案是获取每个用户分组的number 的总和。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多