简体   繁体   English

seaborn 箱线图和条形图点未按色调在 x 轴上对齐

[英]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?如何解决这个问题?

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')

在此处输入图像描述

  • To get the points all in a single line, also set 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')

在此处输入图像描述

  • Use 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM