【问题标题】:Seaborn catplot sort by columnsSeaborn catplot 按列排序
【发布时间】:2023-01-17 00:57:04
【问题描述】:

我正在尝试对 seaborn catplot 中的列进行排序,但我无法执行此操作。我知道我可以使用 order= 对图表中的条形进行排序,但如何对列进行排序? 到目前为止,我已经编写了用于绘图的代码:

top_codes = df["Code"].value_counts()[:5].index.tolist()
top_stations = df["Station"].value_counts()[:5].index.tolist()
sns.catplot(x='Code',col='Station', data=df.loc[(df['Code'].isin(top_codes)) & (df['Station'].isin(top_stations))],
            kind='count', col_wrap=5)

上面的代码产生以下结果:

我希望车站名称(例如 KENNEDY BD STATION、SHEPPHARD WEST STATION、FINCH STATION)按字母顺序显示。

【问题讨论】:

  • 也许在情节代码中将df.loc[(df['Code'].isin(top_codes)) & (df['Station'].isin(top_stations))更改为df.loc[(df['Code'].isin(top_codes)) & (df['Station'].isin(top_stations)).sort_values(by="Station")
  • df.Station = pd.Categorical(df.Station, sorted(df.Station.unique()), ordered=True) code and plot

标签: pandas sorting seaborn catplot


【解决方案1】:

简单的升序排序非常简单:只需调用sorted() 函数即可。 将 code_order=sorted(top_stations) 作为参数添加到 sns.catplot,如下所示:

top_codes = df["Code"].value_counts()[:5].index.tolist()
top_stations = df["Station"].value_counts()[:5].index.tolist()
sns.catplot(x='Code',col='Station', data=df.loc[(df['Code'].isin(top_codes)) & (df['Station'].isin(top_stations))],
        kind='count', col_wrap=5, code_order=sorted(top_stations))

【讨论】:

    猜你喜欢
    • 2021-05-12
    • 1970-01-01
    • 2019-11-10
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 2019-08-30
    相关资源
    最近更新 更多