Python / Pandas - 在堆积的酒吧的不同的标签颜色

问题描述 投票:1回答:1

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

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

enter image description here

代码如下:

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')
python pandas stacked-chart
1个回答
0
投票

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

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

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.