【问题标题】:How to change bar label color based on background如何根据背景更改条形标签颜色
【发布时间】: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


    【解决方案1】:

    您可以创建所需标签颜色的列表,枚举 ax.containers,并在循环内为 label_colors 编制索引,如下所示。在这种情况下,我选择了白色的标签颜色显示在黑色和深灰色的背景上,而黑色的标签颜色显示在深灰色和银色的背景上,但您可以选择任何您想要的颜色。

    plt.style.use('ggplot')
    ax = df_new2.plot(kind='barh', stacked=True, figsize=(12, 10), color=['black', 'dimgray', 'darkgray', 'silver'])
    
    label_colors = ['white', 'white', 'black', 'black']
    
    for i, c in enumerate(ax.containers):
        labels = [f'{w:.0f}%' if (w := v.get_width()) > 0.49 else '' for v in c]
        ax.bar_label(c, labels=labels, label_type='center', color= label_colors[i], padding=3, fontsize=8)
    
    ax.legend(bbox_to_anchor=(1.025, 1), loc='upper left', borderaxespad=0.)
    ax.set_xlim(right=103)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      相关资源
      最近更新 更多