分组变量以绘制多级条形图

发布于 2025-02-13 07:42:00 字数 619 浏览 1 评论 0原文

您能帮我帮助我吗?我有一个具有可变数量的产品(产品)的数据集,该数据集将离散值从1到3(随附)获取。然后,我有一个男性变量(性别)1,女性为0。我想绘制一个多级条形图,在x轴上我有数量的产品(prod),而在y轴上,我具有由性别分组的这些产品的总价值。我需要创建一个“计数”变量,该变量计算每个“性别”类别中每个“产品”的观察值。要分组和绘制变量,我使用以下代码(不起作用):

#Group the variables
grouped_gender['count'] = main_data.groupby(['Prod', 'Gender'])[['Prod']].count()
grouped_gender = pd.DataFrame(grouped_gender)

#Plot
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10, 7))

barplot2 = sns.barplot(
    data=grouped_gender,
    x='Prod',
    y='count',
    hue='Gender',
    orient='v',
    ax = axes,
    ci=None,
    dodge=False
    )

您可以帮助我确定问题吗?

Can you please help me with the following. I have a dataset with a variable - number of products (Prod) that takes discrete values from 1 to 3 (included). Then I have a variable (Gender) 1 for males, 0 for females. I want to plot a multilevel bar chart where on the x-axis I have number of products (Prod) and on the y-axis I have total value of these products that are grouped by the Gender. I need to create a 'count' variable that counts how many observations of each 'Prod' are in each 'Gender' category. To group and plot the variables I use the following code (which does not work):

#Group the variables
grouped_gender['count'] = main_data.groupby(['Prod', 'Gender'])[['Prod']].count()
grouped_gender = pd.DataFrame(grouped_gender)

#Plot
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10, 7))

barplot2 = sns.barplot(
    data=grouped_gender,
    x='Prod',
    y='count',
    hue='Gender',
    orient='v',
    ax = axes,
    ci=None,
    dodge=False
    )

Can you please help me to identify the problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

翻身的咸鱼 2025-02-20 07:42:00

假设您可以将数据框放在与我的类似状态下,

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

grouped_gender = pd.DataFrame(
    {
        "Man": [50, 70],
        "Woman": [90, 30]
    },
    index=["Product1", "Product2"]
)

grouped_gender.plot(kind="bar", stacked=True)

plt.title("Products sales")
plt.xlabel("Products")
plt.ylabel("Sales")
plt.show()

这会产生以下结果 ”在此处输入图像描述”

Assuming you can put your DataFrame in a similar state as mine

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

grouped_gender = pd.DataFrame(
    {
        "Man": [50, 70],
        "Woman": [90, 30]
    },
    index=["Product1", "Product2"]
)

grouped_gender.plot(kind="bar", stacked=True)

plt.title("Products sales")
plt.xlabel("Products")
plt.ylabel("Sales")
plt.show()

This produces the following resultenter image description here

疯狂的代价 2025-02-20 07:42:00

使用Countplot在原始数据集上:

# sample dataset
df = sns.load_dataset('tips')

# `day` plays `Prod`, `sex` plays `Gender`
sns.countplot(x='day', hue='sex', data=df)

输出:

”在此处输入图像描述”

注意:如果您需要数据,而不仅仅是图,请使用:

counts = pd.crosstab(df['day'], df['sex'])

# then to plot bar chart
# counts.plot.bar()

它给您:

sex   Male  Female
day               
Thur    30      32
Fri     10       9
Sat     59      28
Sun     58      18

Use countplot on the original dataset:

# sample dataset
df = sns.load_dataset('tips')

# `day` plays `Prod`, `sex` plays `Gender`
sns.countplot(x='day', hue='sex', data=df)

Output:

enter image description here

Note: if you want the data, not just the plot, use:

counts = pd.crosstab(df['day'], df['sex'])

# then to plot bar chart
# counts.plot.bar()

which gives you:

sex   Male  Female
day               
Thur    30      32
Fri     10       9
Sat     59      28
Sun     58      18
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文