- Use pandas.Categorical https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Categorical.html设置分类顺序
'Time of Day'
in the df
.
- 测试于
python 3.11
, pandas 1.5.3
, matplotlib 3.7.1
, seaborn 0.12.2
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
data = {'Time of Day': ['Day', 'Day', 'Day', 'Evening', 'Evening', 'Evening', 'Morning', 'Morning', 'Morning', 'Night', 'Night', 'Night'],
'Season': ['Shoulder', 'Summer', 'Winter', 'Shoulder', 'Summer', 'Winter', 'Shoulder', 'Summer', 'Winter', 'Shoulder', 'Summer', 'Winter'],
'value': [30.581606, 25.865560000000002, 42.644529999999996, 39.954759, 32.053458, 53.678297, 32.171245, 25.070815, 42.876667, 22.082042, 17.510289999999998, 33.262356]}
# create dataframe
df = pd.DataFrame(data)
# set categorical order
df['Time of Day'] = pd.Categorical(df['Time of Day'],
categories=['Morning', 'Day', 'Evening', 'Night'],
ordered=True)
# plot
ax = sns.lineplot(x='Time of Day', y='value', data=df, hue='Season')
sns.move_legend(ax, bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)
- If you are plotting data against a categorical x-axis, then consider using a categorical plot https://seaborn.pydata.org/tutorial/categorical.html like sns.pointplot https://seaborn.pydata.org/generated/seaborn.pointplot.html, where the x-axis can be ordered with the
order
parameter.
- The 图形级 https://seaborn.pydata.org/tutorial/function_overview.html#figure-level-vs-axes-level-functions plot, sns.catplot https://seaborn.pydata.org/generated/seaborn.catplot.html with
kind='point'
也有效。
order=['Morning', 'Day', 'Evening', 'Night']
ax = sns.pointplot(x='Time of Day', y='value', data=df, hue='Season', order=order, marker='')
sns.move_legend(ax, bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)