Loading [MathJax]/extensions/Safe.js

Tuesday, June 27, 2017

Python Plotting Tutorial -- Part 1

Here's a script which makes a simple plot in python. First look at the example, then we'll break it down line by line.

Input:


Output:


Ok, let's break it down.


First, we need to tell python which supplemental packages and options we want to use. This is called the preamble:
The first line tells python we are using the package numpy (short for "numerical python"), and that we will reference functions from numpy using the name np. For example, np.sqrt means the function "sqrt" from the package "numpy". Similarly, we will call the package matplotlib.pyplot (which is a package for plotting) by the name plt. The third line is a special command for Jupyter notebooks, which tells Jupyter to display the plot in the output.


Next, we create the variable x by directly typing values into an array:
There are other ways to create a variable, but this is the simplest.


Then, we create a variable y with the values x squared:
Python uses "**" as the exponent symbol, which is somewhat unusual.

Before plotting, let us print out the variables x,y to see them directly:
The first line tells python to print out two things. First, the string "x =". Then, its representation of the variable x. Since x is a list, it shows the values surrounded by square brackets. Same for y on the second line. These lines produce the output:


Now to generate the plot. It will automatically be displayed in the output because of the earlier matplotlib inline command. To make the plot, we use the function plt.plot . This has two required arguments (the x and y arrays). It also accepts a number of "keyword arguments", which allow you to specify options like color, style, or line width. In this case we input:
and get the output shown above. Try changing the marker to 'x'. Try changing linestyle to '-' or '--'. You can also change the color. If you delete the keyword arguments, they will assume default values. If you delete the x or y inputs, you will cause an error. There are many more options to change the appearance of your graph -- we can cover those later.


Finally, we want to save our graph to use in the lab report:
I have specified the filename "part1.png". The extension tells python what file type you want. It will automatically be saved into the same folder as the notebook you are running (within your Jupyter account). The file should appear in the folder as seen here:

That should be enough to get you started. A key part of programming is getting good at googling things you don't know. So if you have Q's, you can ask me or just google away!

No comments:

Post a Comment