Python Friday #172: Combine Multiple Plots in Matplotlib

Matplotlib allows us to draw our annotations on top of a plot. Today we look what happens if we draw a plot on top of another plot.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

Line plots work well

We can draw one line plot on top of another without any problems:

This gives us a figure with a line in red for the first and a line in green for the second plot:

Two lines (red, green) share the same figure

By specifying the parameter legend for each plot, we can have a legend on the figure.

 

Bar charts overlay each other

We can combine two bar charts and put them on the same axes:

We are lucky and the data we have for night and day temperature averages can be combined without any problems:

The orange night average temperature does not interfere much with the blue day average.

However, for different values the plot may be useless when it completely hides a bar.

 

Pie charts fall apart

We can create two pie charts and put them on the same axes:

Unfortunately, the result is a totally useless combination that no longer has any meaning:

We now have 4 labels on one pie chart with two different colours.

 

Manually layout your bar charts

If we want a bar chart with the bars nicely placed next to each other, we need to do a lot of work by hand. We need to convert our data into a structure that works for Matplotlib and then we need to calculate the position of each bar. The documentation offers us a nice example that I slightly modified by using the average temperatures from Bern instead of a pinguin population:

This creates us a plot with the day and night average temperatures next to each other:

A plot with bars next to each other instead of on top of each other.

 

Next

It depends very much on your data and on the type of diagram whether Matplotlib can create a useful combined diagram. There is always the option of doing the low-level work on your own, but we see that Matplotlib reaches its limits of giving us a nice looking plot without much effort.

Next week we will explore NetworkX before we continue with the plot functions of Pandas to see where we can use an abstraction for Matplotlib to get better results.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.