Py学习  »  Python

如何根据用户制作的表格绘制多条形图。python中的groupby函数?

userj • 3 年前 • 1646 次点击  

我似乎在将这个表(使用group by函数从数据帧生成)转换为我需要的图形时遇到了一些问题。该表由10个问题组成,用户被要求回答1到5分制的问题,以及每个性别的平均答案。

性别 Q1 问题2。。。。。。。
0(男) 3.7 1.3
1(女) 2.8 3.1
2(其他) 4.2 4.7

它看起来有点像这张桌子,只是它可以容纳所有10个问题。目前我正在使用。使用此表的名称打印函数。它正在打印错误的图形。它正在绘制这个图表:

enter image description here

如果不是这个图表,我希望每个问题的3个不同条代表3个性别。然后,10个问题中的每一个都沿着x轴进行。对于如何实现这一目标的任何帮助,我们都将不胜感激。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131990
文章 [ 1 ]  |  最新文章 3 年前
JohanC
Reply   •   1 楼
JohanC    3 年前

目前尚不清楚您的数据是如何组织的,也不清楚您是如何创建表的。

假设输入数据有三列:“性别”、“问题”、“标记”。以下是该表格中的一些数据,以便进行测试:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({'gender': np.random.choice(['male', 'female', 'other'], 1000),
                   'question': pd.Categorical.from_codes(codes=np.random.randint(0, 10, 1000),
                                                         categories=[f'Q{i}' for i in range(1, 11)]),
                   'mark': np.random.randint(1, 6, 1000)})
df['gender'] = pd.Categorical(df['gender'], categories=['male', 'female', 'other'])  # fix an order

然后可以通过 df.pivot_table(index='gender', columns='question', values='mark') 并将其绘制为条形图,类似于问题的图像:

df.pivot_table(index='gender', columns='question', values='mark').plot.bar(rot=0, width=0.8)

pandas bar plot from pivot table

现在,以另一种方式创建pivot_表,将问题放置为x位置,将性别放置为颜色:

df.pivot_table(index='question', columns='gender', values='mark').plot.bar(rot=0, width=0.8)

pandas bar plot from transposed pivot table

如果已经创建了表格,则可以在打印前对其进行转置,这也会导致x轴出现问题:

df_table = df.pivot_table(index='gender', columns='question', values='mark')
df_table.T.plot.bar(rot=0, width=0.8)

另一种方法是使用seaborn,它直接从原始数据帧创建条形图,并且(可选)显示错误条(使用 ci=None 以抑制错误条)。你只需要告诉seaborn你想在x轴上看到什么,在y轴上看到什么,以及什么是彩色分离。

import seaborn as sns

ax = sns.barplot(data=df, x='question', y='mark', hue='gender')
ax.legend(bbox_to_anchor=[1.01, 1.01], loc='upper left')
plt.tight_layout()
plt.show()

sns.barplot using hue

现在,如果您的数据帧看起来像:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({'Gender': np.arange(3),
                   **{f'Q{i}': np.random.randint(15, 46, 3) / 10 for i in range(1, 11)}})

例如:

  Gender   Q1   Q2   Q3   Q4   Q5   Q6   Q7   Q8   Q9  Q10
0      0  3.9  2.7  2.2  2.6  2.2  2.8  2.2  3.2  2.9  2.9
1      1  4.2  2.0  4.4  2.4  3.6  2.1  1.6  4.0  2.7  4.2
2      2  3.7  3.9  4.2  2.9  3.2  4.4  4.2  2.1  2.9  3.6

您可以使用专有名称对“性别”列进行分类,将其用作索引,转换数据帧和绘图:

df['Gender'] = pd.Categorical.from_codes(df['Gender'], categories=['Male', 'Female', 'Other'])
df.set_index('Gender').T.plot.bar(rot=0, width=0.8)