Matplotlib堆积的条形图标签(python)

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

我正在尝试使用matplotlib创建堆积的条形图。

所需的输出:-不显示零值作为标签-使用x作为地下室(它将不会显示在图形上)

for p in a.patches[4:]:
    width, height = p.get_width(), p.get_height()
    x, y = p.get_xy() 
    a.text(x+width/2, 
            y+height/2, 
            '{:.0f}'.format(height), 
            horizontalalignment='center', 
            verticalalignment='center')
plt.show()
python pandas matplotlib bar-chart data-science
1个回答
1
投票
似乎您所谓的“地下室”就是matplotlib称为条形图的“底部”。目前,pandas绘图不允许通过列名设置底部,但是可以通过提供列内容来进行处理。然后可以将x留在列中以进行绘制(以及白色)。

要跳过零的文本,请使用if测试来检查零。

import matplotlib.pyplot as plt import numpy as np import pandas as pd dflast = pd.DataFrame({'Line': {0: 'a', 1: 'b', 2: 'c', 3: 'd'}, 'x': {0: 0, 1: 118, 2: 117, 3: 0}, 'y': {0: 21, 1: 0, 2: 3, 3: 18}, 'z': {0: 72, 1: 0, 2: 11, 3: 67}, 't': {0: 24, 1: 5, 2: 4, 3: 26}, 'k': {0: 1, 1: 0, 2: 0, 3: 1}}) colors = ["green", "yellow", "red", "maroon"] ax = dflast.loc[:, ['y', 'z', 't', 'k']].plot.bar(stacked=True, bottom=dflast['x'], color=colors, edgecolor="none", width=0.3) ax.set_facecolor('w') h, l = ax.get_legend_handles_labels() ax.legend(h[1:5], ['y', 'z', 't', 'k'], loc='upper center', bbox_to_anchor=(0.5, -0.05), ncol=5, fontsize=5, borderaxespad=0, frameon=False, fancybox=True, shadow=True) ax.tick_params(axis='x', labelsize=5) ax.yaxis.set_visible(False) ax.xaxis.label.set_visible(False) ax.axhline(.4, xmin=0, xmax=1, linewidth=0.3, color=(0, 0, 0, 0.75)) for p in ax.patches: width, height = p.get_width(), p.get_height() x, y = p.get_xy() if height > 0: ax.text(x + width / 2, y + height / 2, '{:.0f}'.format(height), horizontalalignment='center', verticalalignment='center') plt.show()

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