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

Python/Pandas-堆叠条上的不同标签颜色,python,pandas,stacked-chart,Python,Pandas,Stacked Chart,我想更改每列中第一个块(深色块)的标签颜色,以获得更好的可视化效果。有办法吗 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.DataFram

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

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

希望这能有所帮助。

如果您想保持相同的颜色映射并更改标签颜色,您可以在
注释
函数中指定
颜色
参数,如下所示

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

希望这能有所帮助。

您是指每列中的第一个区块(深色区块)?您是指每列中的第一个区块(深色区块)?谢谢您的回答!!我真的不想改变当前的调色板。如果可能的话,我只想将第一个块的标签颜色更改为可见…请将其放入问题中,否则我们怎么知道?注释中的颜色参数适用于所有块。如果可能的话,我只想更改第一个块的标签颜色以使其可见。。。有没有办法只指定第一个块的标签颜色?现在看看。是的,有办法!但它仅在数据集没有重复值(如[1,1.1])时才起作用。也许最好的解决方案是尝试使用dataframe列名,而不是手动值。我会记住这一点再试一次。谢谢你的回答!!我真的不想改变当前的调色板。如果可能的话,我只想将第一个块的标签颜色更改为可见…请将其放入问题中,否则我们怎么知道?注释中的颜色参数适用于所有块。如果可能的话,我只想更改第一个块的标签颜色以使其可见。。。有没有办法只指定第一个块的标签颜色?现在看看。是的,有办法!但它仅在数据集没有重复值(如[1,1.1])时才起作用。也许最好的解决方案是尝试使用dataframe列名,而不是手动值。我会记住这一点再试一次。。