当通过hue偏移时,如何将图表居中对齐于xticks

7
我的箱线图似乎与绘图的x轴刻度不对齐。如何使箱线图与x轴刻度对齐?
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame([['0', 0.3],['1', 0.5],['2', 0.9],
                   ['0', 0.8],['1', 0.3],['2', 0.4],
                   ['0', 0.4],['1', 0.0],['2', 0.7]])

df.columns = ['label', 'score']

label_list = ['0', '1', '2']

fig = plt.figure(figsize=(8, 5))
g=sns.boxplot(x='label', y='score', data=df, hue='label', hue_order=label_list)
g.legend_.remove()

plt.show()

enter image description here


5
移除 hue='label', hue_order=label_list,这会导致条形图发生偏移。 - ImportanceOfBeingErnest
2个回答

13

您可以在boxplot行中添加dodge=False,这样就可以解决这个问题了。 更新后的代码如下:

g=sns.boxplot(x='label', y='score', data=df, hue='label', hue_order=label_list, dodge=False)

enter image description here

您可以使用width控制箱线图的宽度(默认宽度为0.8),从而进行调整,实现自己想要的效果,如下所示:

g=sns.boxplot(x='label', y='score', data=df, hue='label', hue_order=label_list, dodge=False, width=.2)

enter image description here


0
根据《重要性的本质》所述,删除hue='label', hue_order=label_list。这是导致箱子移动的原因。 适用于sns.catplot和相关的轴级别分类图hue应该用于编码不同的类别集合,而不是多次编码相同的类别'label''label'类别已经在x轴上编码了。同样,不需要图例,因为信息已经在x轴上编码了。
以下是一些关于图形感知和颜色使用的引用。
虽然一些软件包,如ggplotseaborn,可能会用颜色对x轴上的每个类别进行编码,但最好避免不必要的颜色使用
来自Stephen Few, Perceptual Edge的《在图表中使用颜色的实用规则》中的有意义且克制地使用颜色部分:这个图表中的颜色使用没有意义,应该避免。
- 只在需要达到特定传达目标时使用颜色。 - 只在数据的含义有所不同时使用不同的颜色。 作为一般参考,请参阅《图形感知和分析科学数据的图形方法》,由William S. Cleveland和Robert McGill撰写,发表于New Series, Vol. 229, No. 4716 (Aug. 30, 1985), pp. 828-833 (6 pages),由美国科学促进会出版。 弗吉尼亚理工大学

默认情节,不带hue

ax = sns.boxplot(data=df, x='label', y='score')
_ = ax.set(title='Default Plot\nUnnecessary Use of Color')

enter image description here

只用一种颜色的情节
ax = sns.boxplot(data=df, x='label', y='score', color='tab:blue')
_ = ax.set(title='Avoid Unnecessary Use of Color')

enter image description here


如果x轴上的类别顺序很重要,而且没有正确排序,可以实施以下选项之一: 1. 使用order参数指定顺序。
  • order=['0', '1', '2']order=label_list
2. 将df列转换为category Dtype类型,使用pd.Categorical函数。
  • df.label = pd.Categorical(values=df.label, categories=label_list, ordered=True)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接