Generate stacked barplot using Python and matplotlib.pyplot


The result is:

Generate stacked barplot using Python and matplotlib.pyplot

This page shows how to generate stacked barplot using Python and matplotlib.pyplot.

See also:

Python Matplotlib Tips: Add sample number to stacked barplot using Python and matplotlib.pyplot

This page shows how to add sample number to stacked barplot using Python and matplotlib.pyplot.

Python Matplotlib Tips: Generate normalized stacked barplot with sample number and percentage using Python and matplotlib.pyplot

This page shows how to generate normalized stacked barplot with sample number of each bar and percentage of each data using python and matplotlib.pyplot.


In [1]:
import numpy as np
print('numpy: '+np.version.full_version)
import matplotlib
print('matplotlib: '+matplotlib.__version__)
import matplotlib.pyplot as plt
%matplotlib inline
numpy: 1.15.1
matplotlib: 2.2.3

Sample data

In [2]:
x = ["a","b","c","d"]
y1 = np.array([3,8,6,4])
y2 = np.array([10,2,4,3])

You can generate stacked barplot by adding "bottom" option to plt.bar function.
Let's see the document:

In [3]:
plt.bar?
Signature: plt.bar(*args, **kwargs)
Docstring:
Make a bar plot.

Call signatures::

   bar(x, height, *, align='center', **kwargs)
   bar(x, height, width, *, align='center', **kwargs)
   bar(x, height, width, bottom, *, align='center', **kwargs)

The bars are positioned at *x* with the given *align* ment. Their
dimensions are given by *width* and *height*. The vertical baseline
is *bottom* (default 0).

Each of *x*, *height*, *width*, and *bottom* may either be a scalar
applying to all bars, or it may be a sequence of length N providing a
separate value for each bar.


Parameters
----------
x : sequence of scalars
    The x coordinates of the bars. See also *align* for the
    alignment of the bars to the coordinates.

height : scalar or sequence of scalars
    The height(s) of the bars.

width : scalar or array-like, optional
    The width(s) of the bars (default: 0.8).

bottom : scalar or array-like, optional
    The y coordinate(s) of the bars bases (default: 0).

align : {'center', 'edge'}, optional, default: 'center'
    Alignment of the bars to the *x* coordinates:

    - 'center': Center the base on the *x* positions.
    - 'edge': Align the left edges of the bars with the *x* positions.

    To align the bars on the right edge pass a negative *width* and
    ``align='edge'``.

Returns
-------
container : `.BarContainer`
    Container with all the bars and optionally errorbars.

Other Parameters
----------------
color : scalar or array-like, optional
    The colors of the bar faces.

edgecolor : scalar or array-like, optional
    The colors of the bar edges.

linewidth : scalar or array-like, optional
    Width of the bar edge(s). If 0, don't draw edges.

tick_label : string or array-like, optional
    The tick labels of the bars.
    Default: None (Use default numeric labels.)

xerr, yerr : scalar or array-like of shape(N,) or shape(2,N), optional
    If not *None*, add horizontal / vertical errorbars to the bar tips.
    The values are +/- sizes relative to the data:

    - scalar: symmetric +/- values for all bars
    - shape(N,): symmetric +/- values for each bar
    - shape(2,N): Separate - and + values for each bar. First row
        contains the lower errors, the second row contains the
        upper errors.
    - *None*: No errorbar. (Default)

    See :doc:`/gallery/statistics/errorbar_features`
    for an example on the usage of ``xerr`` and ``yerr``.

ecolor : scalar or array-like, optional, default: 'black'
    The line color of the errorbars.

capsize : scalar, optional
   The length of the error bar caps in points.
   Default: None, which will take the value from
   :rc:`errorbar.capsize`.

error_kw : dict, optional
    Dictionary of kwargs to be passed to the `~.Axes.errorbar`
    method. Values of *ecolor* or *capsize* defined here take
    precedence over the independent kwargs.

log : bool, optional, default: False
    If *True*, set the y-axis to be log scale.

orientation : {'vertical',  'horizontal'}, optional
    *This is for internal use only.* Please use `barh` for
    horizontal bar plots. Default: 'vertical'.

See also
--------
barh: Plot a horizontal bar plot.

Notes
-----
The optional arguments *color*, *edgecolor*, *linewidth*,
*xerr*, and *yerr* can be either scalars or sequences of
length equal to the number of bars.  This enables you to use
bar as the basis for stacked bar charts, or candlestick plots.
Detail: *xerr* and *yerr* are passed directly to
:meth:`errorbar`, so they can also have shape 2xN for
independent specification of lower and upper errors.

Other optional kwargs:

  agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array 
  alpha: float or None 
  animated: bool 
  antialiased or aa: bool or None 
  capstyle: ['butt' | 'round' | 'projecting'] 
  clip_box: a `.Bbox` instance 
  clip_on: bool 
  clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None] 
  color: matplotlib color spec
  contains: a callable function 
  edgecolor or ec: mpl color spec, None, 'none', or 'auto' 
  facecolor or fc: mpl color spec, or None for default, or 'none' for no color 
  figure: a `.Figure` instance 
  fill: bool 
  gid: an id string 
  hatch: ['/' | '\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*'] 
  joinstyle: ['miter' | 'round' | 'bevel'] 
  label: object 
  linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
  linewidth or lw: float or None for default 
  path_effects: `.AbstractPathEffect` 
  picker: [None | bool | float | callable] 
  rasterized: bool or None 
  sketch_params: (scale: float, length: float, randomness: float) 
  snap: bool or None 
  transform: `.Transform` 
  url: a url string 
  visible: bool 
  zorder: float 

.. note::
    In addition to the above described arguments, this function can take a
    **data** keyword argument. If such a **data** argument is given, the
    following arguments are replaced by **data[<arg>]**:

    * All arguments with the following names: 'bottom', 'color', 'ecolor', 'edgecolor', 'height', 'left', 'linewidth', 'tick_label', 'width', 'x', 'xerr', 'y', 'yerr'.
    * All positional arguments.
File:      ~/miniconda3/envs/py363/lib/python3.6/site-packages/matplotlib/pyplot.py
Type:      function
In [4]:
plt.figure(figsize=(4,3))

plt.bar(x, y1, label='y1')
# stack y2 on top of y1.
plt.bar(x, y2 ,bottom=y1,label='y2')

plt.legend()
plt.savefig('stacked_barplot.png', bbox_inches='tight', pad_inches=0.02)