Graphing using Python and Matplotlib

In this article I will introduce you to graphing in python using matplotlib. There are many kinds of charts you can use with matplot lib. By the end of this article, you should understand how to draw basic bar, line, and scatterplot charts.

As you go through each of the example charts, you will see there are two arrays. These arrays are for the X and Y axis. And will sometimes include labels for the values on the chart.

Prerequisites

Before you get started, you will need to intall the prerequisites. You can do that by running the following command:pip3 install matplotlibpip3 install numpy

Drawing a bar chart

Bar charts are good for comparing a small list of values. For example, perhaps you want to compare how many miles each person walked in the last week. We create a list of people, Matt, Sally, John. We then create a list of how many miles they walked. lets just say 1,2,3 respectively.

Below is the code for drawing our bar chart. See the comments for details:

The above code will produce the following chart:

Bar Chart

Drawing a line chart

A line chart is good for showing data over time, or showing the correlation between two values. In this case, we are just doing a generic line chart.

The above code will produce the following chart:

Line Chart

Drawing a Scatter Plot

Scatter plots are good for thowing a bunch of values onto a chart and see if any patterns emerge. You might find that there are clusters of values. Or you might find that the values form a line.

The above code will produce the following chart:

Scatter Plot

The following code is similar to the above chart. However, in this example, we pass in an array of points to draw instead of drawing the points one at a time:

The above code will produce the following chart:

Scatter Plot

Draw a line showing the slope

As mentioned in the previous section, you might find that the scatter plots form a slope. The code below will calculate the slope of the line and draw it on your graph to help you spot a trend. You will notice that we are now including the numpy module. numpy is a module used for adding higher level mathematical functions to python as well as some some features around multi-dimentional arrays.

[code language=”plain”][/code]

The above code will produce the following chart:

Scatterplot with line

%d bloggers like this: