- 使用
.melt 将列转换为长格式
- 见
seaborn.boxenplot
- 通过为值指定一个轴,为类别列指定另一个轴进行绘图。
hue= 可用于可视化第三个分类列。
- 不需要图例(对于这种情况),因为每个标签都在轴上,所以有一个图例是多余的
- 可以通过多种方式更改分类轴标签。
- 熔解前更改列名(使用
.rename)
- 熔化后更改列中的值(使用
.map)
- 更改绘图的刻度标签 (
p.set_yticklabels(['Total Bill', 'Tips'])
- 在
python 3.9.7、pandas 1.3.4、matplotlib 3.5.0、seaborn 0.11.2中测试
dfm = expeditions[["nbre_members", "hired_staff"]].melt()
sns.boxenplot(data=dfm, x='value', y='variable')
工作示例
import seaborn as sns
import matplotlib.pyplot as plt
# sample data for wide data
tips = sns.load_dataset('tips')
# display(tips.head(3))
total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
# convert two columns to a long form
dfm = tips[['total_bill', 'tip']].melt()
# display(dfm.head(3))
variable value
0 total_bill 16.99
1 total_bill 10.34
2 total_bill 21.01
# plot
fig, ax = plt.subplots(figsize=(6, 4))
p = sns.boxenplot(data=dfm, x='value', y='variable', ax=ax)
p.set(ylabel='My yLabel', xlabel='My xLabel', title='My Title')
p.set_yticklabels(['Total Bill', 'Tips'])
plt.show()
给定第三列
# melt columns and have an id variable
dfm = tips[['total_bill', 'tip', 'smoker']].melt(id_vars='smoker')
# display(dfm.head(3))
smoker variable value
0 No total_bill 16.99
1 No total_bill 10.34
2 No total_bill 21.01
# plot
fig, ax = plt.subplots(figsize=(6, 4))
p = sns.boxenplot(data=dfm, x='value', y='variable', hue='smoker', ax=ax)
p.set(ylabel='My yLabel', xlabel='My xLabel')
plt.show()