How do you show values on a stacked bar chart in python?

here is one way to do it:

ax=df.plot[kind='bar', stacked=True]
#loop to add the text
list_values = [dffinal['numPatients6month'].tolist[][::3] 
                + dffinal['numPatients6month'].tolist[][1::3] 
                + dffinal['numPatients6month'].tolist[][2::3]]
for rect, value in zip[ax.patches, list_values]:
    h = rect.get_height[] /2.
    w = rect.get_width[] /2.
    x, y = rect.get_xy[]
    ax.text[x+w, y+h,value,horizontalalignment='center',verticalalignment='center']
#same than your code
plt.xticks[range[0,10], ['6month','1 year','1.5 year','2 year','2.5 year','3 year','3.5 year','4 year','4.5 year','5 year'], fontsize=8, rotation=45]
plt.title['Cognitive Impairement-Stack bar']
plt.show[]

The list_values is to get the value from the column 'numPatients6month' in the same order than the rect from ax.patches and the result is:

but because some bars are small the results is not really easy to read.

EDIT: about the loop, ax.patches contains informations about all the bar you plot, so for each bar that I named rect, with get_xy you get the position of the bottom left corner of the bar, and with get_height [r. get_width] get the height [r. width] of the bar. so [x+w, y+h] gives the coordinates of the middle of the bar, where you add the text value [from list_values] with the function ax.text [parameters horizontalalignment and verticalalignment are to center the text]

EDIT 2: more general method, thanks to @SpghttCd for getting list_values

list_values = [dffinal.drop['final-formula', 1].groupby[['6month','Question Text']].sum[]
               .unstack['Question Text'].fillna[0].astype[int].values.flatten['F']]
for rect, value in zip[ax.patches, list_values]:
    if value != 0:
        h = rect.get_height[] /2.
        w = rect.get_width[] /2.
        x, y = rect.get_xy[]
        ax.text[x+w, y+h,value,horizontalalignment='center',verticalalignment='center']

Plotting stacked bar charts with labels in Matplotlib

This post will go through a few examples of creating stacked bar charts using Matplotlib. We'll look at some styling tweaks [like choosing custom colors] as well as go through how to add labels to the bars, both the totals and sub-totals for each bar.

And be sure to check out our related post on creating stacked bar charts using several python libraries beyond Matplotlib, like Seaborn and Altair.

Simple Stacked Bar Chart

The general idea for creating stacked bar charts in Matplotlib is that you'll plot one set of bars [the bottom], and then plot another set of bars on top, offset by the height of the previous bars, so the bottom of the second set starts at the top of the first set. Sound confusing? It's really not, so let's get into it.

Let's first get some data to work with.

import seaborn as sns

tips = sns.load_dataset['tips']
# Let's massage the data a bit to be aggregated by day of week, with
# columns for each gender. We could leave it in long format as well [
# with gender as values in a single column].
agg_tips = tips.groupby[['day', 'sex']]['tip'].sum[].unstack[].fillna[0]
agg_tips

sexMaleFemaledayThurFriSatSun
89.41 82.42
26.93 25.03
181.95 78.45
186.78 60.61

Now let's create our first chart. We want to know the total amount tipped by day of week, split out by gender.

from matplotlib import pyplot as plt

fig, ax = plt.subplots[]
# First plot the 'Male' bars for every day.
ax.bar[agg_tips.index, agg_tips['Male'], label='Male']
# Then plot the 'Female' bars on top, starting at the top of the 'Male'
# bars.
ax.bar[agg_tips.index, agg_tips['Female'], bottom=agg_tips['Male'],
       label='Female']
ax.set_title['Tips by Day and Gender']
ax.legend[]

As you can see, it's pretty simple. We first plot tips that males gave and then plot tips that females gave, but give an additional bottom argument to tell Matplotlib where to start the bars [which happens to be the values of the previous bars; in this case male tips].

The above code generates this lovely plot:

Customizing the Stacked Bar Chart

The problem with the above code is that it starts to get very verbose, and quite repetitive, if we have more than a few layers in our stacked bars. So let's make it a bit more DRY.

import numpy as np
from matplotlib import pyplot as plt

fig, ax = plt.subplots[]

# Initialize the bottom at zero for the first set of bars.
bottom = np.zeros[len[agg_tips]]

# Plot each layer of the bar, adding each bar to the "bottom" so
# the next bar starts higher.
for i, col in enumerate[agg_tips.columns]:
  ax.bar[agg_tips.index, agg_tips[col], bottom=bottom, label=col]
  bottom += np.array[agg_tips[col]]

ax.set_title['Tips by Day and Gender']
ax.legend[]

This gives the exact same output as above, but is much nicer because we can apply it to any stacked bar need now, and it can handle as many layers as you need.

It's also pretty flexible; for example, if we want to use custom colors we can easily do that:

fig, ax = plt.subplots[]

colors = ['#24b1d1', '#ae24d1']
bottom = np.zeros[len[agg_tips]]

for i, col in enumerate[agg_tips.columns]:
  ax.bar[agg_tips.index, agg_tips[col], bottom=bottom, label=col,
         color=colors[i]]
  bottom += np.array[agg_tips[col]]

ax.set_title['Tips by Day and Gender']
ax.legend[]

Adding Labels to the Bars

It's often nice to add value labels to the bars in a bar chart. With a stacked bar chart, it's a bit trickier, because you could add a total label or a label for each sub-bar within the stack. We'll show you how to do both.

Adding a Total Label

We'll do the same thing as above, but add a step where we compute the totals for each day of the week and then use ax.text[] to add those above each bar.

fig, ax = plt.subplots[]

colors = ['#24b1d1', '#ae24d1']
bottom = np.zeros[len[agg_tips]]

for i, col in enumerate[agg_tips.columns]:
  ax.bar[
      agg_tips.index, agg_tips[col], bottom=bottom, label=col, color=colors[i]]
  bottom += np.array[agg_tips[col]]

# Sum up the rows of our data to get the total value of each bar.
totals = agg_tips.sum[axis=1]
# Set an offset that is used to bump the label up a bit above the bar.
y_offset = 4
# Add labels to each bar.
for i, total in enumerate[totals]:
  ax.text[totals.index[i], total + y_offset, round[total], ha='center',
          weight='bold']

ax.set_title['Tips by Day and Gender']
ax.legend[]

Adding both Sub-Bar and Total Labels

Now let's do the same thing again, but this time, add annotations for each sub-bar in the stack. The method here is a bit different; we can actually get the patches or bars that we've already plotted, read their values, and then add those values as text annotations at the right location.

fig, ax = plt.subplots[]

colors = ['#24b1d1', '#ae24d1']
bottom = np.zeros[len[agg_tips]]

for i, col in enumerate[agg_tips.columns]:
  ax.bar[
      agg_tips.index, agg_tips[col], bottom=bottom, label=col, color=colors[i]]
  bottom += np.array[agg_tips[col]]

totals = agg_tips.sum[axis=1]
y_offset = 4
for i, total in enumerate[totals]:
  ax.text[totals.index[i], total + y_offset, round[total], ha='center',
          weight='bold']

# Let's put the annotations inside the bars themselves by using a
# negative offset.
y_offset = -15
# For each patch [basically each rectangle within the bar], add a label.
for bar in ax.patches:
  ax.text[
      # Put the text in the middle of each bar. get_x returns the start
      # so we add half the width to get to the middle.
      bar.get_x[] + bar.get_width[] / 2,
      # Vertically, add the height of the bar to the start of the bar,
      # along with the offset.
      bar.get_height[] + bar.get_y[] + y_offset,
      # This is actual value we'll show.
      round[bar.get_height[]],
      # Center the labels and style them a bit.
      ha='center',
      color='w',
      weight='bold',
      size=8
  ]

ax.set_title['Tips by Day and Gender']
ax.legend[]

Looks good. Thanks for reading and hopefully this helps get you on your way in creating annotated stacked bar charts in Matplotlib.

How do you show values in a stacked bar chart in Python?

bar[stacked=True] , or pandas. DataFrame. plot[kind='bar', stacked=True] , is the easiest way to plot a stacked bar plot. This method returns a matplotlib.

How do I show numbers on a stacked bar chart?

The Keys to Adding Totals to the Stacked Bar Chart Above:.
Highlight your data including the “Spacing” column but not including the “Grand Total” column. ... .
On the “Insert” menu select a “2-D Stacked Bar Chart”.
Select “Switch Row/Column” as necessary so the “Spacing” values are not listed as an option on the Y axis..

How do you display a value in a bar chart?

Add data labels Click the chart, and then click the Chart Design tab. Click Add Chart Element and select Data Labels, and then select a location for the data label option. Note: The options will differ depending on your chart type. If you want to show your data label inside a text bubble shape, click Data Callout.

How do you add a value to a bar chart in Python?

To add value labels on a Matplotlib bar chart, we can use the pyplot. text[] function. The pyplot. text[] function from the Matplotlib module is used to add text values to any location in the graph.

Chủ Đề