0% found this document useful (0 votes)
53 views

KOS1110 Python - Introduction To Plotting: 1. Getting Started - What Do You Need?

This document provides an introduction to plotting in Python. It discusses the modules needed for plotting (NumPy and Matplotlib), and covers the basics of line plots, scatter plots, customizing plot styles, plotting multiple graphs on the same axes, adding legends, reading and writing data files, and more. Examples are provided using short code snippets to demonstrate each concept.

Uploaded by

Syuhada Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

KOS1110 Python - Introduction To Plotting: 1. Getting Started - What Do You Need?

This document provides an introduction to plotting in Python. It discusses the modules needed for plotting (NumPy and Matplotlib), and covers the basics of line plots, scatter plots, customizing plot styles, plotting multiple graphs on the same axes, adding legends, reading and writing data files, and more. Examples are provided using short code snippets to demonstrate each concept.

Uploaded by

Syuhada Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

KOS1110

Python - Introduction to plotting


Welcome to a very short introduction on getting started with plotting in Python!

1. Getting started – what do you need?

For this tutorial, you’ll be using two python modules called Numpy and Matplotlib.

 Numpy – this is the module which does most array and mathematical
manipulation
 Matplotlib – this is the module you’ll be using for plotting
 Pylab – is a module that gets installed alongside matplotlib
We will use Googlecolab to do the plotting. Click Here.

2. Basic plots

Two basic plot types which you will find very often are (x,y) line and scatter plots.
Some codes for making these two types of plots is included in this section.

2.1 Line plots

import numpy as np
import pylab as pl

# Make an array of x values


x = [1, 2, 3, 4, 5]

# Make an array of y values for each x value


y = [1, 4, 9, 16, 25]

# use pylab to plot x and y


pl.plot(x, y)

# show the plot on the screen as shown in Fig. 1


pl.show()

OUTPUT:

1
Fig. 1 – Line plot

2.2 Scatter plots

Alternatively, you may want to plot quantities which have an x and y position. For example,
plotting the location of stars or galaxies in a field for example such as the plot in Fig. 2. Try
running the script below to do this:

# scatterplot.py
import numpy as np
import pylab as pl

# Make an array of x values


x = [1, 2, 3, 4, 5]

# Make an array of y values for each x value


y = [1, 4, 9, 16, 25]

# use pylab to plot x and y as red circles


pl.plot(x, y, ’ro’)

# show the plot on the screen


pl.show()

OUTPUT:

Fig. 2 – Scatter plot

2
2.3 Making things look pretty

2.3.1 Changing the line color


It is very useful to be able to plot more than one set of data on the same axes and to be able to
differentiate between them by using different line and marker styles and colours. You can
specify the colour by inserting a 3rd parameter into the plot() command. For example, in
lineplot.py, try changing the line

pl.plot(x, y)
to
pl.plot(x, y, ‘r’)

This should give you the same line as before, but it should now be red. The other colours you
can easily use are:

2.3.2 Changing the line style


You can also change the style of the line e.g. to be dotted, dashed, etc. Try:

plot(x,y, ‘—‘)

This should give you a dashed line now. Other linestyles you can use can be found on the
Matplotlib webpage

2.3.3 Changing the marker style


Lastly, you can also vary the marker style you use. Try:
plot(x,y, ‘b*’)

This should give you blue star-shaped markers. The table below gives some more options for
setting marker types:

3
2.3.4 Plot the axis titles and limits
It is very important to always label the axes of plots to tell the viewer what they are looking at.
You can do this in python by using the commands:
pl.xlabel('put text here')
pl.ylabel('put text here')

You can make a title for your plot by:


pl.title(' Put plot title here')

You can change the x and y ranges displayed on your plot by:
pl.xlim(x_low, x_high)
pl.ylim(y_low, y_high)

Have a look at the modified macro lineplotAxis.py below:

#lineplotAxis.py
import numpy as np
import pylab as pl
# Make an array of x values
x = [1, 2, 3, 4, 5]

# Make an array of y values for each x value


y = [1, 4, 9, 16, 25]

# use pylab to plot x and y


pl.plot(x, y)

# give plot a title


pl.title(’Plot of y vs. x’)

# make axis labels


pl.xlabel(’x axis’)
pl.ylabel(’y axis’)

# set axis limits


pl.xlim(0.0, 7.0)
pl.ylim(0.0, 30.)

# show the plot on the screen


pl.show()

OUTPUT:

4
Fig.3 made with lineplotAxis.py

2.3.5 Plotting more than one plot at the same set of axes
It is very easy to plot more than one plot on the same axes. You just need to define the x and y
arrays for each of your plots and then:
plot(x1, y1,'r')
plot(x2, y2,'g')

2.3.6 Figure legends


It’s very useful to add legends to plots to differentiate between the different lines or quantities
being plotted. In python you can make a legend as follows:
pl.legend()

Have a look at Fig. 5 which is made using the macro below:


# lineplotFigLegend.py
import numpy as np
import pylab as pl

# Make x, y arrays for each graph


x1 = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
x2 = [1, 2, 4, 6, 8]
y2 = [2, 4, 8, 12, 16]

# use pylab to plot x and y : Give your plots


names
plot1 = pl.plot(x1, y1,'r', label='red line')
plot2 = pl.plot(x2, y2,'go',label='green circle')

# give plot a title


pl.title('Plot of y vs. x')

5
# make axis labels
pl.xlabel('x axis')
pl.ylabel('y axis')

# set axis limits


pl.xlim(0.0, 9.0)
pl.ylim(0.0, 30.)

# make legend
pl.legend()

# show the plot on the screen


pl.show()

Fig.4 made with lineplotFigLegend.py

3. Plotting data contained in files

Often you will have data in ascii (text) format which you will need to plot in some way. In this
section we will briefly discuss how to open, read from, and write to, files.

3.1 Reading data from files

There are many ways to read data from a file in python. Here I am going to illustrate one
simple method, but you should read the Python, Numpy and Matplotlib manuals to find out
about the other ways which might sometimes apply better to you particular situation. You can
use Numpy to read in numerical values from a text file. For example, let’s take the text file
called fakedata.txt which contains the following data (2 columns of numbers):

# data.txt
0 0
1 1
2 4
3 9
4 16
5 25
6 36

6
7 49
8 64
9 81

We can read this into a numpy 2D array and plot the second column against the first using the
macro readFileAndPlot.py and shown in Fig. 12:

#readFileAndPlot.py
import numpy as np
import pylab as pl

#Use numpy to load the data contained in’fakedata.txt’

data = np.loadtxt('fakedata.txt')
# plot the first column as x, and second column as y
pl.plot(data[:,0], data[:,1], 'ro')
pl.xlabel('x')
pl.ylabel('y')
pl.xlim(0.0, 10.)
pl.show()

OUTPUT:

Fig. 5 – Plotting data from a file

3.2 Writing data to a text file

There are also various ways to write text to a text file. Here we show you one possible way to
do it. You first have to open a file to write to, then write what you want to the file, and then,
do not forget to close the file! See the code below, writeToFile.py to see how to do this:

# writeToFile.py
import numpy as np

# Let’s make 2 arrays (x, y) which we will write to a file


# x is an array containing numbers 0 to 10, with intervals of 1
x = np.arange(0.0, 10., 1.)

# y is an array containing the values in x, squared


y = x*x

print('x=', x )
print('y=', y )

7
# Now open a file to write the data to
# 'w' means open for ’writing’
file = open('testdata.txt', 'w')

# loop over each line you want to write to file


for i in range(len(x)):
txt = str(x[i]) + '\t' + str(y[i]) + '\n'

file.write(txt) # write the txt to the file

# Close your file


file.close()

You might also like