Two-dimensional plots on Python [Part III]

Published on Author alexandrejaguarLeave a comment

Hey scientist! How is it going?
Yes, we weren’t here on the previous week, but… we’re back! 🙂
Let’s continue the series about 2D plots on Python. How about to put several plots on the same window? Maybe you want to compare some information on different plots. We’ll use the command subplots() for that.

In this example we’ll put a sine and a cosine on the same plot, ranging from 0 to 2. If you have any doubts on the first commands, please check the previous posts ([1] and [2]), ok? The code follows:

Very well. We just said to subplots() that we want two plots on the same figure, and we want them sharing the same X axis (sharex=True). The figure is contained on the variable fig, and the axes were attributed to the variable ax; then, the coefficient 0 on ax represents the first plot. The coefficient 1, by its turn, represents the second one. Python starts to count on zero, not one!

The result follows:

How nice it is, right? If you want your plots in columns instead of rows, just change the previous subplots() by this:

And this is the result:

Awesome! If you need more plots, you can use any number you want. Let’s say 5:

In this example we would have 5 plots in different rows: ax[0], ax[1], ax[2], ax[3], ax[4]. Note that when we want only plots in rows, the second number is not necessary.

We also can divide the plots into rows and columns. If you’d like to have 3 rows and 2 colums of plots, the command is:

In this case, we would use the ax variable as a matrix. Then, the plots would be:

  • first row, first column: ax[0, 0] (or a[0][0])
  • second row, first column: ax[1, 0] (or a[1][0])
  • third row, first column: ax[2, 0] (or a[2][0])
  • first row, second column: ax[0, 1] (or a[0][1])
  • second row, second column: ax[1, 1] (or a[1][0])
  • third row, second column: ax[2, 1] (or a[2][0])

Let’s exemplify. The following code presents sine, cosine, tangent, secant and cosecant of π/8 in different colors and line styles:

The resulting plots follow:

This is it fellows! Now you can put several plots on the same window. I’ll stop this 2D plot series for now, let’s work with different things a little 🙂 Try the commands, make your plots and show us how they look!
Gigaregards, see you next time!


Did you like this post? Please comment and share with your friends!
Want to download Programming Science codes? Go to our GitHub!
I’m on Twitter: @alexdesiqueira! Follow me if you can!
Make a donation for Programming Science!

ShareEmail this to someoneShare on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on RedditShare on TumblrPin on Pinterest

Leave a Reply

Your email address will not be published. Required fields are marked *