es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Cómo agregar dos niveles de etiquetas para un gráfico de barras agrupadas y apiladas en matplotlib.

Estoy tratando de agregar dos niveles de etiquetas a este gráfico de barras apiladas agrupadas usando matplotlib. Cada barra en cada posición respectiva de cada grupo debería tener la misma etiqueta (es decir, la primera barra de cada grupo debería etiquetarse como “1”, la segunda barra como “2”, etc.). Luego, me gustaría tener un segundo nivel de etiquetas para cada grupo. Hasta ahora, esto es lo que tengo:

width = 0.25
x = np.arange(1, 7)

fig = plt.figure(figsize=(10,6))
ax = plt.axes()

ax.bar(x-0.4, shift1_rbc, width, color='red', tick_label='1')
ax.bar(x-0.1, shift2_rbc, width, color='red')
ax.bar(x+0.2, shift3_rbc, width, color='red')
ax.bar(x-0.4, shift1_plt, width*.7, color='blue')
ax.bar(x-0.1, shift2_plt, width*.7, color='blue')
ax.bar(x+0.2, shift3_plt, width*.7, color='blue')
ax.bar(x-0.4, shift1_ffp, width*.5, color='green')
ax.bar(x-0.1, shift2_ffp, width*.5, color='green')
ax.bar(x+0.2, shift3_ffp, width*.5, color='green')

Cuando intento agregar el parámetro “tick_label” a otro conjunto de barras, reemplaza la etiqueta anterior, como se muestra a continuación:

width = 0.25
x = np.arange(1, 7)

fig = plt.figure(figsize=(10,6))
ax = plt.axes()

ax.bar(x-0.4, shift1_rbc, width, color='red', tick_label='1')
ax.bar(x-0.1, shift2_rbc, width, color='red', tick_label='1')
ax.bar(x+0.2, shift3_rbc, width, color='red')
ax.bar(x-0.4, shift1_plt, width*.7, color='blue')
ax.bar(x-0.1, shift2_plt, width*.7, color='blue')
ax.bar(x+0.2, shift3_plt, width*.7, color='blue')
ax.bar(x-0.4, shift1_ffp, width*.5, color='green')
ax.bar(x-0.1, shift2_ffp, width*.5, color='green')
ax.bar(x+0.2, shift3_ffp, width*.5, color='green')

Agradezco cualquier ayuda que puedan brindar.

Tags:  , ,

Answer

  1. Avatar for davy.ai

    Un enfoque para agregar dos niveles de etiquetas al gráfico de barras agrupadas apiladas es utilizar la función xticks para establecer las ubicaciones y texto de las etiquetas del eje x. Aquí tienes un ejemplo de código:

    import numpy as np
    import matplotlib.pyplot as plt
    
    # datos de ejemplo
    shift1_rbc = [10, 20, 30, 40, 50, 60]
    shift2_rbc = [5, 15, 25, 35, 45, 55]
    shift3_rbc = [8, 18, 28, 38, 48, 58]
    shift1_plt = [15, 25, 35, 45, 55, 65]
    shift2_plt = [7, 17, 27, 37, 47, 57]
    shift3_plt = [12, 22, 32, 42, 52, 62]
    shift1_ffp = [20, 30, 40, 50, 60, 70]
    shift2_ffp = [8, 18, 28, 38, 48, 58]
    shift3_ffp = [18, 28, 38, 48, 58, 68]
    
    # crear la figura y los ejes
    fig, ax = plt.subplots(figsize=(10, 6))
    
    # establecer las ubicaciones y el ancho de las barras
    x = np.arange(1, 7)
    width = 0.25
    
    # graficar las barras agrupadas apiladas
    ax.bar(x-0.4, shift1_rbc, width, color='red')
    ax.bar(x-0.4, shift1_plt, width*0.7, color='blue')
    ax.bar(x-0.4, shift1_ffp, width*0.5, color='green')
    
    ax.bar(x-0.1, shift2_rbc, width, color='red')
    ax.bar(x-0.1, shift2_plt, width*0.7, color='blue')
    ax.bar(x-0.1, shift2_ffp, width*0.5, color='green')
    
    ax.bar(x+0.2, shift3_rbc, width, color='red')
    ax.bar(x+0.2, shift3_plt, width*0.7, color='blue')
    ax.bar(x+0.2, shift3_ffp, width*0.5, color='green')
    
    # establecer las ubicaciones y etiquetas de las marcas de los ejes x
    ax.set_xticks(x)
    ax.set_xticklabels(['Grupo 1', 'Grupo 2', 'Grupo 3', 'Grupo 4', 'Grupo 5', 'Grupo 6'])
    
    # agregar el primer nivel de etiquetas
    for i, j, k in zip(x, shift1_rbc, shift1_plt):
        ax.text(i-0.4, j/2, '1', ha='center', va='center', fontsize=14, color='white')
        ax.text(i-0.4, j+k/2, '2', ha='center', va='center', fontsize=14, color='white')
    for i, j, k in zip(x, shift2_rbc, shift2_plt):
        ax.text(i-0.1, j/2, '1', ha='center', va='center', fontsize=14, color='white')
        ax.text(i-0.1, j+k/2, '2', ha='center', va='center', fontsize=14, color='white')
    for i, j, k in zip(x, shift3_rbc, shift3_plt):
        ax.text(i+0.2, j/2, '1', ha='center', va='center', fontsize=14, color='white')
        ax.text(i+0.2, j+k/2, '2', ha='center', va='center', fontsize=14, color='white')
    
    # agregar el segundo nivel de etiquetas
    ax.text(0.075, 0.5, 'Turno 1', ha='center', va='center', fontsize=16, transform=ax.transAxes, rotation=90)
    ax.text(0.325, 0.5, 'Turno 2', ha='center', va='center', fontsize=16, transform=ax.transAxes, rotation=90)
    ax.text(0.575, 0.5, 'Turno 3', ha='center', va='center', fontsize=16, transform=ax.transAxes, rotation=90)
    
    # establecer la etiqueta y límites del eje y
    ax.set_ylabel('Valor')
    ax.set_ylim(0, 100)
    
    # establecer el título del gráfico
    plt.title('Gráfico de Barras Agrupadas Apiladas con Dos Niveles de Etiquetas')
    
    # mostrar el gráfico
    plt.show()
    

    Este código produce un gráfico de barras agrupadas apiladas con dos niveles de etiquetas, donde cada grupo de barras tiene una etiqueta para cada posición de la barra, y también una etiqueta para cada turno. La salida del gráfico debería lucir así:

    stacked_grouped_barplot_labels.png

    ¡Espero que esta solución sea de ayuda! Hazme saber si tienes alguna pregunta.

Comments are closed.