3 Plots In One Figure Python

 admin

Learning Objectives:

Python Multiple plots in one Figure: In this tutorial, we are going to learn about the multiple plots in one figure and its Python implementation. Submitted by Anuj Singh, on July 09, 2020 Most of the time, we need to compare multiple data and functions.

  1. I need to plot one stacked bar chart and two lines in the same figure. I have 5 columns–year,priority,value,opened and closed. I was able to plot stacked bar chart as shown in the code pasted below. Can anyone help me in plotting two more lines–one with ‘opened’ column w.r.t ‘year’ and other with ‘closed’ w.r.t ‘year’.
  2. Python Multiple Plots In One Figure Loop.
  • To be able to produce figures with multiple plot frames, with distinct axes labels and error bars.
  • To describe the interactive nature of programming to produce plots

Keywords: figure, axes, frame

In this section, we will discuss, in more detail, how Python produces plots and how we can produce multiple plots within a single programme, within the same figure.

3.3.1 Sizing and positioning plot frames

When a plot is drawn, it is drawn inside an abstract grid with its own coordinates, known as a plot frame . By default, Python chooses the size and positioning of the frame in which a plot is subsequently drawn. In particular, the bottom-left of a plot frame is taken to lie at the origin of this abstract grid, and the height and width of the plot frame are chosen to be something convenient, by default!

You can specify the size and shape of a plot frame by using the function add_axes(). The arguments of add_axes() are the x and y coordinates of the bottom-left of the frame, and the width and height of the frame. In particular, if the x and y coordinates of the bottom-left of the plot frame are x and y respectively, and the width and height of the plot frame are w and h respectively, the syntax to add this frame to a figure is:

plt.figure(1).add_axes((x, y, w, h))

Notice that the arguments of add_axes() are entries enclosed in curcly brackets ( ), instead of square brackets [ ] as for a list. The former object is a new kind of object known as a tuple: essentially a set of entries, seperated by commas, but enclosed in curly brackets ( ). The following example defines a tuple

For our purposes, you don’t need to know anything else about tuples, just that, in this case, they are passed to the function add_axes().

Let’s see how this works by adapting the example from 3.1.3 (a simple scatter plot). In this case we will set the x and y values of the bottom-left of the plot frame to be at the origin and we will set the width and height of the plot frame to be 1.5 and 0.5 respectively:

In this case, we obtain exactly the same plot obtained in example 3.1.3, but now the frame in which the plot is drawn has a size and position that we specified initially.

Exercise 3.3.1

1)

In the following code box, change the values of the entries of the tuple that is passed to add.axes() in order to generate a plot with various different sizes and positions.

The first two entries of the tuple passed to add_axes() can be positive or negative (to move the bottom-left corner of the frame up or down as required), but the last two entries, corresponding to the width and height of the plot, must be positive.

3.3.2 Adding and sizing/positioning a new plot frame

You can conveniently add a new plot frame to a figure, in exactly the same way as in the examples shown above, with a new position for the bottom-left of the frame and new width and height. This is how you could, for example, add a plot below (or above, or next to) an existing plot in a figure.

In the following example we will repear the example shown in 3.1.6 (Multiple plots in the same figure) and we will add a second plot frame below the first plot frame, with the same width but whose height is $0.2$ and where the top of the second frame coincices with the bottom of the first frame. We will add the same pair of plots that appear in 3.1.6 to each of the two frames:

Notice that in line-16 above, plt.figure(1) appears again, which we recall is the syntax for creating figure 1. In this case, we aren’t creating a new figure (figure 1 already existed since line 10), but we’re adding another frame to figure 1.

3.3.3 The “active frame”

Let’s do something odd; let’s take the previous example and move the bit where we added the plot of xvalues vs other_yvalues (on line 19) to before the line where we created the second frame (line 16). Can you guess what will happen? Let’s see what happens:

In this case, the code adds both plots (of xvalues vs yvalues and xvalues vs other_yvalues) to the first frame. This happened because we added the second plot before we created the second plot frame. When we create a plot frame, this frame becomes the active frame : every line of code that follows it applies only to that frame , until we create another frame. In jargon we say that “the plotting environment is interactive”. This essentially means that if write code that applies something to a plot, it applies to the active frame, and to do something to a plot in another plot frame, you have to switch the active frame to the new frame. This is why the line to generate the second plot, in the second frame, had to come after the second plot frame became the active frame.

3.3.4 Removing axes ticks

Let’s consider the following example, where we have placed two identical plot frames side-by-side, using the method described in 3.2.2 . We’ve assumed we have two data sets, ranging over the same y-values, but with two sets of x-values

An immediately unappealing feature of this figure is that the, even though these data are usefully depicted with a shared y-axis, the y-axis values are printed on the left of the right plot frame. In instances like this, you might want to just get rid of the ticks on one of the axes!

You can do this by using a combination of the functions gca(), get_xaxis()/get_yaxis() and set.ticks().

Python plot new figure

The syntax to remove the ticks from either the x or y axis of the plot in the active frame is:

plt.gca().axes.get_xaxis().set_ticks([]) to remove the x-ticks

plt.gca().axes.get_yaxis().set_ticks([]) to remove the y ticks

This is essentially complicated function call, but for now you can see how this works in practice and then you can simply copy and paste this line into your own code.

Going back to the previous example, we wanted to remove the ticks along the y-axis for the plot in the second plot frame. To achieve this we should add the line plt.gca().axes.get_yaxis().set_ticks([]) after the second plot frame has been created. We do this in the following example:

This looks much better!

3 Plots In One Figure Python

Exercise 3.3.2

1)

Determine whether it matters if you label the axes of a plot, or change the axes limits, before or after changing the orientation of a plot.

In this tutorial, we will learn how to use Python library Matplotlib to plot multiple lines on the same graph. Matplotlib is the perfect library to draw multiple lines on the same graph as its very easy to use. Since Matplotlib provides us with all the required functions to plot multiples lines on same chart, it’s pretty straight forward.

In our earlier article, we saw how we could use Matplotlib to plot a simple line to connect between points. However in that article, we had used Matplotlib to plot only a single line on our chart. But the truth is, in real world applications we would often want to use Matplotlib to plot multiple lines on the same graph. This tutorial will explain how to achieve this.

But before we start, let us first create the dataset required for our tutorial.

Creating dataset for Matplotlib to plot multiple lines on same graph

Just like we did in our previous tutorial, we will simply generate our sample dataset using Python’s range function.

Now, if you are unfamiliar with Python’s built-in range function, take a look at this tutorial we wrote about it earlier.

So the code to generate multiple datasets with Python’s range function looks like this:

With this, we now have our sample dataset saved in the Python variable x. So its time to start using these values to plot our chart.

Using Matplotlib to plot multiple lines on same graph

Wait a second! Using above code we got only one set of data. How are we going to use it to plot multiple lines on the same graph?

Well, the answer is that we can convert this single dataset into 3 different datasets by simply multiplying it with different values. So for example to create three different datasets we can do something like:

Cheeky huh?! 😉

So with our required datasets in place, we can start writing our code to draw different lines out of it. Here we go!

So these three lines of code is all that is required to draw 3 different lines on our graph using Matplotlib. But are you not so sure what these three lines are doing? Then let me explain the first line of code first. This should make the rest of the code clear as well, right?

Let us take a look at the first line of code again:

What we are doing over here is that we are calling Maplotlib’s plot function. The only job of this plot function is to draw or plot our data on the Matplotlib’s canvas!

But if you are not familiar with Matplotlib’s canvas, you should first read this article on Introduction to Matplotlib.

Understanding Matplotlib plot function’s parameters

3 Plots In One Figure Python

From this first line of code, you can also notice that we are passing two parameters to our plot function. The first parameter we pass is simply the value of x. This forms the x-axis values for our plot. On the other hand, the second parameter forms the y-axis values of our plot. But what is exactly happening here? Why is the second parameter looking so complicated?

What we are doing over here is that we are looping over each value of x and multiplying it by 1. So this is the final value that we use for the y-axis of the plot.

Python Figure Subplot

Now if you are able to keep up with me so far, then you will know what the last two lines of code does as well, right? You can see that they also do the same thing as our first line of code. The only difference is that they multiply the y-axis values with different co-efficients.

3 Plots In One Figure Python Function

Display the final output graph

3 Plots In One Figure Python Geeks

So far we in the code generated our sample dataset and drawn three lines using it on the same graph. But if you have followed along with me and typed in the code, you realize that no image is yet displayed. But why so? The reason is that we might have drawn the image on Matplotlib canvas, but we haven’t displayed it yet. In order to display our final output image, we still need to call one another function:

This Matplotlib’s show function is the one that is responsible to display the output on our screen. This function does not take any parameters as seen. But calling this in your code is a must if you want to display the graph on screen.

How To Plot A Graph In Python

So with just these 6 lines of code, we have been able to make Matplotlib plot multiple lines on same graph.

Here is the final output image drawn using the above piece of code.

One another interesting thing for us to note here is that Matplotlib has plot these multiple lines on the same graph using different colors. This is a built-in feature found in Matplotlib. If it needs to plot more than one line on the same graph, it automatically chooses different colors for different lines! In this way, we will be able to differentiate different datasets represented on a single chart. Isn’t it cool & beautiful? 😉

Plot 3 Graphs In One Figure Python

Conclusion

3 Plots In One Figure Python Example

So this is how we can make Matplotlib plot multiple lines on the same graph. By using Python’s Matplotlib and writing just 6 lines of code, we can get this result.

Here is the final summary of all the pieces of code put together in a single file:

Matplotlib is an easy to use Python visualization library that can be used to plot our datasets. We can use many different types of datasets and Matplotlib will still be to handle them. By familiarizing ourselves with this wonderful Python library package, we are adding new tool into our arsenal.

Hope this tutorial was easy enough for you to understand. If you have any queries on Matplotlib or Python in general, do not forget to comment below. I will try my best to provide you with all the helpful answers I can give. With this, I will conclude this tutorial on Matplotlib. Until next time, ciao!