【问题标题】:How to set x axis ticklabels in a seaborn plot如何在 seaborn 图中设置 x 轴刻度标签
【发布时间】:2019-10-29 12:01:24
【问题描述】:

我无法为 seaborn lineplot 正确设置 x 轴刻度标签。

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

df = pd.DataFrame({'a':np.random.rand(8),'b':np.random.rand(8)})
sns.set(style="darkgrid")
g = sns.lineplot(data=df)
g.set_xticklabels(['2011','2012','2013','2014','2015','2016','2017','2018'])

x 轴上的年份没有正确对齐。

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    每当您手动设置 x-ticklabels 时,您应该尝试先设置相应的刻度,然后指定标签。因此,在您的情况下,您应该这样做

    g = sns.lineplot(data=df)
    g.set_xticks(range(len(df))) # <--- set the ticks first
    g.set_xticklabels(['2011','2012','2013','2014','2015','2016','2017','2018'])
    

    【讨论】:

    • 是否可以通过指定预期间隔而不是枚举所需的 x 刻度来做到这一点?
    【解决方案2】:

    从 matplotlib 3.5.0 开始

    set_xticklabels 现在不鼓励使用:

    不鼓励使用此方法,因为它依赖于刻度位置。在大多数情况下,您需要改用set_xticks(positions, labels)

    现在set_xticks 包含一个新的labels 参数以同时设置刻度和标签:

    ax = sns.lineplot(data=df)
    ax.set_xticks(range(len(df)), labels=range(2011, 2019))
    #                             ^^^^^^
    

    【讨论】:

      猜你喜欢
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 2020-10-09
      • 2021-04-08
      • 2019-06-20
      • 1970-01-01
      相关资源
      最近更新 更多