Making Plot in Python
Plot a term used to describe a graphical representation of data could be done in a lot of ways. There’s a lot of applications that could be used to create a plot, such as Microsoft Excel, MATLAB, etc. Beside using an established apps, you could also made plot using computing languages of your choice. Today i will tell you how to graphically represent your data using python, the reference used would be from Essential Python for the Physicist by Giovanni Moruzzi.
Pyplot
In python there’s a lot of library you could use, for plotting we will use matplotlib and its plotting module pyplot. Pyplot ussually used to make Matplotlib function a lot like MATLAB. Using pyplot we could customize our graph to satisfy our needs, whether plot lines, adding label, and many more could be done with this.
Plotting List of Number
To plot a list of number, first you need to get a list of number, for this example we’ll use [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]. The code that we’ll use are shown below:
#!/ usr/ bin/env python3
import matplotlib.pyplot as plt
#
plt.plot ([1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0])
plt.show( )At line 2 we see that pyplot were imported under the names plt, and to use all command associated pyplot we now need to use plt instead, as seen in line 4.
As you see we haven’t specified whether the data is y or x, but the machine spirit will assume that the data is y. We, the children of omnissiah could of course specify which data is in what axis.
4 plt.plot ([3.0,4.0,5.0,6.0,7.0,8.0],[8.0,16.0,32.0,64.0,128.0,256.0], ’ro ’)
We modified the 4th line into something like the above. The first set of data will be x and the second will be y, the ro in the end means that we don’t want the data to be served in a wacky line, we want it in red (r) circle (o)™.
Let’s make our life a bit harder, we love pain and suffering after all. Lets add complexity to our plot by plotting three data, and two of them are a function. We will need numpy for this one.
#!/usr/ bin/env python3
import matplotlib. pyplot as plt
import numpy as np
#
x=np.arange (0.0 ,2.0 ,0.05)
plt.plot (x,x,x,np. sqrt (x) , 'ro ' ,x,x∗x, 'g^ ' )
plt.show( )note: in the book Moruzzi use x**2 to represent x², but if you just copy paste directly from the e-book it‘s fine, but i rather retype it, it is, in my opinion help me in learning the code.
Plotting Function
We’ve kinda do that already, but let’s try again, now using even more function than the last example. First a basic sin graph.
#!/usr/ bin/env python3
import matplotlib. pyplot as plt
import numpy as np
#
x=np.arange (0,6.4 ,0.1)
y=np.sin(x)
plt.plot (x, y)
plt.show( )Line 5 is a command that will create an array of number from 0 to 6.4 with 0.1 step. It is important to also remember that every trigonometric function use radian instead of degree here. We could improve this code by adding detail such as label using plt.ylabel ( r ’$\ sin (x)$’ , fontsize=24), grid using plt.grid (True), and many more, I’m not going to show you how it’s done, do it yourself.
Multiple Plot
Let say you have two function and you want to have its plot placed side by side at the same time. That could be done using plt.subplot(1,2,1)where (1,2,1) represents row, column, and the last 1 means that the nex plt.plot will be in the first column, and if you put 2 intead, the next plt.plot will be in the second column.
Simple example:
#!/ usr/ bin/env python3
import matplotlib.pyplot as plt
import numpy as np
#
x = np.arange (0,6.4 ,0.1)
y= np.sin(x)
plt.subplot(1,2,1)
plt.plot(x,y, 'r-')
plt.grid(True)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.xlabel(r'$x({\rm rad})$', fontsize=14)
plt.ylabel(r'$\ sin (x)$', fontsize=14)
plt.tight_layout( )
#
plt.subplot (1,2,2)
plt.plot(x,np.exp(x))
plt.grid(True)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.xlabel('X', fontsize=14)
plt.ylabel(r'$e^x$', fontsize=14)
plt.tight_layout( )
#
plt.savefig ('MultiPlot0.eps', format='eps', dpi=1000)
plt.show( )result:
Logarithmic Axis Scales
We could set the scale of our plot using command plt.xscale(`log`)or plt.xscale(`symlog`)if the x value is zero or negative.
example:
#!/ usr/ bin/env python3
import matplotlib.pyplot as plt
import numpy as np
#
x = np.arange (0,100,0.1)
y= np.sqrt(x)
plt.subplot(2,2,1)
plt.plot(x,y, 'r-')
plt.grid(True)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.xlabel(r'$x$', fontsize=14)
plt.ylabel(r'$sqrt(x)$', fontsize=14)
plt.tight_layout( )
#
plt.subplot (2,2,2)
plt.plot(x,y)
plt.grid(True)
plt.xscale('log')
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.xlabel(r'$\ log$', fontsize=14)
plt.ylabel(r'$sqrt(x)$', fontsize=14)
plt.xlim(x.min(),x.max())
plt.tight_layout( )
#
plt.subplot (2,2,3)
plt.plot(x,y)
plt.grid(True)
plt.xscale('symlog')
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.xlabel(r'$\ symlog$', fontsize=14)
plt.ylabel(r'$sqrt(x)$', fontsize=14)
plt.xlim(x.min(),x.max())
plt.tight_layout( )
#
plt.savefig ('MultiPlot0.eps', format='eps', dpi=1000)
plt.show( )We could clearly see the difference between the use of log and symlog at figure 5. When using log scale, the value at x=0 aren’t 0 this was not the same as the value found at linear scale, but when using symlog, the value is the same as the one found at linear scale.
Plotting Field Lines
Ever wonder how to plot an electromagnetic field using python? or perhaps just some basic vector field? well its complicated process but we’ll see. The code below are code to draw a Field, a Field is an area where a certain things exist, like mentioned before electromagnetics, velocity, etc.. The result of this code are rather unlclear, simplistic and lacking, but sadly this is all i got.
#!/usr/bin/env python3
#
import matplotlib.pyplot as plt
import numpy as np
#
yplus = 1.0
yminus = -1.0
xplus = xminus = 0.0
rad = 0.1
lim = 30
nLin = 60
plt.axis('off')
#
i = 0
d = 0.05
xlist = []
ylist = []
while i < nLin:
alpha0 = i * 2 * np.pi / float(nLin) , there should be an indent here
x = xplus + rad * np.cos(alpha0)
y = yplus + rad * np.sin(alpha0)
xlist.append(x)
ylist.append(y)
i += 1
while True: , there should be an indent here
alpha = np.arctan2((y - yplus), (x - xplus))
beta = np.arctan2((y - yminus), (x - xminus))
Eplus = 1.0 / ((x - xplus) ** 2 + (y - yplus) ** 2)
Eminus = -1.0 / ((x - xminus) ** 2 + (y - yminus) ** 2)
Ex = Eplus * np.cos(alpha) + Eminus * np.cos(beta)
Ey = Eplus * np.sin(alpha) + Eminus * np.sin(beta)
gamma = np.arctan2(Ey, Ex)
x = x + d * np.cos(gamma)
y = y + d * np.sin(gamma)
if x > lim or x < -lim or y > lim or y < 0:
break , there should be an indent here
xlist.append(x)
ylist.append(y)
plt.plot(xlist, ylist, 'k-', linewidth=0.5) , aligned with the While True above
ylist = -np.array(ylist)
plt.plot(xlist, ylist, 'k-', linewidth=0.5)
plt.savefig('DipoleField.pdf', format='pdf')
plt.show()Animating Your Plot
Using matplotlib there’s two easy way to make animation, using Func-Animation or ArtistAnimation. FuncAnimation as the name suggest will use a function and repeat those function to make animation, so it close to what a simmulation is. Today we’ll learn about FuncAnimation.
Get Rizki A. F.’s stories in your inbox
Join Medium for free to get updates from this writer.
You know the drill
#!/usr/bin/env python3
#
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as anim
#
fig,ax=plt.subplots( figsize =(10,6))
ax.set(ylim=(-1,1))
#
def func(x):
return np.sin(8*x)*np.exp(-0.1*x)
#
x= np.arange(0,10,0.01)
line1,=ax.plot (x, func(x))
#
def animate(i):
xx=x+i/100
line1.set_xdata(xx)
line1.set_ydata(func(xx))
ax.set(xlim=(xx[0] ,xx[999]))
return line1,
#
ani=anim.FuncAnimation(fig, animate, interval=20)
plt.show( )The code above animate function sin(8x)*e^(-1x).
The result would be:
Different function will require different code, if the function are a function of two variable you’ll have to modify the funct(x) to func(x, t) if your other variable are t. If you have such equation, let say a wave packet equation, you can enter it and set all the variable such as ‘k’ etc outside or inside the defined function. Tho if you have some difficulties, you could always ask ChatGPT and enter your equation, it’s lazy and not recomended, but who am i to stop you. I’ve asked said AI to make me some animation and the result were pretty good.
Conclussion
Making plot aren’t just fun but also useful to represent your data and make it more interesting while making it easy to understand. I made this article in hope that reader will not just copy paste the code but also playing around with all the parameter in the code. My lack of explanation is not a mistake, but rather an attempt for you to learn and explore more, the codes are in english after all, it won’t be that hard. Happy learning.
In Plain English 🚀
Thank you for being a part of the In Plain English community! Before you go:
- Be sure to clap and follow the writer ️👏️️
- Follow us: X | LinkedIn | YouTube | Discord | Newsletter
- Visit our other platforms: Stackademic | CoFeed | Venture
- More content at PlainEnglish.io










