How to center align the plot over the xticks when offset by hue
Asked Answered
D

2

7

My boxplot seem not align with the x-tick of the plot. How to make the boxplot align with the x-tick?

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

Disorientate answered 28/11, 2019 at 0:55 Comment(0)
E
13

You can add dodge=False into your boxplot line & that should fix this. That updated code would be as below

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

enter image description here

You can then play with width to control the width (default width is 0.8) of box plots like below

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

enter image description here

Emphasis answered 28/11, 2019 at 2:18 Comment(0)
O
0

Default Plot Without hue

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

enter image description here

Plot With a Single Color

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

enter image description here


  • If the order of categories on the x-axis is important, and not correctly ordered, one of the following options can be implemented:
    1. Specify the order with the order parameter.
      • order=['0', '1', '2'] or order=label_list
    2. Convert the df column to a category Dtype with pd.Categorical
      • df.label = pd.Categorical(values=df.label, categories=label_list, ordered=True)
Oven answered 1/6, 2023 at 18:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.