【问题标题】:How to set a categorical axis in order in Seaborn boxplot?如何在 Seaborn 箱线图中按顺序设置分类轴?
【发布时间】:2018-08-15 10:22:43
【问题描述】:

我有一个数据框,我想根据其中的一列绘制箱线图和颜色:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

data = {'Age': [50, 30, 38, 43, 26, 30, 38, 46, 37, 43, 55, 29, 31, 31, 33, 34, 32, 25, 25, 40, 29, 34, 26, 30, 26, 30, 38, 29, 46, 30, 28, 26, 28, 61, 21, 44, 30, 30, 28, 66, 34, 40, 25, 44, 30, 27, 34, 24, 42, 57, 28, 23, 49, 34, 55, 28, 36, 33, 34, 26],
        'Age Bin': ['(47.0, 51.0]', '(28.0, 33.0]', '(37.0, 42.0]', '(42.0, 47.0]', '(23.0, 28.0]', '(28.0, 33.0]', '(37.0, 42.0]', '(42.0, 47.0]', '(33.0, 37.0]', '(42.0, 47.0]', '(51.0, 56.0]', '(28.0, 33.0]', '(28.0, 33.0]', '(28.0, 33.0]', '(28.0, 33.0]', '(33.0, 37.0]', '(28.0, 33.0]', '(23.0, 28.0]', '(23.0, 28.0]', '(37.0, 42.0]', '(28.0, 33.0]', '(33.0, 37.0]', '(23.0, 28.0]', '(28.0, 33.0]', '(23.0, 28.0]', '(28.0, 33.0]', '(37.0, 42.0]', '(28.0, 33.0]', '(42.0, 47.0]', '(28.0, 33.0]', '(23.0, 28.0]', '(23.0, 28.0]', '(23.0, 28.0]', '(56.0, 61.0]', '(18.0, 23.0]', '(42.0, 47.0]', '(28.0, 33.0]', '(28.0, 33.0]', '(23.0, 28.0]', '(61.0, 66.0]', '(33.0, 37.0]', '(37.0, 42.0]', '(23.0, 28.0]', '(42.0, 47.0]', '(28.0, 33.0]', '(23.0, 28.0]', '(33.0, 37.0]', '(23.0, 28.0]', '(37.0, 42.0]', '(56.0, 61.0]', '(23.0, 28.0]', '(18.0, 23.0]', '(47.0, 51.0]', '(33.0, 37.0]', '(51.0, 56.0]', '(23.0, 28.0]', '(33.0, 37.0]', '(28.0, 33.0]', '(33.0, 37.0]', '(23.0, 28.0]'],
        'Values': [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
        'Class': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]}

data = pd.DataFrame(data, columns=['Age','Age Bin', 'Values', 'Class'])

fig = plt.figure(figsize=(10,5))
sns.boxplot(x='Age Bin', y="Values", hue='Class', data=data)
plt.xticks(rotation=45)

这会产生以下情节:

可以看出,x 轴上的值不是按升序排列的。我该如何解决这个问题?

【问题讨论】:

  • x 轴标签的顺序与您在“Age Bin”中提供的 bin 的顺序相同。您是否尝试过在绘图前按“年龄 Bin”排序?
  • Age Bin 值对应于Age 值;这就是为什么我展示了这两列,尽管在这个例子中我只使用了Age Bins。那么,除非我按照Age对dataframe进行排序,有没有其他的解决方案?
  • 您可能想查看order 参数in the documentation

标签: python matplotlib plot graph seaborn


【解决方案1】:

您可以根据找到的文档 here 设置轴的顺序。

在这种情况下,您可以通过对您的 bin 数据执行 pd.value_counts 来设置顺序,按索引对其进行排序,然后像这样抓取索引:

order_agebin = pd.value_counts(data['Age Bin']).sort_index().index

然后只需修改您的sns.boxplot() 部分如下:

sns.boxplot(x='Age Bin', y="Values", hue='Class', data=data, order = order_agebin)

【讨论】:

    猜你喜欢
    • 2020-06-24
    • 2023-04-10
    • 2021-03-16
    • 1970-01-01
    • 2019-12-07
    • 2021-03-08
    • 2019-04-29
    • 2021-06-24
    • 2021-07-23
    相关资源
    最近更新 更多