2

Elaborè un gráfico de barras combinado a partir de una tabla, el cual me indica en el eje x los meses del año, pero por defecto los ordena en orden alfabético, quisiera que se ordenaran cronológicamente (ENERO, FEBRERO...etc).

Estoy intentando lo siguiente:

result = pd.DataFrame({
"AÑO": (list_año),
"MES": (list_mes),
"ACTUALIZADO": (list_actualizado),
"DESACTUALIZADO": (list_desactualizado),
"SIN IMAGEN": (list_sin_imagen)
 })

 group_sum = result.groupby(['AÑO', 'MES'])['ACTUALIZADO', 
 'DESACTUALIZADO', 'SIN IMAGEN'].sum()
  ax = group_sum.plot.bar(figsize=(15, 7), stacked=True)

  ax.set_title('titulo', fontsize=25)  # Titulo de la 
  grafica
  ax.set_ylabel('y', fontsize=20) # Titulo eje y
  ax.set_xlabel('x', fontsize=20) # Titulo eje x
  ax.legend(bbox_to_anchor=(1, 0.6), fontsize=16) #ubicación leyenda
  ax.tick_params(axis="x", rotation=0, labelsize=15)
  ax.tick_params(axis="y", labelsize=15)
  ax.grid(True)

  abs_values = group_sum.values
  rel_values = abs_values / abs_values.sum(axis=1, keepdims=True) * 
  100

  labels = zip(abs_values.T.flatten(), rel_values.T.flatten())

  for path in ax.patches:
  abs_value, rel_value = next(labels)
  label = f"{rel_value:.2f}% ({abs_value})"
  width, height = path.get_width(), path.get_height()
  x, y = path.get_xy() 
  ax.text(x=x + width / 2, 
        y=y + height / 2, 
        s=label,
        horizontalalignment='center', 
        verticalalignment='center'
        )
        plt.show()

grafico

1 respuesta 1

0

Matplotlib realmente no ordena nada, es pandas.DataFrame.groupby el que ordena los grupos por defecto y lo hace lexicográficamente como has observado.

Una posibilidad es hacer que tu columna MES sea de tipo categórico (pandas.Categorical o mediante as_type y pd.api.types.CategoricalDtype), lo cual permite a Pandas recordar el orden inicial de las categorías y ordenar en base a él.

El código sería algo así (ver advertencia debajo porque hay un bug en la versión actual de Pandas):

lista_meses = ['ENERO', 'FEBRERO', 'MARZO', 'ABRIL', 'MAYO', 'JUNIO', 'JULIO',
               'AGOSTO', 'SEPTIEMBRE', 'OCTUBRE', 'NOVIEMBRE', 'DICIEMBRE']
meses = pd.api.types.CategoricalDtype(categories=lista_meses)

result = pd.DataFrame({
"AÑO": (2018, 2019, 2019, 2018, 2019, 2019, 2018),
"MES": ("DICIEMBRE", "AGOSTO", "ENERO", "MARZO", "JUNIO", "ABRIL", "OCTUBRE"),
"ACTUALIZADO": (4, 8, 7, 12, 7, 1, 7),
"DESACTUALIZADO": (2, 4, 5, 6, 7, 3, 2),
"SIN IMAGEN": (4, 5, 2, 1, 3, 2, 5)
 })

result["MES"] = result["MES"].astype(meses)
group_sum = result.groupby(['AÑO', 'MES'], observed=True)['ACTUALIZADO', 'DESACTUALIZADO', 'SIN IMAGEN'].sum()

IMPORTANTE

groupby ante datos categóricos agrupa usando todas las categorías posibles, no solo por las que tu DataFrame presenta. Esto se evita con el argumento observer=True. Actualmente, pandas 0.24 tiene un bug por el cual groupby pierde la capacidad de ordenar correctamente cuando se usa observer=False. Este bug está corregido y será subsanado en la versión pandas 0.25. Por ahora, podemos simplemente aplicar pandas.DataFrame.sort_values previamente a agrupar y evitar que Groupby ordene el nombre de los grupos (sort=False):

import pandas as pd
import matplotlib.pyplot as plt


lista_meses = ['ENERO', 'FEBRERO', 'MARZO', 'ABRIL', 'MAYO', 'JUNIO', 'JULIO',
               'AGOSTO', 'SEPTIEMBRE', 'OCTUBRE', 'NOVIEMBRE', 'DICIEMBRE']
meses = pd.api.types.CategoricalDtype(categories=lista_meses)

result = pd.DataFrame({
"AÑO": (2018, 2019, 2019, 2018, 2019, 2019, 2018),
"MES": ("DICIEMBRE", "AGOSTO", "ENERO", "MARZO", "JUNIO", "ABRIL", "OCTUBRE"),
"ACTUALIZADO": (4, 8, 7, 12, 7, 1, 7),
"DESACTUALIZADO": (2, 4, 5, 6, 7, 3, 2),
"SIN IMAGEN": (4, 5, 2, 1, 3, 2, 5)
 })

result["MES"] = result["MES"].astype(meses)
result.sort_values(by=['AÑO', 'MES'], ascending=[True, True], inplace=True)
group_sum = result.groupby(['AÑO', 'MES'], observed=True, sort=False)['ACTUALIZADO', 'DESACTUALIZADO', 'SIN IMAGEN'].sum()

ax = group_sum.plot.bar(figsize=(15, 7), stacked=True)
ax.set_title('titulo', fontsize=25)  # Titulo de la grafica
ax.set_ylabel('y', fontsize=20) # Titulo eje y
ax.set_xlabel('x', fontsize=20) # Titulo eje x
ax.legend(bbox_to_anchor=(1, 0.6), fontsize=16) #ubicación leyenda
ax.tick_params(axis="x", rotation=0, labelsize=15)
ax.tick_params(axis="y", labelsize=15)
ax.grid(True)

abs_values = group_sum.values
rel_values = abs_values / abs_values.sum(axis=1, keepdims=True) * 100

labels = zip(abs_values.T.flatten(), rel_values.T.flatten())

for path in ax.patches:
    abs_value, rel_value = next(labels)
    label = f"{rel_value:.2f}% ({abs_value})"
    width, height = path.get_width(), path.get_height()
    x, y = path.get_xy() 
    ax.text(x=x + width / 2, 
            y=y + height / 2, 
            s=label,
            horizontalalignment='center', 
            verticalalignment='center'
            )
    plt.show()

introducir la descripción de la imagen aquí

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.