使用 seaborn 的单个箱线图中的多列
Multiple column in a single boxplot using seaborn
与此相关
我想像这样将它们分组到一个箱线图中。
但是我在使用这段代码时遇到了问题。
cn = ['AgeUnder18', 'Age19to25', 'Age26to29']
sns.boxplot(x=cn, y='AveMonthSpend', data=df)
错误:
The truth value of a Series is ambiguous. Use a.empty, a.bool(),
a.item(), a.any() or a.all().
您需要将数据帧转换为 "long form":
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
cn = ['AgeUnder18', 'Age19to25', 'Age26to29']
df = pd.DataFrame({age_group: np.random.uniform(45, 65, 7) for age_group in cn})
df_melted = df.melt(value_vars=cn, value_name='AveMonthSpend', var_name='Age Bin')
sns.boxplot(y='Age Bin', x='AveMonthSpend', data=df_melted, palette='Greys')
plt.tight_layout()
plt.show()
假设原始数据框如下所示:
Out[10]:
AgeUnder18 Age19to25 Age26to29
0 64.980248 64.673755 56.489776
1 59.858895 48.921889 62.877826
2 62.357871 51.599347 55.651448
3 47.206124 45.817266 52.893839
4 57.627501 51.820863 59.616511
5 61.999523 63.443241 45.919390
6 56.616062 48.353018 46.282314
与此相关
我想像这样将它们分组到一个箱线图中。
但是我在使用这段代码时遇到了问题。
cn = ['AgeUnder18', 'Age19to25', 'Age26to29']
sns.boxplot(x=cn, y='AveMonthSpend', data=df)
错误:
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
您需要将数据帧转换为 "long form":
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
cn = ['AgeUnder18', 'Age19to25', 'Age26to29']
df = pd.DataFrame({age_group: np.random.uniform(45, 65, 7) for age_group in cn})
df_melted = df.melt(value_vars=cn, value_name='AveMonthSpend', var_name='Age Bin')
sns.boxplot(y='Age Bin', x='AveMonthSpend', data=df_melted, palette='Greys')
plt.tight_layout()
plt.show()
假设原始数据框如下所示:
Out[10]:
AgeUnder18 Age19to25 Age26to29
0 64.980248 64.673755 56.489776
1 59.858895 48.921889 62.877826
2 62.357871 51.599347 55.651448
3 47.206124 45.817266 52.893839
4 57.627501 51.820863 59.616511
5 61.999523 63.443241 45.919390
6 56.616062 48.353018 46.282314