根据ax.text上的值更改文本颜色

时间:2019-02-14 14:13:04

标签: python colors bar-chart seaborn

我正在绘制带有百分比的水平条形图,但希望> 0的值为绿色,而负数为红色。

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', 

请参见下图。值21.5%,10.0%等必须为绿色。

当我尝试行colors = ['r' if (y < 0) else 'g' for y in diff['% Change from last month'].values]并将color='red'更改为color='colors'

我得到了错误: ValueError: Invalid RGBA argument: ('g', 'r', 'g', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r') all red

1 个答案:

答案 0 :(得分:-1)

在该行中

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', fontsize=14)

您可以尝试类似if-else的语句

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

    else:
        ax.text(1.06*max(data['BASE VOLUME']), i + len(data2)/50, str("{0:.1f}%".format(v)), color='r', fontweight='bold',