【问题标题】:How to rotate x-axis tick labels in a pandas plot如何在熊猫图中旋转 x 轴刻度标签
【发布时间】:2015-11-21 12:28:25
【问题描述】:

使用以下代码:

import matplotlib
matplotlib.style.use('ggplot')
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]})
df = df[["celltype","s1","s2"]]
df.set_index(["celltype"],inplace=True)
df.plot(kind='bar',alpha=0.75)
plt.xlabel("")

我做了这个情节:

如何将 x 轴刻度标签旋转到 0 度?

我尝试添加这个但没有用:

plt.set_xticklabels(df.index,rotation=90)

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    传递参数rot=0 来旋转xticklabels:

    import matplotlib
    matplotlib.style.use('ggplot')
    import matplotlib.pyplot as plt
    import pandas as pd
    
    df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]})
    df = df[["celltype","s1","s2"]]
    df.set_index(["celltype"],inplace=True)
    df.plot(kind='bar',alpha=0.75, rot=0)
    plt.xlabel("")
    plt.show()
    

    产量图:

    【讨论】:

      【解决方案2】:

      试试这个 -

      plt.xticks(rotation=90)
      

      【讨论】:

      • 这肯定会旋转我的标签,但是现在当我使用plt.show() 时,由于日期标签过长,标签会被切断。
      • @DNguyen :您可以通过在执行plt.tight_layout() 之前执行plt.show() 来解决此问题
      • 这应该是答案!
      【解决方案3】:

      你可以使用 set_xticklabels()

      ax.set_xticklabels(df['Names'], rotation=90, ha='right')
      

      【讨论】:

      • 这个功能在我的情况下不起作用
      【解决方案4】:

      问题很明确,但标题并不准确。我的答案是针对那些希望更改 axis 标签 的人,而不是 tick 标签,这是公认的答案. (标题现已更正)。

      for ax in plt.gcf().axes:
          plt.sca(ax)
          plt.xlabel(ax.get_xlabel(), rotation=90)
      

      【讨论】:

        【解决方案5】:

        以下内容可能会有所帮助:

        # Valid font size are xx-small, x-small, small, medium, large, x-large, xx-large, larger, smaller, None
        
        plt.xticks(
            rotation=45,
            horizontalalignment='right',
            fontweight='light',
            fontsize='medium',
        )
        

        这里是函数xticks[reference] 的例子和API

        def xticks(ticks=None, labels=None, **kwargs):
            """
            Get or set the current tick locations and labels of the x-axis.
        
            Call signatures::
        
                locs, labels = xticks()            # Get locations and labels
                xticks(ticks, [labels], **kwargs)  # Set locations and labels
        
            Parameters
            ----------
            ticks : array_like
                A list of positions at which ticks should be placed. You can pass an
                empty list to disable xticks.
        
            labels : array_like, optional
                A list of explicit labels to place at the given *locs*.
        
            **kwargs
                :class:`.Text` properties can be used to control the appearance of
                the labels.
        
            Returns
            -------
            locs
                An array of label locations.
            labels
                A list of `.Text` objects.
        
            Notes
            -----
            Calling this function with no arguments (e.g. ``xticks()``) is the pyplot
            equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on
            the current axes.
            Calling this function with arguments is the pyplot equivalent of calling
            `~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current axes.
        
            Examples
            --------
            Get the current locations and labels:
        
                >>> locs, labels = xticks()
        
            Set label locations:
        
                >>> xticks(np.arange(0, 1, step=0.2))
        
            Set text labels:
        
                >>> xticks(np.arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue'))
        
            Set text labels and properties:
        
                >>> xticks(np.arange(12), calendar.month_name[1:13], rotation=20)
        
            Disable xticks:
        
                >>> xticks([])
            """
        

        【讨论】:

          猜你喜欢
          • 2020-08-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-04
          • 1970-01-01
          • 1970-01-01
          • 2017-09-20
          • 1970-01-01
          相关资源
          最近更新 更多