Plotting cheatsheet - Basic Python #1
There are two things you should remember before you start plotting in Python:
1. import matplotlib.pyplot as plt --> for plotting
2. import numpy as np --> module (tool) for array and mathematical manipulation
So, let’s say that you want to plot your data (can be points, lines, or even point on lines). Then, this is what you need:
- to plot points (scatter)
 make arrays for x and y value, then type this: pl.plot(x,y,’ro’)
or, simply put the value of x and y in the same line, e.g.: pl.plot([x1,x2,x3],[y1,y2,y3],’ro’)
the ‘ro’ in your code means that you want to make a red dot as your point. you can change it to ‘bo’ means you want to make a blue dot, or ‘g*’ means you want to plot a green star as your point.
- to plot line
make arrays for x and y value (you can change the y value with equation), then type: pl.plot(x,y)
you can also change the style of the line with added ‘--’ (e.g.: pl.plot(x,y,’r--’) if you want to have red dashed line). it works the same as point style to change the style for your lines.
- to plot multiple lines and points
just clearly have different labels for each variables (i.e. mentioned x1, y1, x2, y2, x3, etc), then plot each line and points using the same command as above. pl.plot([x1,x2],[y1,y2],’bo’) --> to plot point 1 (x1,y1) and 2 (x2,y2) pl.plot(x3,y3) --> to plot line of x3,y3 (after you define the x3 and y3)
- to plot points/line from a document
It’s a bit tricky to plot from a certain .txt file. You first need to know the format/pattern of the data. Generally, of you have a .txt data containing two components, then you can plot it as x and y in a graph. But how?
first, read your data by defining it to a certain variable (let’s say we use A to read file1 and B to read file2), by typing this: A = np.loadtxt(’file1.txt’) B = np.loadtxt(’file2.txt’)
then, plot those data by stating this: pl.plot(np.linspace(a1,a2,a3),A) --> change the a1 with a certain number you want the axes to be start, and a2 is the end of axes. the length of your line will depends on a1 and a2, the more the difference, the longer the line. then a3 is the amount of data. A is the name of your data variable pl.plot(np.linspace(b1,b2,b3),B) --> the same as a1,a2,a3, but this works for B data. But, remember that the a3 and b3 should be the same!
Alright, now you can create graphs in Python! For more styling graphs, learn it from the linestyle section in here:Â https://matplotlib.org/api/lines_api.html














