Cómo rotar las etiquetas de marca del eje x en el diagrama de barras de Pandas


95

Con el siguiente código:

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

Hice esta trama:

ingrese la descripción de la imagen aquí

¿Cómo puedo rotar las etiquetas de marca del eje x a 0 grados?

Intenté agregar esto pero no funcionó:

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

Respuestas:


183

Pase rot=0el parámetro para rotar los 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()

produce parcela:

ingrese la descripción de la imagen aquí



9

La pregunta es clara pero el título no es tan preciso como podría ser. Mi respuesta es para aquellos que vinieron buscando cambiar la etiqueta del eje , a diferencia de las etiquetas de tick, que es de lo que se trata la respuesta aceptada. (El título ahora se ha corregido).

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

7

Puede utilizar set_xticklabels ()

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

3

Lo siguiente puede resultar útil:

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

Aquí está la función xticks[referencia] con ejemplo y 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([])
    """

2

Para los gráficos de barras, puede incluir el ángulo que finalmente desea que tengan las marcas.

Aquí estoy usando rot=0para hacerlos paralelos al eje x.

series.plot.bar(rot=0)
plt.show()
plt.close()

Y para los histogramas, es muy similar. Reemplazar rotcon xrotoyrot
Tom
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.