Science and technology

Precision information plotting in Python with Matplotlib

Python provides a wealthy set of choices for visualizing information. I will present you the fundamentals of plotting in Matplotlib by making a bar chart with grouped bars. It exhibits election outcomes for the UK between 1966 and 2020:

For a full comparability of Python plotting libraries, see The 7 most popular ways to plot data in Python.

Precise and highly effective

Matplotlib is the alligator of the plotting zoo. It’s been round for some time, but it surely’s nonetheless bought loads of chunk. Matplotlib provides you exact management over your plots—however, like something exact and highly effective, this typically forces you to suppose tougher than you may wish to.

To see what I imply, let’s begin creating the multi-bar plot. First, import Matplotlib and Numpy:

import matplotlib.pyplot as plt
import numpy as np

Then import the Pandas DataFrame containing the election outcomes:

# Import my election DataFrame in broad kind
from votes import broad as df

It’s in wide form, which means there is a column for every political celebration:

        yr  conservative  labour  liberal  others
zero       1966           253     364       12       1
1       1970           330     287        6       7
2   Feb 1974           297     301       14      18
..       ...           ...     ...      ...     ...
12      2015           330     232        eight      80
13      2017           317     262       12      59
14      2019           365     202       11      72

Next, inform Matplotlib that you simply’re making a determine with a single axis in it. It provides you a Figure and Axis object. If you might have a number of subplots, you might have one Figure and several other Axes.

# Create a Figure with one Axis on it
fig, ax = plt.subplots()

Making the bar plots

Now add the bar charts themselves. The multi-bar chart is made by drawing 4 separate bar charts on the identical axes—offset every bar chart by a specific amount, so they seem side-by-side. This means you need to work out the best way to calculate the offset for every bar chart, and should you wished so as to add one other political celebration, you’d need to rethink your calculation.

# The x-values of the bars.
years = df['yr']
x = np.arange(len(years))

# The width of the bars (1 = the entire width of the 'yr group')
width = zero.15

# Create the bar charts!
ax.bar(x - three*width/2, df['conservative'], width, label='Conservative', colour='#0343df')
ax.bar(x - width/2, df['labour'], width, label='Labour', colour='#e50000')
ax.bar(x + width/2, df['liberal'], width, label='Liberal', colour='#ffff14')
ax.bar(x + three*width/2, df['others'], width, label='Others', colour='#929591')

Axis labels and legend

That’s the plot it created by itself, however you nonetheless want so as to add some axis labels and a legend:

# Notice that options like labels and titles are added in separate steps
ax.set_ylabel('Seats')
ax.set_title('UK election outcomes')

ax.set_xticks(x)    # This ensures we now have one tick per yr, in any other case we get fewer
ax.set_xticklabels(years.astype(str).values, rotation='vertical')

ax.legend()

Make the magic occur

Finally, invoke the magic phrase to make the plot seem on the display:

plt.present()

Hey, presto!

It took a little bit of psychological effort, however you’ve got bought a pleasant, clear plot.

Power

You can most likely see how this API provides you a variety of energy. Let’s think about you wish to plot a line exhibiting the distinction in seats between the Conservative and Labour events. While you are at it, add a set of gridlines within the background and set some smart Y-axis limits:

    ax.plot(x, df['conservative'] - df['labour'], label='Conservative lead over Labour', colour='black', linestyle='dashed')
    ax.grid(colour='#eeeeee')
    ax.set_axisbelow(True)
    ax.set_ylim([-500, 500])

You can get it precisely the way you need it as a result of Matplotlib provides a low-level API that offers exact management of how issues look and the place they’re displayed.

If you like to run this elsewhere, you’ll be able to copy this instance as an Anvil app here (Note: Anvil requires registration to make use of).

Great chart, however can we make it less complicated?

All this energy is nice, however there should be a handful of plots that folks wish to make on a regular basis. Why cannot any person wrap Matplotlib in a high-level interface that makes issues a lot less complicated? That’s been finished, and it is known as Seaborn. We will look into that subsequent time.

In the meantime, congratulations in your first Matplotlib visualization!  


This article is predicated on How to make plots using Matplotlib on Anvil’s weblog and is reused with permission.

Most Popular

To Top