【问题标题】:How to rotate xticklabels in a seaborn catplot如何在 seaborn catplot 中旋转 xticklabels
【发布时间】:2020-09-15 20:24:19
【问题描述】:

我无法在 Seaborn/Matplotlib 中旋转我的 xlabel。我尝试了许多不同的解决方案,但无法修复它。我在 stackoverflow 上看到了很多相关的问题,但它们对我没有用。

我当前的情节看起来像这样,但我希望 xlabels 旋转 90。

    @staticmethod
    def plotPrestasjon(plot):
    sns.set(style="darkgrid")
    ax = sns.catplot(x="COURSE", y="FINISH", hue="COURSE",
                     col="BIB#", data=plot, s=9, palette="Set2")
    ax.set(xlabel='COURSES', ylabel='FINISH (sec)')
    plt.show()

我试过了:

ax.set_xticklabels(ax.get_xticklabels(), rotation=90)

但这无法生成情节。有什么想法可以解决吗?

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:
    • 根据文档,为sns.catplot 设置 xticklabels 的正确方法是使用.set_xticklabels 方法(例如g.set_xticklabels(rotation=30))。
    • 如果需要在 FacetGrid 内逐个地进行更改,则应使用循环遍历 Axes
    • Building structured multi-plot grids
    • seaborn.FacetGrid
    • g 或在 OP 的情况下,axseaborn.axisgrid.FacetGrid
      • 在遍历ax.axes.flat 时,axes 是一个<class 'matplotlib.axes._subplots.AxesSubplot'>,它有很多类方法,包括.get_xticklabels()
    import seaborn as sns
    
    # load data
    exercise = sns.load_dataset("exercise")
    
    # plot catplot
    g = sns.catplot(x="time", y="pulse", hue="kind", col="diet", data=exercise)
    
    # set rotation
    g.set_xticklabels(rotation=30)
    

    • 使用g.set_xticklabels(g.get_xticklabels(), rotation=30) 会产生AttributeError
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-442-d1d39d8cc4f0> in <module>
          1 g = sns.catplot(x="time", y="pulse", hue="kind", col="diet", data=exercise)
    ----> 2 g.set_xticklabels(g.get_xticklabels(), rotation=30)
    
    AttributeError: 'FacetGrid' object has no attribute 'get_xticklabels'
    

    【讨论】:

    • 是的,这确实是更合适的解决方案。谢谢指正!
    【解决方案2】:

    尝试遍历属于 FacetGrid 的轴:

    for axes in ax.axes.flat:
        axes.set_xticklabels(axes.get_xticklabels(), 
                             rotation=90, 
                             horizontalalignment='right')
    
    • FacetGridAxes 的集合组成,一些看起来对整个“情节”如此直观的方法实际上是用于每个个体Axes。在documentation 中搜索Axes。您会看到,当他们需要更改与每个单独的子图相关的功能时(例如,与整个图的图例相反),他们经常会遍历它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-07
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 2021-09-29
      • 2023-01-17
      相关资源
      最近更新 更多