3

Having a question on showing actual values on the chart. I do have a printed chart and need to show values of each stacked bar. How can I show these values?

I have tried ax.text function but it does not give desired result(see in picture). As the chart is normalized to 1 I need to show actual values of each stacked bar (at the top is the total number and it should be split to each bar-first bar should have 1 number 7, second bar should have 3 numbers where number 41 is split by the size of each color bar). Is it possible to do this?

My code how I come up with multiple stacked bars:

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
                ha='center', va='bottom')

p = [] # list of bar properties
def create_subplot(matrix, colors, axis):
    bar_renderers = []
    ind = np.arange(matrix.shape[1])
    bottoms = np.cumsum(np.vstack((np.zeros(matrix.shape[1]), matrix)), axis=0)[:-1]
    for i, row in enumerate(matrix):
        print bottoms[i]
        r = axis.bar(ind, row, width=0.5, color=colors[i], bottom=bottoms[i])
        bar_renderers.append(r)
        autolabel(r)
    #axis.set_title(title,fontsize=28)
    return bar_renderers

p.extend(create_subplot(nauja_matrica,spalvos, ax))

enter image description here

Flabetvibes
  • 3,066
  • 20
  • 32
orangutangas
  • 391
  • 2
  • 7
  • 20

1 Answers1

6

You can show the values of each stacked bar with the ax.text function. There are few corrections to make to your code to nearly get the desired result. Actually, just replace the autolabel function by the following code:

def autolabel(rects):
    # Attach some text labels.
    for rect in rects:
        ax.text(rect.get_x() + rect.get_width() / 2.,
                rect.get_y() + rect.get_height() / 2.,
                '%f'%rect.get_height(),
                ha = 'center',
                va = 'center')

It will correct the vertical positioning of the labels and give: Staked bars with their values

If you want to change the labels to get the unormalized values then there is a little more work to do. The simplest solution is to pass an additional parameter values (which contains the unormalized values) to the autolabel function. The code will be:

def autolabel(rects, values):
    # Attach some text labels.
    for (rect, value) in zip(rects, values):
        ax.text(rect.get_x() + rect.get_width() / 2.,
                rect.get_y() + rect.get_height() / 2.,
                '%d'%value,
                ha = 'center',
                va = 'center')

I hope this will help you.

Flabetvibes
  • 3,066
  • 20
  • 32