在Seaborn情节中作为X的星期几

问题描述 投票:1回答:2

我有一个包含点击次数和展示次数的数据集,我使用groupby和agg在星期几汇总它们

df2=df.groupby('day_of_week',as_index=False, sort=True, group_keys=True).agg({'Clicks':'sum','Impressions':'sum'})

然后我试图用子图绘制它们

f, axes = plt.subplots(2, 2, figsize=(7, 7))
sns.countplot(data=df2['Clicks'], x=df2['day_of_week'],ax=axes[0, 0])
sns.countplot(data=df2["Impressions"], x=df2['day_of_week'],ax=axes[0, 1])

但是使用星期几作为X,情节使用点击次数和展示次数中的值。有没有办法强制X到星期几,而值是在Y?谢谢。

完整代码

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

sns.set_style("whitegrid")

df=pd.read_csv('data/data_clean.csv')

df2=df.groupby('day_of_week',as_index=False, sort=True, group_keys=True).agg({'Clicks':'sum','Impressions':'sum'})

f, axes = plt.subplots(2, 2, figsize=(7, 7))
sns.countplot(data=df2['Clicks'], x=df2['day_of_week'],ax=axes[0, 0])
sns.countplot(data=df2["Impressions"], x=df2['day_of_week'],ax=axes[0, 1])

plt.show()

假数据:

day_of_week,Clicks,Impressions
 0           100       2000
 1           400       4000
 2           300       3500
 3           200       2000
 4           100       1000
 5           50        500
 6           10        150
python-3.x pandas matplotlib seaborn
2个回答
1
投票

根据seaborn文档,我认为countplot期望一个长形式的数据框,例如你的df,而不是你建立并传递给你的问题的预先汇总的df2countplot为你做计算。

但是,你的df2已经准备好了大熊猫的情节:

df2.plot(kind='bar', y=['Impressions', 'Clicks'])

结果:pandas bar plot of df2


1
投票

在Peter的指导下,我能够找到seaborn的答案。

正确的绘图代码是

sns.barplot( x=df2['day_of_week'],y=df2['Clicks'] , color="skyblue", ax=axes[0, 0])
sns.barplot( x=df2['day_of_week'],y=df2['Impressions'] , color="olive", ax=axes[0, 1])

默认情况下似乎seaborn会将第一个变量视为X而不是Y.

© www.soinside.com 2019 - 2024. All rights reserved.