【发布时间】:2021-05-26 17:06:09
【问题描述】:
我是使用 python 处理数据的新手,但是通过将在 here 和其他网站上找到的答案放在一起,我设法将我的数据集绘制成带有条形标签的堆叠条形图。
但是,我希望条形标签根据条形颜色具有不同的文本颜色,以帮助提高可见性(我仅限于条形的灰度颜色)我找到了一些管理此问题的示例,但它们会干扰与我的代码的其他部分,我不知道如何协调这一点。有人可以帮忙吗?
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
ax = df_new2.plot(kind='barh', stacked=True, figsize=(12, 10), color = ['black','dimgray','darkgray','silver'])
for c in ax.containers:
# customize the label to account for cases when there might not be a bar section
labels = [f'{w:.0f}%' if (w := v.get_width()) > 0.49 else '' for v in c ]
# set the bar label
ax.bar_label(c, labels=labels, label_type='center',color='snow',padding=3,fontsize=8)
ax.legend(bbox_to_anchor=(1.025, 1), loc='upper left', borderaxespad=0.)
ax.set_xlim(right=103)
更新:这个仍然不走运。请让我知道是否有人可以提供帮助。
【问题讨论】:
标签: python pandas matplotlib bar-chart