繁体   English   中英

如何将图例标签添加为条形图注释?

[英]How to add the Legend labels as barplot annotations?

我想根据出现在图例中的文本获取注释到条形图。 请看一下我的最小复制示例:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

data = { 'cat1':[np.nan, 0.33, 0.25], 'cat2':[0.4, 0.33, np.nan], 'cat3':[np.nan, np.nan, 0.25]}
df = pd.DataFrame(data)
fig = plt.figure();
ax = df.plot.barh(stacked=True, figsize=(10,8));
ax.grid()
ax.legend()
 
# annotations:
for p in ax.patches:
    left, bottom, width, height = p.get_bbox().bounds
    if width > 0:
         ax.annotate((str(round(width*100))+' %'), xy=(left+width/2, bottom+height/2), 
                    ha='center', va='center')

我得到的看起来像这样:

在此处输入图像描述

但我想要一个像这样的 output (在单栏中将图例的描述作为注释)

在此处输入图像描述

我试图从ax.patches[0].get_label()中获取注释文本,但它给出了 output '_nolegend_'

谢谢您的帮助

  • 查看内联代码注释
  • 当绘制堆积条时,首先绘制底部补丁p ,它对应于图例labels中的第一个值。
  • 除了i == 0时,根据df的长度将counter的值增加 1,并使用counterlabels索引正确的 label 。
    • 在这种情况下,前 31 个补丁的counter将是0 ,然后对于第二个 31 个补丁递增到1 ,依此类推。
      • 当每个 label 的所有行 (31) 都已绘制完毕时,计数器需要增加。
  • 我将为图例使用不同的调色板,因为所有列的当前调色板中没有足够的 colors
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns

# set up the dataframe
df = pd.read_csv('test.csv')
df.set_index('hyd_yr', inplace=True)

# new color palette
colors = sns.color_palette('husl', n_colors=len(df.columns))

# plot
fig = plt.figure();
ax = df.plot.barh(stacked=True, figsize=(20, 16), color=colors)
ax.grid()
ax.legend()
handles, labels = ax.get_legend_handles_labels()  # extract the legend labels
 
# annotations:
counter = 0  # counter is used to index legend labels
for i, p in enumerate(ax.patches, 0):  #
    if (i % len(df) == 0) & (i != 0):  # reset counter to 0 based on length of df
        counter += 1  # increment the counter
    left, bottom, width, height = p.get_bbox().bounds
    label = labels[counter]  # index the correct label
    if width > 0:
         ax.annotate((f'{label}: {width*100:0.0f}%'), xy=(left+width/2, bottom+height/2), ha='center', va='center')

在此处输入图像描述

测试中的真实数据test.csv

hyd_yr,BM,HFA,HFZ,HM,HNA,HNZ,NWA,NWZ,NZ,SEA,SWA,SWZ,TB,TRM,WA,WS,WZ
1989,,,,,,,,0.0979020979020979,,,,,,,0.3006993006993007,,0.23776223776223776
1990,0.14835164835164835,,,,,,,,,,,,,,0.17582417582417584,,0.21428571428571427
1991,0.23626373626373626,0.08791208791208792,,,,,,,,,,,,,,,0.25824175824175827
1992,,,,0.18032786885245902,,,,,,,,,,,0.16393442622950818,,0.16393442622950818
1993,0.0989010989010989,,,0.12087912087912088,,,,,,,,,,,,,0.22527472527472528
1994,,,0.07142857142857142,,,,,,,0.09340659340659341,,,,,,,0.34615384615384615
1995,,,,0.1043956043956044,,,,0.0989010989010989,,,,,,,,,0.3241758241758242
1996,,0.12571428571428572,,,,,,,0.11428571428571428,,0.13142857142857142,,,,,,
1997,,,,0.08791208791208792,,,,,,,,,,,0.08791208791208792,,0.2032967032967033
1998,,,,,0.08241758241758242,,0.08791208791208792,,,,,,,,,,0.22527472527472528
1999,0.15934065934065933,,,,,,,,,,,,,0.09340659340659341,,,0.23076923076923078
2000,,,,,,,,0.11475409836065574,,,,,,,0.12021857923497267,,0.22404371584699453
2001,,,,,,,,,,,,0.11299435028248588,0.11299435028248588,,,,0.1751412429378531
2002,0.1043956043956044,,,,,,,0.17032967032967034,,,,,,,,,0.2032967032967033
2003,0.11538461538461539,0.11538461538461539,,,,,,,,,,,,,,,0.14285714285714285
2004,0.14207650273224043,,,,,,,,,,,,,0.12568306010928962,,,0.2185792349726776
2005,0.13736263736263737,,,,,,,0.13736263736263737,,,,,,0.2087912087912088,,,
2006,0.13186813186813187,,,,,,,0.15934065934065933,,,,,,0.13736263736263737,,,
2007,0.10989010989010989,,,,,,,,,,,0.16483516483516483,,,,,0.21428571428571427
2008,0.20765027322404372,,,,,,,0.08196721311475409,,,,,,,,,0.28415300546448086
2009,0.11731843575418995,,,,,,,0.12290502793296089,,,,,,0.10614525139664804,,,
2010,,,,,,,,,,,,0.10989010989010989,,,,0.12637362637362637,0.13186813186813187
2011,0.15254237288135594,,,,,,,,,,,0.0903954802259887,,,,,0.11864406779661017
2012,,,,0.10382513661202186,,,,0.18032786885245902,,,,,,,,,0.15300546448087432
2013,,,,,,0.13186813186813187,,,,,,,,0.15934065934065933,,,0.10989010989010989
2014,0.1043956043956044,,,,,,,,,,,0.23076923076923078,,,,,0.08241758241758242
2015,0.12290502793296089,,,,,,,,,,,,,0.1452513966480447,,,0.1340782122905028
2016,,,,,,,,,,,,,,0.09836065573770492,0.1366120218579235,,0.14207650273224043
2017,0.14285714285714285,,,0.14835164835164835,,,,,,,,,,,,,0.13736263736263737
2018,0.1043956043956044,,,,,,,,,,,,,0.12637362637362637,,,0.15934065934065933
2019,0.11363636363636363,,,,,,0.12121212121212122,0.12121212121212122,,,,,,,,,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM