WeCodeAcademy

Grouped and Stacked Bars

To compare categories across a second variable, put several bars at each position. Grouped bars sit side by side so each pair can be compared; stacked bars pile up so the total and its parts show together. Matplotlib has no single call for grouped bars, so you shift the x positions: use numpy to make positions, then offset each series by half a bar width. For stacking, pass bottom= with the heights below.

Rule of thumb: grouped bars compare the parts, stacked bars compare the totals. Only the bottom part of a stack shares a common baseline, so keep stacks to two or three parts.

Examplepython
Open in editor »
Quick check

Which argument stacks a bar on top of another?

Your turn: write the code

Draw the stacked bars (second series on top of the first with bottom=) and print the top edge of each stacked bar, which is the total (use [int(p.get_y() + p.get_height()) for p in ax.patches[3:]]).

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.