Python/Pandas - 堆叠条上的不同标签颜色

Python/Pandas - Different label colors on stacked bar

我想更改每列中第一个块(深色块)的标签颜色以获得更好的可视化效果。有什么办法吗?

ps:我不想更改当前的调色板。只是第一块的颜色标签!

代码如下:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

sns.set_style("white")
sns.set_context({"figure.figsize": (7, 5)})

df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
           columns=['a', 'b', 'c'])

fig, ax = plt.subplots()
ax = df.plot.bar(stacked=True, cmap="cividis", alpha=1, edgecolor="black")
sns.despine(top=False, right=True, left=False, bottom=True)

#add text
for p in ax.patches:
    left, bottom, width, height =  p.get_bbox().bounds
    if height > 0 :
        ax.annotate("{0:.0f}".format(height), xy=(left+width/2, bottom+height/2), ha='center', va='center')

如果要保持相同的颜色图并更改标签颜色,可以在 annotate 函数中指定 color 参数,如下所示。

 ax.annotate("{0:.0f}".format(height), xy=(left+width/2, bottom+height/2), ha='center', va='center', color="white")

还有字体大小等其他配置。 第一个块表示数组中的 1, 4, 7 个块。因此,您可以提取数据框的第一行并使用 np.isin() like;

检查高度是否是单元格值之一
firstblocks = (df.iloc[:, 0])
for p in ax.patches:
    left, bottom, width, height = p.get_bbox().bounds

    if np.isin(p.get_height(), firstblocks):
        ax.annotate("{0:.0f}".format(height), xy=(left + width / 2, bottom + height / 2), ha='center', va='center',
                    color="white", fontsize=12)
    else:
        ax.annotate("{0:.0f}".format(height), xy=(left + width / 2, bottom + height / 2), ha='center', va='center')

希望这对您有所帮助。