python 如何更改分类x轴的绘制顺序

2exbekwf  于 2023-03-16  发布在  Python
关注(0)|答案(2)|浏览(229)

我得到了一个 Dataframe ,如下所示:
DF:

Time of Day Season  value
Day        Shoulder 30.581606
Day        Summer   25.865560
Day        Winter   42.644530
Evening    Shoulder 39.954759
Evening    Summer   32.053458
Evening    Winter   53.678297
Morning    Shoulder 32.171245
Morning    Summer   25.070815
Morning    Winter   42.876667
Night      Shoulder 22.082042
Night      Summer   17.510290
Night      Winter   33.262356

我正在使用seaborn绘制线图中的值,使用以下代码:

g = sns.lineplot(x='Time of Day',y='value',data=df,hue='Season')

它会生成以下图形:

图表的问题是x轴的顺序不是所需的顺序。我想将a轴值的顺序更改为['Morning','Day','Evening',' Night ']。我尝试使用以下命令进行更改:

g.set_xticklabels(['Morning','Day','Evening','Night'])

但是这个命令只改变了x轴的标签,而不是数据点的顺序。有人能帮我解决这个问题吗?

bxgwgixi

bxgwgixi1#

  • 使用pandas.Categorical设置'Time of Day'df中的分类顺序。
    *python 3.11pandas 1.5.3matplotlib 3.7.1seaborn 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.04,0.5), loc="center left", borderaxespad=0)

neekobn8

neekobn82#

如果您不想将其更改为分类列并进行有序绘图?!

# here dictionary value in map() will decide which value should be first and next
df_sort = df.sort_values('Time of Day'
                         , key=lambda col: col.map(
                                 { 'Morning':10
                                  ,'Evening':3
                                  ,'Day':2
                                  ,'Night':4}))
sns.lineplot(x='Time of Day', y='value', data=df_sort, hue='Season');

相关问题