如何更改分类 x 轴的绘图顺序 [英] How to change the plot order of the categorical x-axis

查看:51
本文介绍了如何更改分类 x 轴的绘图顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了一个如下所示的数据框:

df:

时间季节值天肩30.581606天夏 25.865560白天 冬天 42.644530晚间肩部 39.954759夏夜 32.053458晚上冬天 53.678297晨肩 32.171245早晨夏天 25.070815早上冬天 42.876667夜肩 22.082042夜夏 17.510290夜冬 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轴的标签,而不是数据点的顺序.有人能帮我解决这个问题吗?

解决方案

设置

I got a dataframe which looks like below:

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

I am plotting the values in line plot using seaborn using following code:

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

it generates the following graph:

The problem with the graph is that order of the x-axis is not in the desired order. I want to change the order of a-axis value to ['Morning', 'Day','Evening','Night']. I tried to change it with the following command:

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

But this command only changes the label of the x-axis, not the order of data points. Could anyone help me in fixing the issue?

解决方案

Set the categorical order of Time of Day in the dataframe

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
g = sns.lineplot(x='Time of Day', y='value', data=df, hue='Season')
plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)

这篇关于如何更改分类 x 轴的绘图顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆