[英]seaborn boxplot and stripplot points aren't aligned over the x-axis by hue
I have the following code to draw a boxplot and overlay all data points on the bars.我有以下代码来绘制箱线图并覆盖条形图上的所有数据点。
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy.random as rnd
f = plt.figure(figsize=[18,12])
ax = f.add_subplot(111)
sns.boxplot(x='month', y='ffdi', hue='scenario', data=df_diff_concat, ax=ax)
sns.stripplot(x="month", y="ffdi",hue='scenario', data=df_diff_concat, ax=ax)
The data points are not vertically aligned with the middleline of the bar they belong to.数据点未与它们所属的条的中线垂直对齐。
How can this be fixed?如何解决这个问题?
dodge=True
in seaborn.stripplot
, otherwise the values are plotted as a single group centered over the x-tick在seaborn.stripplot
中使用dodge=True
,否则这些值将绘制为以 x-tick 为中心的单个组kind='bar'
can be replaced with kind='box'
请参阅如何在条形图图形级 plot 上叠加数据点,其中kind='bar'
可以替换为kind='box'
python 3.8.11
, matplotlib 3.4.3
, seaborn 0.11.2
在python 3.8.11
、 matplotlib 3.4.3
、 seaborn 0.11.2
中测试import seaborn as sns
# load the dataframe
tips = sns.load_dataset('tips')
ax = sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="GnBu")
# add stripplot with dodge=True
sns.stripplot(x="day", y="total_bill", hue="smoker", data=tips, palette="GnBu", dodge=True, ax=ax, ec='k', linewidth=1)
# remove extra legend handles
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[:2], labels[:2], title='Smoker', bbox_to_anchor=(1, 1.02), loc='upper left')
jitter=False
, but all data points won't show when there's overlap.要将所有点都放在一行中,还要设置jitter=False
,但当有重叠时,所有数据点都不会显示。ax = sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="GnBu")
# add stripplot with dodge=True
sns.stripplot(x="day", y="total_bill", hue="smoker", data=tips, palette="GnBu",
dodge=True, ax=ax, ec='k', linewidth=1, jitter=False)
# remove extra legend handles
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[:2], labels[:2], title='Smoker', bbox_to_anchor=(1, 1.02), loc='upper left')
seaborn.swarmplot
, which is similar to stripplot()
, but the points are adjusted (only along the categorical axis) so that they don't overlap.使用seaborn.swarmplot
,它类似于stripplot()
,但点被调整(仅沿分类轴),使它们不重叠。ax = sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="GnBu")
# add stripplot with dodge=True
sns.swarmplot(x="day", y="total_bill", hue="smoker", data=tips, palette="GnBu",
dodge=True, ax=ax, ec='k', linewidth=1, size=3)
# remove extra legend handles
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[:2], labels[:2], title='Smoker', bbox_to_anchor=(1, 1.02), loc='upper left')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.