[Python] How to add % to annotations using the fmt option of bar_label

Discussão em 'Python' iniciado por Stack, Janeiro 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to use the new bar_label option in Matplotlib but am unable to find a way to append text e.g. '%' after the label values. Previously, using ax.text I could use f-strings, but I can't find a way to use f-strings with the bar-label approach.

    fig, ax = plt.subplots(1, 1, figsize=(12,8))
    hbars = ax.barh(wash_needs.index, wash_needs.values, color='#2a87c8')
    ax.tick_params(axis='x', rotation=0)

    # previously I used this approach to add labels
    #for i, v in enumerate(wash_needs):
    # ax.text(v +3, i, str(f"{v/temp:.0%}"), color='black', ha='right', va='center')

    ax.bar_label(hbars, fmt='%.2f', padding=3) # this adds a label but I can't find a way to append a '%' after the number

    plt.show()

    Continue reading...

Compartilhe esta Página