[Python] create bar charts with x axis and custom labels using groupby in jupyter notebooks

Discussão em 'Python' iniciado por Stack, Agosto 11, 2025.

  1. Stack

    Stack Membro Participativo

    Good day all, thanks to the help here i've been able to build a bar chart with value based x axis from this data which is stored in a pandas dataframe, where each bar represents a "Label" and is colored by "PVR Group":

    Capex NPV Label DA PVR Group min_x max_x min_y max_y
    2 25 54 Well8 Russ1 1_Low 86 111 0 54
    6 27 30 Well9 Russ2 1_Low 127 154 0 30
    3 12 10 Well4 Russ3 1_Low 181 193 0 10
    5 13 60 Well2 Russ2 2_Med 56 69 0 60
    8 17 59 Well6 Russ3 2_Med 69 86 0 59
    1 27 30 Well7 Russ1 2_Med 154 181 0 30
    7 26 81 Well3 Russ3 3_High 0 26 0 81
    4 30 80 Well5 Russ2 3_High 26 56 0 80
    0 16 50 Well1 Russ1 3_High 111 127 0 50


    Using this code:

    res = df.sort_values(by=['PVR Group','max_y'],ascending=[True,False])
    fig, ax = plt.subplots(figsize=(15,3))
    colors = {}
    for name, group in res.groupby('PVR Group'):
    ax.bar((group['min_x']+(group['max_x']-group['min_x'])/2),
    group['max_y']-group['min_y'],
    width=(group['max_x']-group['min_x']),
    bottom=group['min_y'],
    label='PVR Group'+' - '+name,
    alpha=.8,
    edgecolor = (0,0,0,0.8),
    )
    ax.legend()
    ax.set_facecolor('#EBEBEB')
    #ax.grid(color='white', linewidth=.5, alpha=.5)
    for spine in list(ax.spines):
    ax.spines[spine].set_visible(True)
    ax.margins(0.05)
    plt.xlabel("X axis")
    plt.ylabel("Y axis")
    plt.title("Bookshelf Chart")
    plt.show()


    Which creates a plot that looks like this where each bar is shown and colored by "PVR Group" which is exactly what I'm looking for:

    [​IMG]

    Each of the bars represents a "Label" (there is code before this that calculates the x and y values based on grouping by Label).

    What I'd like to do is to add the "Label" text to each bar.

    I've tried this code, but it doesn't label the bars appropriately:

    res = df.sort_values(by=['PVR Group','max_y'],ascending=[True,False])
    fig, ax = plt.subplots(figsize=(15,3))
    colors = {}
    for name, group in res.groupby('PVR Group'):
    bars = ax.bar((group['min_x']+(group['max_x']-group['min_x'])/2),
    group['max_y']-group['min_y'],
    width=(group['max_x']-group['min_x']),
    bottom=group['min_y'],
    label='PVR Group'+' - '+name,
    alpha=.8,
    edgecolor = (0,0,0,0.8),
    )
    for i, bar in enumerate(bars):
    ax.text(bar.get_x() + bar.get_width() / 2, # X-coordinate for the label (center of the bar)
    bar.get_height()/2, # Y-coordinate for the label (top of the bar)
    res['Label'].iloc, # The label text from 'Label_Category'
    ha='center', # Horizontal alignment
    va='center', # Vertical alignment
    rotation=90
    )
    ax.legend()
    ax.set_facecolor('#EBEBEB')
    #ax.grid(color='white', linewidth=.5, alpha=.5)
    for spine in list(ax.spines):
    ax.spines[spine].set_visible(True)
    ax.margins(0.05)
    plt.xlabel("X axis")
    plt.ylabel("Y axis")
    plt.title("Bookshelf Chart")
    plt.show()


    As you can see, it seems to repeat each "Label" text for each "PVR Group". I'm sure I'm somehow not formatting things correctly but I can't seem to sort it out. [​IMG]

    Continue reading...

Compartilhe esta Página