Python 如何在 Pandas 条形图中旋转 x 轴刻度标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32244019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:17:13  来源:igfitidea点击:

How to rotate x-axis tick labels in Pandas barplot

pythonpandasmatplotlib

提问by neversaint

With the following code:

使用以下代码:

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("")

I made this plot:

我做了这个情节:

enter image description here

在此处输入图片说明

How can I rotate the x-axis tick labels to 0 degrees?

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

I tried adding this but did not work:

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

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

采纳答案by EdChum

Pass param rot=0to rotate the xticks:

传递参数rot=0以旋转 xticks:

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()

yields plot:

产量图:

enter image description here

在此处输入图片说明

回答by CPBL

The question is clear but the title is not as precise as it could be. My answer is for those who came looking to change the axislabel, as opposed to the tick labels,which is what the accepted answer is about. (The title has now been corrected).

问题很清楚,但标题并不像它可能的那样精确。我的答案是针对那些想要更改标签而不是刻度标签的人,这是公认的答案。(标题现已更正)。

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

回答by Skromak

You can use set_xticklabels()

您可以使用 set_xticklabels()

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

回答by caot

The follows might be helpful:

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

# 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',
)

Here is the function xticks[reference]with example and API

这是带有示例和API的函数xticks[参考]

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([])
    """

回答by Ankit Kumar Rajpoot

Try this -

尝试这个 -

plt.xticks(rotation=90)

enter image description here

在此处输入图片说明