使用 sns.relplot 时 X 轴顺序不正确

X-axis not in order when using sns.relplot

我使用 sns relplot 制作了一个折线图,但它没有以正确的顺序显示 x 轴。下图:

#plot line graph
g=sns.relplot( 
           data=df_fig1,
           kind="line")
g.fig.suptitle("Exams", y=1.05)
g.set(xlabel="Months",
     ylabel="Exams (%)")
g.fig.set_size_inches(8,6)
for ax in g.axes.flat:
    ax.yaxis.set_major_locator(MultipleLocator(5))
plt.show()
plt.show()

x 轴顺序应为一月、二月、...十月、十一月。如何确定顺序?我已经在数据框中修复了索引顺序,但它仍然没有在图中正确显示。

这是我的数据框的样子:

Disclaimer: this is inaccurate

sns.relplot 始终对它的 x 轴进行排序。
如果您想将 x 轴视为类别,则 relplot 不是正确的工具。
sns.catplot 有一个订单参数应该符合您的需要,但由于它是为分类数据制作的,所以它没有折线图的选项。
您必须在折线图和正确排序的数据之间做出选择。

以下代码已使用seaborn 0.11.2 进行测试。 "wide form" 中的数据帧已给出,但未分配 x=y=。因此,索引用于 x 轴,然后分别绘制每一列。

如果需要,您可以通过 df.reindex(...) 以所需顺序对列表重新排序。

您还可以设置明确的顺序,通过 pandas:

将字符串列转换为 'categorical'
df["month"] = pd.Categorical(df["month"], months_ordered)`

这里有一些示例代码来展示它是如何工作的。请注意,在 figure-level 图中,figsize 是通过各个子图的 height=aspect= 设置的。

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

df = pd.DataFrame({'month': ['Apr', 'Aug', 'Dec', 'Feb', 'Jan', 'Jul', 'Jun', 'Mar', 'May', 'Nov', 'Oct', 'Sep'],
                   'exams_increased': np.random.randint(16, 40, 12),
                   'capture_increased': np.random.randint(16, 40, 12)})
df = df.set_index('month')

# reorder the index with the order given in list 'months_ordered'
months_ordered = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
df = df.reindex(months_ordered)
# relplot when given a dataframe in wide form, uses the index to define the order
g = sns.relplot(data=df,
                kind="line", height=8, aspect=6 / 8)
plt.show()