September 28 { Making Graphs with Python
September 28 ? Making Graphs with Python
Basics
There are three main ways to generate graphs with Python using the library matplotlib:
1. using a Jypyter notebook; this is the recommended way but does not work on noether. If you want to use Jupyter on your home computer, you can find information on how to do it at
2. by starting the Python interpreter using the command python and then typing in one-by-one the various commands.
3. by typing all commands in a file called, e.g., plot.py and then giving the command python plot.py & in the prompt. We will be using primarily this last method.
A good tutorial for creating simple graphs with Python can be found at
Making a basic plot
The following lines of code plot a single line between points with coordinates given in the two arrays xarray and yarray.
import numpy as np import matplotlib.pyplot as plt xarray=[1,2,3,4] yarray=[1,4,9,16] plt.plot(xarray,yarray) plt.xlabel('x-axis label') plt.ylabel('y-axis label') plt.show()
The output should look like:
# imports library for math # imports library for plots # array with x-coordinates # array with y-coordinates # plot xarray vs. yarray # label for x-axis # label for y-axis # show the plot
y-axis label
16
14
12
10
8
6
4
2
01.0
1.5
2.0
2.5
3.0
3.5
4.0
x-axis label
Without giving any additional options, Python will generate a plot with a solid line connecting the points and with the ranges of the axes chosen by the graphics algorithm.
In order to set a user-defined range for the axes (say the x-axis to go from 0 to 6 and the y-axis to go from 0 to 20), we use the command
plt.axis([0, 6, 0, 20]) whereas to change the type of the plot, we give the command
plt.plot(xarray,yarray,'ro') # red circle
Our code then becomes
import numpy as np import matplotlib.pyplot as plt xarray=[1,2,3,4] yarray=[1,4,9,16] plt.axis([0, 6, 0, 20]) plt.plot(xarray,yarray,'ro') plt.xlabel('x-axis label') plt.ylabel('y-axis label') plt.show()
and the output changes to
# imports library for math # imports library for plots # array with x-coordinates # array with y-coordinates # set axes limits # plot with red circles # label for x-axis # label for y-axis # show the plot
20
15
y-axis label
10
5
00
1
2
3
4
5
6
x-axis label
Finally, in order to export the plot to a PDF file called, e.g., plot.pdf, we change the last command such that the code becomes
import numpy as np import matplotlib.pyplot as plt xarray=[1,2,3,4] yarray=[1,4,9,16] plt.axis([0, 6, 0, 20]) plt.plot(xarray,yarray,'ro') plt.xlabel('x-axis label') plt.ylabel('y-axis label') plt.savefig('plot.pdf') plt.close()
# imports library for math # imports library for plots # array with x-coordinates # array with y-coordinates # set axes limits # plot with red circles # label for x-axis # label for y-axis # save the graph as 'plot.pdf' # close the file
2
Changing the Plot Style
The plt.plot command takes a large number of options, which control how the data points are plotted. We already saw how to change from the default (a solid line) to a sequence of red circles. Other options we can play with include
plt.plot(xarray,yarray,'bo') # b: blue, o: circles
plt.plot(xarray,yarray,'gs') # g: green, s:square
plt.plot(xarray,yarray,'r-') # r: red, -:solid line
plt.plot(xarray,yarray,'--') # --: dashed line
plt.plot(xarray,yarray,':') # : dotted line
plt.plot(xarray,yarray,'go-') # g: green, o: circles, -:line
As the above examples show, the various options can be combined to change, e.g., the style (line vs. points), the color, or even to combine two styles, e.g., line and points.
The result of using this last command, i.e.,
import numpy as np import matplotlib.pyplot as plt xarray=[1,2,3,4] yarray=[1,4,9,16] plt.axis([0, 6, 0, 20]) plt.plot(xarray,yarray,'go-') plt.xlabel('x-axis label') plt.ylabel('y-axis label') plt.show()
looks like
# imports library for math # imports library for plots # array with x-coordinates # array with y-coordinates # set axes limits # plot with green cirles+line # label for x-axis # label for y-axis # show the plot
20
15
y-axis label
10
5
00
1
2
3
4
5
6
x-axis label
3
The following are some of the options available to control the style and color of the plot.
Option '-' '?' '-.' ':' 'o' 's' 'p' '*' '+' 'x' 'D'
Style solid line style dashed line style dash-dot line style dotted line style circle marker square marker pentagon marker star marker plus marker x marker diamond marker
Option b g r c m y k w
Color blue green red cyan magenta yellow black white
We can also add the option lw to the plt.plot command to change the thickness (lineweight) of the line and the option fontsize to the xlabel command to change the size of the font. For example, the output of the following code
import numpy as np
# imports library for math
import matplotlib.pyplot as plt
# imports library for plots
xarray=[1,2,3,4]
# array with x-coordinates
yarray=[1,4,9,16]
# array with y-coordinates
plt.axis([0, 6, 0, 20])
# set axes limits
plt.plot(xarray,yarray,'g-',lw=4) # plot with thick green line
plt.xlabel('x-axis label',fontsize=18)# large label for x-axis
plt.ylabel('y-axis label',fontsize=18)# large label for y-axis
plt.show()
becomes
20
15
y-axis label
10
5
00
1
2
3
4
5
6
x-axis label
4
Changing the Plot Type
In physics, we often plot log- and log-log plots of different physical quantities. It is easy to change the style of either the x- or the y-axes by giving the commands
plt.xscale('log') plt.yscale('log')
For example, the following lines of code (don't forget to change the lower limits from zero to something that has a real logarithm)
import numpy as np import matplotlib.pyplot as plt xarray=[1,2,3,4] yarray=[1,4,9,16] plt.xscale('log') plt.yscale('log') plt.axis([0.5, 20., 0.5, 20.]) plt.plot(xarray,yarray,'g-') plt.xlabel('x-axis label') plt.ylabel('y-axis label') plt.show()
generate the following output
# imports library for math # imports library for plots # array with x-coordinates # array with y-coordinates # logarithmic x-axis # logarithmic y-axis # set axes limits # plot with green line # label for x-axis # label for y-axis
101
y-axis label
100 100
101 x-axis label
5
Annotating the Plot
There are many ways to add annotations to a plot (other than the labels of the axes). The simplest is to use the command
plt.text(4.0, 10.0, 'this is a label')
in which the two numbers are the x- and y-coordinates of the label. The following example code
import numpy as np import matplotlib.pyplot as plt xarray=[1,2,3,4] yarray=[1,4,9,16] plt.axis([0, 6, 0, 20]) plt.plot(xarray,yarray,'ro') plt.text(4.0, 10.0, 'this is a label') plt.xlabel('x-axis label') plt.ylabel('y-axis label') plt.show()
# imports library for math # imports library for plots # array with x-coordinates # array with y-coordinates # set axes limits # plot with red circles # print a text label # label for x-axis # label for y-axis
generates the following output
20
15
10
this is a label
y-axis label
5
00
1
2
3
4
5
6
x-axis label
If there more than one sets of data on the plot, which can be put by adding more plt.plot commands, then one can label each set of data points using, e.g.,
plt.plot(xarray,yarray1,'ro',label="curve_1") plt.plot(xarray,yarray2,'ro',label="curve_2")
and then plot a legend using
plt.legend()
6
The following example code
import numpy as np
# imports library for math
import matplotlib.pyplot as plt
# imports library for plots
xarray=[1,2,3,4]
# array with x-coordinates
yarray1=[1,4,9,16]
# one array with y-coordinates
yarray2=[1,2,3,4]
# second array with y-coordinates
plt.axis([0, 6, 0, 20])
# set axes limits
plt.plot(xarray,yarray1,'g-',label="curve1") # plot 1st curve with green line
plt.plot(xarray,yarray2,'r-',label="curve2") # plot 2nd curve with red line
plt.xlabel('x-axis label')
# label for x-axis
plt.ylabel('y-axis label')
# label for y-axis
plt.legend()
plt.show()
generates the following output
20
curve1 curve2
15
y-axis label
10
5
00
1
2
3
4
5
6
x-axis label
7
Reading Data From a File
In most of our work, the data points we would like to plot will be the result of a complex numerical calculation and will be stored in an ASCII (i.e., readable with an editor) data file.
For the following example, we will assume that the data file contains only columns of numbers, i.e.,
1.0 1.0 1.0 2.0 4.0 2.0 3.0 9.0 3.0 4.0 16.0 4.0
and we want to use these data to plot two lines; both lines will have the data in the first column as the x-coordinates; the first and the second line will have the data in the second and third columns as the y-coordinates, respectively.
We will be using the command
alldata = np.genfromtxt("sample.dat") # read data in file 'sample.dat'
in order to read all data from the file into a large array which we call here alldata and then we will split this array into the various coordinate arrays we want, using the commands (remembering that Python like C counts the first array element as a zero)
xarray=alldata[:,0] yarray1=alldata[:,1] yarray2=alldata[:,2]
# first column of array alldata # second column of array alldata # third column of array alldata
Finally, we plot yarray1 versus xarray and yarray2 versus xarray. The following lines of code
import numpy as np
# imports library for math
import matplotlib.pyplot as plt
# imports library for plots
alldata = np.genfromtxt("sample.dat") # read data in file 'sample.dat'
xarray=alldata[:,0]
# first column of array alldata
yarray1=alldata[:,1]
# second column of array alldata
yarray2=alldata[:,2]
# third column of array alldata
plt.axis([0, 6., 0, 20.])
# set axes limits
plt.plot(xarray,yarray1,'g-')
# plot 2nd column with green line
plt.plot(xarray,yarray2,'r-')
# plot 3rd column with red line
plt.xlabel('x-axis label')
# label for x-axis
plt.ylabel('y-axis label')
# label for y-axis
plt.savefig('example6.pdf')
plt.close()
generate the following plot
8
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
Related searches
- making words with 7 letters
- making words with 6 letters
- making money with online marketing
- making tea with fresh herbs
- making money with stocks
- making money with amazon
- making words with certain letters
- making sentences with spelling words
- making necklaces with polished rocks
- making words with a calculator
- making sentences with pictures
- graphs with r