matplotlib更改条形图标签上的文本颜色

2024-10-06 07:09:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码,用于绘制堆积条形图,然后将条形图上的百分比标签绘制为文本:

dfLev = pd.DataFrame({"year":['2017/16','2015/16','2014/15','2013/14','2012/13', '2011/12', '2010/11'],
                    "a":[1158,1091,1029,1062,929,922,725], 
                    "b":[3713,3319,3395,3773,3684,4215,4177]})


df_total = [4871,4410,4424,4835,4613,5137,4902]

dfLevFinal = dfLev.iloc[:, 0:3]


plotBar = dfLevFinal.plot(x = 'year', kind='barh',stacked = True, color = ['#8C4799','#008275'], title = '', mark_right = True)

df_rel = dfLevFinal[dfLevFinal.columns[1:3]].div(df_total, 0)*100

#plot the labels on the bars
for n in df_rel:
    for i, (cs, ab, pc) in enumerate(zip(dfLevFinal.iloc[:, 1:].cumsum(1)[n], dfLevFinal[n], df_rel[n])):
        plt.text(cs - ab/2, i, str(int(np.round(pc))) + '%', va='center', ha='center')

但是,标签上的标签是“黑色”字体,很难看到。我怎么把它改成白色?在

我试过以下方法,但没用:

^{pr2}$

有什么建议吗?在


Tags: theintruedfforplot绘制标签
1条回答
网友
1楼 · 发布于 2024-10-06 07:09:14

我找到了。这是一个简单的解决办法:

我把color = 'white'添加到了底线:

#plot the labels on the bars
for n in df_rel:
    for i, (cs, ab, pc) in enumerate(zip(dfLevFinal.iloc[:, 1:].cumsum(1)[n], dfLevFinal[n], df_rel[n])):
        plt.text(cs - ab/2, i, str(int(np.round(pc))) + '%', va='center', ha='center', color = 'white')

相关问题 更多 >