我有以下代码,用于执行堆积的条形图,然后将条形图上的百分比标签绘制为文本:
221218
但是,条形图上的标签为“黑色”字体,很难看到。如何将其更改为“白色”?
我尝试了以下方法,但是它不起作用:
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')
有什么建议吗?
答案 0 :(得分:1)
我找到了。这是一个简单的解决方法:
我将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')