Bar charts (bar graphs) is commonly used to show comparisons among categories (clusters, groups) with rectangular bars. Each bar's height (vertical bars) or length (horizontal bars) is proportional to the values that they represent. This article presents how to draw basic and stacked bar chart with the Python module Matplotlib.
1. Bar charts with error bar
plt.bar
makes a bar plot. plt.barh
makes a horizontal bar plot. plt.barbs
makes a 2-D field of barbs.
The rectangle is bounded by (left, left + width, bottom, bottom + height)
, representing the edge of (left, right, bottom, top)
. I make a bar chart with error bar, as shown below.
Fig. 1: A bar chart with error bar
The main source code is as follows. (The complete one is hosted at GitHub, barchart_errorbar.py)
def main():
# plot a barchart with error bar
fig, ax = plt.subplots()
legends = ['Q1', 'Q2', 'Q3', 'Q4']
# 4 groups, generate a random list with `random.sample(range(1, 5), 4)`
groups = [ [4, 3, 1, 2], # Q1
[1, 2, 3, 4], # Q2
[3, 1, 2, 4], # Q3
[2, 1, 4, 3]] # Q4
colors = ['r', 'g', 'b', 'm']
x = range(len(groups))
list_rects = list()
for idx, group in enumerate(groups):
left = [i+idx*0.2 for i in x]
rects = plt.bar(left, group,
width=0.2,
color=colors[idx],
yerr=0.1, ecolor='k', capsize=5,
orientation='vertical')
list_rects.append(rects)
# decoration
ax.legend(list_rects, legends, loc='best')
Error bars gives a general idea of how precise a measurement is. To plot an error bar, pass the parameter, xerr
or yerr
to plt.bar
.
xerr=None, # scalar or array-like, generate errorbar(s) on the bar chart
yerr=None, # scalar or array-like, generate errorbar(s) on the bar chart
ecolor=None, # scalar or array-like, specifies the color of errorbar(s)
capsize=None, # scalar, determines the length in points of the error bar caps
error_kw=, # dict, dictionary of kwargs to be passed to errorbar method
Write the value inside each bar
To produce a tidy graph, we can write the y coordinates of the bars inside each bar and remove axes by ax.axis('off')
.
rects = plt.bar(...)
def autolabel(rects, ax):
"""write the value inside each bar"""
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x()+rect.get_width()/2., height-0.4,
'%d' % int(height), fontsize=15, ha='center', va='bottom')
2. Stacked bar charts
The optional parameter bottom
of plt.bar()
allows us to specify a starting value for a bar, instead of zero. Here is a simple demo.
fig, ax = plt.subplots()
A = [3, 1, 2, 4]
B = [2, 1, 4, 3]
x = range(4)
ax.bar(x, A, color = 'b', label='A')
ax.bar(x, B, color = 'g', bottom=A, label='B')
ax.legend(loc='best')
ax.axis('off')
plt.show()
3. The arguments of plt.bar
# return a container with all of the bars + errorbars, matplotlib.container.BarContainer
bars = plt.bar( left, # the x coordinates of the left sides of the bars
height, # the y coordinates of the bars (the heights of the bars)
width=0.8, # scalar or array-like
bottom=None, # scalar or array-like, use for stacked bar charts
color=, # scalar or array-like, the colors of the bar faces
hold=None, # [True|False] overrides default hold state
data=None, # all positional and all keyword arguments are replaced by data[<arg>]
edgecolor=, # scalar or array-like, the colors of the bar edges
linewidth=None, # scalar or array-like, width of bar edge(s)
tick_label=None, # string or array-like, the tick labels of the bars
align=, # ‘edge’ | ‘center’, ‘edge’ for aligning bars by their left edges (a negative width for the right edges);
#‘center’ interpret the left argument as the coordinates of the centers of the bars.
orientation=, # ‘vertical’ | ‘horizontal’, the orientation of the bars.
log=False, # boolean, sets the axis to be log scale
xerr=None, # scalar or array-like, generate errorbar(s) on the bar chart
yerr=None, # scalar or array-like, generate errorbar(s) on the bar chart
ecolor=None, # scalar or array-like, specifies the color of errorbar(s)
capsize=None, # scalar, determines the length in points of the error bar caps
error_kw=, # dict, dictionary of kwargs to be passed to errorbar method
)
References:
[1] Official demos: barchart_demo.py
, barchart_demo2.py
and spine_placement_demo.py
.