当色调偏移时,如何在 xticks 上居中对齐绘图

问题描述 投票:0回答:2

我的箱线图似乎与图的 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()

python seaborn bar-chart boxplot violin-plot
2个回答
13
投票

您可以将

dodge=False
添加到您的
boxplot
行中,这应该可以解决此问题。 更新后的代码如下

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

然后您可以使用

width
来控制箱线图的宽度(默认宽度为 0.8),如下所示

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


-1
投票
ax = sns.boxplot(data=df, x='label', y='score')
ax.set(title='Default Plot: Unnecessary Usage of Color')

ax = sns.boxplot(data=df, x='label', y='score', color='tab:blue')
ax.set(title='Avoids Unnecessary Usage of Color')


  • 如果 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)
© www.soinside.com 2019 - 2024. All rights reserved.