Blue Flower

Graphic programs with an intuitive user interface, such as Microsoft Excel, have allowed millions of people to use computers without learning how to program, but they add enough features over time that the user interface becomes so complex that it is not intuitive anymore. Users never use some features because they just cannot find them. On the other hand, programming languages have evolved to be simple and powerful. They are easy to learn, don't change with every version of software, and can express infinitely complex ideas - unlike graphic user interface. It is about time we switch from expensive proprietary software to the free scientific Python stack and one of its gems - the Matplotlib charting library. In this post, I will get you up to speed with one of the most popular plot types - the line plot with error bars.

Plotting is very easy in Python. You can make a line plot in just 3 lines of code:

import matplotlib.pyplot as plt #import plotting library
plt.plot([1,2,3,4], [1,4,9,16], "rs--") #X-s Y-s, R(ed)S(quare) marker, dashed line
plt.show() # show the plot

 But there is no way to add error bars to it. There is a special function errorbar to generate a plot with error bars

import matplotlib.pyplot as plt
%matplotlib inline
plt.errorbar(
    [1,2,3,4],  # X
    [1,4,9,16], # Y
    yerr=5,     # Y-errors
    label="Error bars plot",
    fmt="rs--", # format line like for plot()
    linewidth=3	# width of plot line
    )
plt.legend() #Show legend
plt.show()

Line plot with error barw drawn with default settings of Python pyplot library

The default graph looks ugly:

  • Line color and width are applied to both the line and error bars
  • The error bar caps are so short that they are almost invisible at this line width
  • There are two markers in the legend, they have error bars, and, because we used the dashed line, they look separate
  • The first and last points are right at the limits of the X-axis

Fortunately, it takes less than ten lines of code to make it much prettier:

Four extra parameters take care of the error bars appearance:

elinewidth=0.5,# width of error bar line
ecolor='k',    # color of error bar
capsize=10,    # cap length for error bar
capthick=0.5   # cap thickness for error bar

Getting rid of the error bars in the legend is not as straightforward though. The function errorbar returns three values: the plot line, error bar cap lines, and error bar lines. To get a label marker without error bars, we need to give a label to the regular plot line that the function uses under the hood. The parameters of the lines that have been plotted already can be adjusted with the pyplot function setp().

line,caps,bars=plt.errorbar(...)
plt.setp(line,label="Error bars plot")

The number of markers in a legend can be adjusted globally for all data series passing a numpoints parameter to a legend() function that adds a legend to the plot. And, while we are at it, let's also adjust the legend's position.

plt.legend(numpoints=1, loc=('upper left'))

The X-axis's limits can be adjusted by calling:

plt.xlim((0.5,4.5))

Here is the final result. Enjoy!

import matplotlib.pyplot as plt
%matplotlib inline

line,caps,bars=plt.errorbar(
    [1,2,3,4],     # X
    [1,4,9,16],    # Y
    yerr=5,        # Y-errors
    fmt="rs--",    # format line like for plot()
    linewidth=3,   # width of plot line
    elinewidth=0.5,# width of error bar line
    ecolor='k',    # color of error bar
    capsize=5,     # cap length for error bar
    capthick=0.5   # cap thickness for error bar
    )

plt.setp(line,label="My error bars")#give label to returned line
plt.legend(numpoints=1,             #Set the number of markers in label
           loc=('upper left'))      #Set label location
plt.xlim((0.5,4.5))                 #Set X-axis limits
plt.xticks([1,2,3,4])               #get only ticks we want
plt.yticks([0,5,10,15,20])
plt.show()

Publication quality scientific plot with error bars using Python and matplotlib's Pyplot module

References:

  1. Scientific Python distributions
  2. Pyplot documentation
  3. My book on getting started with scientific plotting using Python and Pyplot
Leave comment
Please register to add comment