[Python] Changing the text colour depending on the value on ax.text

Discussão em 'Python' iniciado por Stack, Junho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I am plotting a horizontal bar chart with percentages on, but would like the values > 0 to be colored in green, with the negatives in red.

    plt.figure(figsize=(10,6))

    clrs = ['b' if (x > 10) else 'gray' for x in data2['BASE VOLUME %']]
    ax = sns.barplot(x,y, data=data2, palette=clrs)
    ax.set_xlabel('Base Volume',fontsize=15)
    ax.set_ylabel('Color Group',fontsize=15)
    plt.xticks(fontsize=15)
    plt.yticks(fontsize=15)

    for i, v in enumerate(data2['BASE VOLUME %']):
    ax.text(0 + 0.01*max(data['BASE VOLUME']), i + len(data2)/50, str("{0:.1f}%".format(v)), color='black', fontweight='bold', fontsize=14)

    for i, v in enumerate(diff['% Change from last month']):
    ax.text(1.06*max(data['BASE VOLUME']), i + len(data2)/50, str("{0:.1f}%".format(v)), color='red', fontweight='bold',


    See graph below. The values 21.5%, 10.0% etc need to be in green.

    When I try the line colors = ['r' if (y < 0) else 'g' for y in diff['% Change from last month'].values], and change color='red' to color='colors'

    I get the error: ValueError: Invalid RGBA argument: ('g', 'r', 'g', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r') [​IMG]

    Continue reading...

Compartilhe esta Página