Search code examples
pythonjupyter-notebookseaborn

Rotate label xin seaborn (Small multiple time series)


In the past, I created a graph where all the labels on the x-axis appeared in vertical format.

https://i.sstatic.net/5RSci.jpg

After a few days, the same code no longer displayed the labels; it left them blank. I made some corrections and managed to rotate only the labels on the last image.

https://i.sstatic.net/kMJWY.jpg

data

this is the code

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

# Leer el archivo Excel
df = pd.read_excel('demanda2.xlsx')

# Seleccionar las columnas relevantes (Año y meses)
columnas_meses = ['Año', 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre']
df_meses = df[columnas_meses]

# Reorganizar el DataFrame para ser compatible con Seaborn
df_meses_melted = pd.melt(df_meses, id_vars='Año', var_name='Mes', value_name='KWh')

# Configurar tema y estilo de Seaborn
sns.set_theme(style="dark")

# Plot cada serie temporal de años en su propia faceta
g = sns.relplot(
    data=df_meses_melted,
    x="Mes", y="KWh", col="Año", hue="Año",
    kind="line", palette="crest", linewidth=4, zorder=5,
    col_wrap=3, height=3, aspect=2, legend=False,  # Ajustar height y aspect
)

# Iterar sobre cada subplot para personalizar aún más
for año, ax in g.axes_dict.items():
    # Añadir el título como una anotación dentro del gráfico
    ax.text(.8, .85, año, transform=ax.transAxes, fontweight="bold")

    # Plot de todas las series temporales de años en el fondo
    sns.lineplot(
        data=df_meses_melted, x="Mes", y="KWh", units="Año",
        estimator=None, color=".7", linewidth=1, ax=ax,
    )

    # Reducir la frecuencia de las marcas en el eje x
ax.set_xticks(ax.get_xticks()[::1])

    # Hacer que las etiquetas del eje x se vean en formato vertical
ax.set_xticklabels(ax.get_xticklabels(), rotation=90, ha='center')

# Ajustar los aspectos de soporte del gráfico
g.set_titles("")
g.set_axis_labels("", "MW")
g.tight_layout()

To be able to see the labels as in the first image, I'm not sure if my Jupyter Notebook got misconfigured after reinstalling everything.

The same issue occurs with the example from the Seaborn gallery. https://seaborn.pydata.org/examples/timeseries_facets.html

Image Example


Solution

  • You rotate the labels of ax outside of the for-loop. This is then only the last Axes object of the loop and thus the last plot. Also it is better to use ax.tick_params():

    Use

    ax.tick_params(axis='x', rotation=90)
    

    inside the for-loop:

    for año, ax in g.axes_dict.items():
        # Añadir el título como una anotación dentro del gráfico
        ax.text(.8, .85, año, transform=ax.transAxes, fontweight="bold")
    
        # Plot de todas las series temporales de años en el fondo
        sns.lineplot(
            data=df_meses_melted, x="Mes", y="KWh", units="Año",
            estimator=None, color=".7", linewidth=1, ax=ax,
        )
    
        ax.tick_params(axis='x', rotation=90)
    
    # Reducir la frecuencia de las marcas en el eje x
    ax.set_xticks(ax.get_xticks()[::1])
    
    
    # Ajustar los aspectos de soporte del gráfico
    g.set_titles("")
    g.set_axis_labels("", "MW")
    g.tight_layout()
    

    See also: Rotate label text in seaborn