我想更改每列中第一个块(深色)的标签颜色,以获得更好的可视化效果。有什么办法吗?
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')
如果要保持相同的颜色映射并更改标签颜色,可以在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')
希望这可以帮助。