【问题标题】:Python Grouped bar chart. Count doesnt workPython 分组条形图。计数不起作用
【发布时间】:2019-10-11 12:00:46
【问题描述】:

我正在处理一个学校项目,但我一直在制作分组条形图。我在网上找到了这篇文章并有解释:https://www.pythoncharts.com/2019/03/26/grouped-bar-charts-matplotlib/ 现在我有一个数据集,在 Age 列中有一个 Age 列和一个 Sex 列,代表客户的年限和性别,女性为 0,男性为 1。我想绘制男性和女性之间的年龄差异。现在我已经尝试了示例中的以下代码:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import pylab as pyl
fig, ax = plt.subplots(figsize=(12, 8))
x = np.arange(len(data.Age.unique()))
# Define bar width. We'll use this to offset the second bar.
bar_width = 0.4
# Note we add the `width` parameter now which sets the width of each bar.
b1 = ax.bar(x, data.loc[data['Sex'] == '0', 'count'], width=bar_width)
# Same thing, but offset the x by the width of the bar.
b2 = ax.bar(x + bar_width, data.loc[data['Sex'] == '1', 'count'], width=bar_width)

这引发了以下错误:KeyError: 'count'

然后我尝试稍微更改代码并得到另一个错误:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import pylab as pyl
fig, ax = plt.subplots(figsize=(12, 8))
x = np.arange(len(data.Age.unique()))
# Define bar width. We'll use this to offset the second bar.
bar_width = 0.4
# Note we add the `width` parameter now which sets the width of each bar.
b1 = ax.bar(x, (data.loc[data['Sex'] == '0'].count()), width=bar_width)
# Same thing, but offset the x by the width of the bar.
b2 = ax.bar(x + bar_width, (data.loc[data['Sex'] == '1'].count()), width=bar_width)

这引发了错误:ValueError: shape mismatch: objects cannot be broadcast to a single shape

现在我如何计算我做这个分组条形图的结果?

【问题讨论】:

  • 年龄差是什么意思?平均年龄差?分布差异?
  • 请阅读minimal reproducible exampleHow to make good reproducible pandas examples。您得到的错误只是数据框中没有名为 "count" 的列。但人们不知道为什么会这样。
  • 现在我有一个包含 Age 列和 Sex 列的数据集:您的数据没有 'count' 列,您不能这样做:data.loc[data['Sex'] == '0', 'count']跨度>

标签: python pandas numpy matplotlib


【解决方案1】:

似乎这篇文章为了绘制分组图表条而遇到了太多麻烦:

np.random.seed(1)
data = pd.DataFrame({'Sex':np.random.randint(0,2,1000),
                     'Age':np.random.randint(20,50,1000)})

(data.groupby('Age')['Sex'].value_counts()        # count the Sex values for each Age
     .unstack('Sex')                              # turn Sex into columns
     .plot.bar(figsize=(12,6))                    # plot grouped bar
)

使用seaborn 甚至更简单:

fig, ax = plt.subplots(figsize=(12,6))
sns.countplot(data=data, x='Age', hue='Sex', ax=ax)

输出:

【讨论】:

    猜你喜欢
    • 2016-07-07
    • 2022-12-06
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 2021-04-22
    相关资源
    最近更新 更多