简体   繁体   English

如何根据背景更改条形图 label 颜色

[英]How to change bar label color based on background

I'm new to using python for data, but by putting together answers found here and on other sites, I've managed to plot my dataset into a stacked bar chart with bar labels.我是使用 python 获取数据的新手,但是通过将在此处和其他站点上找到的答案汇总在一起,我设法将我的数据集 plot 转换为带有条形标签的堆叠条形图。

However, I would like the bar labels to have different text colors based on the bar color, to aid in visibility (I'm restricted to grayscale colors for the bars) I've found some examples that manage this but they interfere with other parts of my code and I'm not sure how to reconcile this.但是,我希望条形标签根据条形颜色具有不同的文本 colors,以帮助提高可见性(我仅限于条形的灰度 colors)我找到了一些管理此问题的示例,但它们会干扰其他部分我的代码,我不知道如何协调这一点。 Can anyone help?任何人都可以帮忙吗?

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)

update: out of luck with this one still.更新:这个仍然不走运。 please let me know if anyone can help.请让我知道是否有人可以提供帮助。

在此处输入图像描述

You can create a list of desired label colors, enumerate the ax.containers, and index the label_colors inside the loop as below.您可以创建所需 label colors 的列表,枚举 ax.containers,并在循环内索引 label_colors,如下所示。 In this case, I have chosen a label color of white to show on a background of black and dimgray while a label color of black shows on a background of darkgray and silver, but you can chose any colors you want.在这种情况下,我选择了白色的 label 颜色显示在黑色和暗灰色的背景上,而黑色的 label 颜色显示在深灰色和银色的背景上,但你可以选择任何你想要的 Z62848E3CE58204AA985513A7B2Z。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM