Two-dimensional plots on Python [Part I]

Published on Author alexandrejaguarLeave a comment

Hey scientist! How is it going?
Today we’ll work with some simple 2D plots on Python. A great opportunity to drop that pirate Origin [1] you could have there…

Did you install Python and all the other stuff? If you didn’t install it yet, see this previous post [2] and set your Python system running.

This plot was customized from matplotlib’s [3] example page [4]. The commands we’ll use follow:

This results in the following little window:

Let’s study the code and see what each line do, ok?
All additional Python libraries must be imported before using them. For that we use:

In this example, we’ll import EVERYTHING (little star: *) from pylab [4] library. Pylab is a library included on the matplotlib package; it’s aimed to let Python closer from languages like Matlab [5], making scientific programming easy. On pylab page we have the history of Joe, that dropped Matlab to use Python instead…

After importing pylab we’ll have tons of functions to use. First, let’s create a vector t from 0 to 2, step 0.01; thus, our fearless t has the values 0, 0.01, 0.02, 0.03, …, 1.99. Notice that 2 isn’t contained in this set; if you’d like that, use linspace() [6]. The difference is that arange() uses a given step, and linspace() uses the desired size of the sample. After we created the dear t, we call y a sine curve (sin()) from  times t. It could be a cosine (cos()), tangent (tan()), exponential (exp()), … thousands and thousands of possibilities. Then, y will be calculated for each point using the value of t.

After we create these variables, we can use the good, old plot() command. The X axis will be t, and the Y axis well be… y itself. Unlike other languages, plot() doesn’t show the plot; we’ll have to use show() together. But hang on, we’ll let it pretty first.

To put a name on axes and a title on the figure, you can use xlabel(), ylabel() and title().

Then, to show the little grid on the figure we use grid().

Now we can show some stuff!

All right, then we have the figure above. If you’d like to save the figure instead of plotting it, you can put that before show():

And that finishes the plot!
This post is going too big! In the next one, I’ll show how to set your figure, change colors and put some different elements.
Gigaregards! Meeeerry christmas to you all!


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 *