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

标签 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

最佳答案

如评论中所述,您只需将 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)

关于python - 如何设置x轴刻度宽度和标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63572933/

相关文章:

python - 在 Seaborn FacetGrid 图上绘制不同 'hue' 数据的平均线

Python Seaborn 箱线图 : Overlay 95 percentile values on whisker

python - 在 redis 作业上存储 "meta"数据不起作用?

python - 如何从递归函数返回单个 bool 值?

python - SQLAlchemy session 错误 : InvalidRequestError

python - 如何降低 seaborn 中 x-ticks 的密度

python - 如何更改seaborn jointplot中注释的字体大小?

pandas - 使用 seaborn 绘图时如何为色调参数指定多个变量?

python - Django:使用表单的一个模板中的多个模型

python - 检查一个单词是否是具有相同字母数量的另一个单词的子集