簡體   English   中英

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

還有其他CONFIGS如字體大小等。第一塊裝置1, 4, 7所述陣列中的塊。 因此,您可以像使用np.isin()一樣提取數據幀的第一行並檢查height是否是單元格值之一;

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

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM