我的箱线图似乎与图的 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()
hue='label', hue_order=label_list
。它负责移动条形。hue
应该用于对不同类别的变量进行编码,而不是多次对同一类别 'label'
进行编码。
'label'
类别已在 x 轴上编码。同样,不需要图例,因为信息已经在 x 轴上编码。ggplot
和 seaborn
)可能会使用颜色对 x 轴上的每个类别进行编码,但最好避免不必要地使用颜色。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')
order
参数指定顺序。
order=['0', '1', '2']
或 order=label_list
df
将 category Dtype
列转换为
pd.Categorical
df.label = pd.Categorical(values=df.label, categories=label_list, ordered=True)