将标签放置在每个堆叠条的顶部,并在 matplotlib 中设置字体颜色

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

我有以下代码(DF和图表):

import pandas as pd
import matplotlib.pyplot as plt

data = [['2005','A',10],['2006','A',15],['2007','A',10],
                       ['2005','B',15],['2006','B',70],['2007','B',10],
                       ['2005','C',75],['2006','C',15],['2007','C',80]
                      ]


df = pd.DataFrame(
    data=data, 
    columns=['year','type','count'])

fig, ax = plt.subplots(figsize=(15, 7),facecolor = '#fdf1e6')
ax.set_facecolor('#fdf1e6')

ax = sns.histplot(df, x='year', 
                  hue='type', 
                  weights='count',
                  multiple='stack', 
                  shrink=0.9,
                  linewidth=3.5,
                  )

ax.get_legend().remove()

for c in ax.containers:
    ax.bar_label(c, fmt=lambda x: f'{x:.0%}' if x > 0 else '', label_type='center')

结果是

我想将每个堆栈标签放置在每个堆栈的顶部(现在位于每个堆栈的中心)并将字体颜色更改为白色。

有什么想法吗?

谢谢!!!

python matplotlib stacked-bar-chart
1个回答
0
投票

删除

label_type='center'
(默认为
'edge'
),对
padding
使用负值,添加
color
参数,并使用
get_height
,例如:

for c in ax.containers:
    labs = [f'{r.get_height():.0%}' if r.get_height() > 0 else '' for r in c]
    ax.bar_label(c, labs, color='w', padding=-15)

输出:

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