您可以通过注释条与参考问题类似地执行此 *** 作。对于堆积的条形图,您必须稍微调整标签的位置,以使其位于所需位置。您可以使用
horizontalalignment,
verticalalignment并像我一样添加一点空白(+.5)。
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom cycler import cycler#used gray colormap, you can use your own colors by replacing colormap='gray' with color=colorscolors = ["#252525", "#636363", "#969696", "#cccccc", "#f7f7f7"]plt.rcParams['axes.prop_cycle'] = cycler(color=colors)#dummy datadf = pd.Dataframe(np.random.randint(5, 8, (10, 3)), columns=['Group1', 'Group2', 'Group3'])for col in df.columns.tolist(): df[col] = df[col].apply(lambda x:x*100 / df[col].sum())ax = df.T.plot.barh(stacked=True, colormap='gray', edgecolor='black', linewidth=1)for lbl in ax.patches: ax.annotate("{:.0f}%".format(int(lbl.get_width())), (lbl.get_x(), lbl.get_y()+.5), verticalalignment='bottom', horizontalalignment='top', fontsize=8, color='black')ax.legend(loc='center left', bbox_to_anchor=(1.0, .5))ax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['bottom'].set_visible(False)ax.spines['left'].set_visible(False)plt.show()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)