I am following this tutorial/example to create stacked bar charts, however in my case I am representing various types of support tickets that are being received by specific technicians. As such, not all of the types are always present, so some of the bar values are zero and not all of the totals for each row add up to the same amount. I am trying to find a way to edit the labels such that they are either transparent or are simply not applied if a given bar width is zero, as right now there is a '0' label appearing between other categories. I am able to access the widths via something like the following:
for rect in rects:
if rect.get_width() == 0:
#delete label, set opacity, etc
However, if I try to do something like rect.set_width(None)
it errors out, which makes me think I can't just get rid of the label. It also does not appear that there is a way to set the opacity with matplotlib directly. Does anyone know of a way to remove the extraneous labels?
stacked bar chart showing extraneous lables
In your loop, ax.bar_label contains a list of Annotation objects. You can loop over each of these objects to get their text with .get_text() and if it's '0' you use .set_text("") to remove the label.
for i, (colname, color) in enumerate(zip(category_names, category_colors)):
widths = data[:, i]
starts = data_cum[:, i] - widths
rects = ax.barh(labels, widths, left=starts, height=0.5,
label=colname, color=color)
r, g, b, _ = color
text_color = 'black' if r * g * b < 0.5 else 'darkgrey'
all_labels = ax.bar_label(rects, label_type='center', color=text_color)
for lab in all_labels:
if lab.get_text() == '0':
lab.set_text("")