如何设置x轴刻度线宽度和标签

时间:2020-08-25 06:07:44

标签: python seaborn

x轴是两年日期的年月。因此有24个值。因为relplot函数仅允许x和y轴使用数字类型。因此,由于201801至201912的间距不相等,因此x轴全部聚类为两端。我如何用正确的标签将其等距排列:201801,201802 .... 201912。 (24个日期值)

import seaborn as sns
sns.set(style="ticks")
palette = dict(zip(rel['Sub-Category'].unique(),
                   sns.color_palette("rocket_r", 17)))
r=sns.relplot(x='YearMonth', y="Profit",
            hue="Sub-Category", col="Category",
            #size="Year", size_order=["2019", "2018"], 
            palette=palette,
            height=5, aspect=.7, facet_kws=dict(sharex=True),
            kind="line", legend="full", data=rel)
r.set(yticks=[i for i in range(int(min(rel['Profit'])), int(max(rel['Profit'])) + 50, 500)],
     xticks=[i for i in rel.YearMonth.unique()])

sample output

1 个答案:

答案 0 :(得分:2)

如评论中所述,您只需要将YearMonth列转换为日期时间:

# Input data
df = pd.DataFrame({'YearMonth': ['2018-01','2018-01','2018-02','2018-04','2018-03','2018-05'],
                   'Category':['Clothing','Furniture','Clothing','Clothing','Furniture','Clothing'], 
                   'Sub-Category':['Henkerchief','Table','Skirt','Henkerchief','Table','Skirt'],
                   'Profit':[16,40,110,33,44,55]})

# Create datetime column
df['date'] = pd.to_datetime(df['YearMonth'], format = '%Y-%m')

# Plot
sns.set(style="ticks")
palette = dict(zip(df['Sub-Category'].unique(),
                   sns.color_palette("rocket_r", 17)))
r=sns.relplot(x='date', y="Profit",
            hue="Sub-Category", col="Category",
            palette=palette,
            height=5, aspect=.7, facet_kws=dict(sharex=True),
            kind="line", legend="full", data=df)

# Adjust xticks
xticks = pd.date_range(start='2017-12',end='2018-05',
                       freq='MS',closed='right')
r.set(xticks=xticks)

这是输出图: enter image description here

更新: 如果要旋转xtick标签,可以使用:

for ax in r.axes.ravel():
    ax.set_xticklabels(ax.get_xticklabels(), rotation=45)