This article is an advanced version of Python's visualization tools. ~~ It has become long, so I decided to divide the advanced version into two. (Application 2 is still being written) ~~ The advanced version has been added to this article to make it one. If you are not familiar with Python plots, I wrote the basics last time, so please check here!
I am currently a graduate student with a second year master's degree. I am studying the atmosphere of Mars using numerical simulations. I used to analyze the results obtained by numerical simulation mainly using Python, so I tried to summarize all the functions used in the process. Please note that it is not exhaustive. .. .. I've just looked at the documentation and struggled to use it, so I'm hoping that if anyone is going to use Python's visualization tools, it'll help!
The following will be explained in another article (I will write this time) --Reading and writing csv files --Reading and exporting HDF5 files
The libraries used in this article are as follows. There is no problem if you copy and paste the following code on the code for the time being.
import matplotlib.pyplot as plt #Actually plot
import numpy as np #Data organization
from matplotlib.colors import LogNorm #color bar log
from matplotlib import animation as animation #Create gif file
What is a color plot in the first place? I think that there are many people, so 3D data is represented by a 2D color map as shown in the graph below. ~~ Because it's a big deal, I have an artistic face ... lol ~~
Structure & explanation of graph drawing using pcolor. (Please copy and use)
#Structure of pcolor
#1
#x axis,Prepare y-axis data and mesh
#Probably of the 3D data you want to plot(x,y)I think there are ingredients.
#ex) x = y = np.arange(-10, 10, 0.5)
X, Y = np.meshgrid(x, y) #This X,Y is len respectively(x)*len(y)It becomes a matrix of.
#2
#Create Z.
#If you have data you want to plot
#X made in step 1,Create a matrix Z that is the same size as Y.(Make a matrix by reading from csv)
#If not(This sample)
#Z=f(X,Y)Write the function as
#ex)
Z = np.exp(-X**2-Y**2)
#If there is a gap in the data and you want to mask the range(Uncomment if necessary)
#Z = np.ma.masked_where(np.isnan(Z), Z)#Mask none location
#3
#plot
fig, ax = plt.subplots(dpi=100) #dpi:resolution
#Create color map
c=ax.pcolor(X,Y,Z,cmap='Favorite color map', vmin=minimum value, vmax=Maximum value)
#c=ax.pcolor(X,Y,Z, norm=LogNorm(minimum value,Maximum value),cmap='Favorite color map') #log scale ver
#Add color bar
cax = fig.colorbar(c, ax=ax) #Add color bar
#Fill the masked area with diagonal lines(Uncomment if necessary)
#ax.patch.set(hatch='x', edgecolor='black')
I think it's hard to imagine, so for example, X in the sample code is X= It is a matrix of len (x) * len (y). Z is also a matrix of the same size, and the z value of the coordinates (x, y) is composed as an element.
The pcolor function
c=ax.pcolor(X,Y,Z,cmap='Favorite color map', vmin=minimum value, vmax=Maximum value)
-Cmap ='color map type' can be used to specify what color scheme to use. You can find a lot in this official document. -You can decide the range you want to color vmin and vmax. That is, the pixels are colored with z-values from vmin to vmax.
This is a sample code for a face written in pcolor.
#pcolor
from matplotlib.colors import LogNorm
import matplotlib.pyplot as plt #Actually plot
import numpy as np #Data organization
x = y = np.arange(-10, 10, 0.5)
X, Y = np.meshgrid(x, y)#Mesh and create a matrix
#A function that expresses the eyes, nose, and mouth of the face
Z = np.exp(-(X+5)**2 - (Y-3)**2)+np.exp(-(X-5)**2-(Y-3)**2)+np.exp(-(X)**2-(5*(Y+5))**2)+np.exp(-(10*X)**2-(5*Y)**2)
fig, ax = plt.subplots(dpi=200)
#Plot with pcolor
c=ax.pcolor(X,Y,Z, norm=LogNorm(1e-4, 1),cmap='Set3')
cax = fig.colorbar(c, ax=ax,shrink=0.9)
This is the graph.
When sharing the x-axis, it is OK if the structure is as follows. (For copy and paste)
fig, ax1 = plt.subplots(dpi=100)
##Write the ax1 plot here
#ax1.plot(...)
#ax1.set_??
ax2 = ax1.twinx()#Now you can share the x-axis!!!
##Write the ax2 plot here
#ax2.plot(...)
#ax2.set_??
Below is the sample code.
import matplotlib.pyplot as plt #Actually plot
import numpy as np #Data organization
def fun(x):
y = 2**x #Write your function here
return y
#prepare x,y data
X = np.linspace(1,10,num=100)
Y1 = fun(X)
Y2 = np.exp(X)
#Plot for left y-axis
fig, ax1 = plt.subplots(dpi=100)
ax1.plot(X,Y1,color='g',label=r'$y=2^x$', linestyle='-.',)
ax1.set_xlabel('xaxis')
ax1.set_ylabel("yaxis1")
ax1.set_ylim((0,100))
ax1.tick_params(axis='y')
ax1.legend(loc="upper left")
#Plot for right y-axis
ax2 = ax1.twinx()#Now you can share the x-axis!!!
ax2.plot(X,Y2,color='r', label=r'$y=e^x$')#plot
ax2.set_ylabel('yaxis2') # we already handled the x-label with ax1
ax2.set_yscale("log") #Right y-axis set to log scale
ax2.set_ylim((1,10000))
ax2.legend(loc="upper right")
I want to draw such a graph!
If you want to arrange two graphs vertically, you can use the following structure.
#(1)
#Arrange two subplots vertically
fig, axs = plt.subplots(2,1,sharex=True,dpi=100)
#Set 0 between the upper and lower graphs and stick them together
fig.subplots_adjust(hspace=0)
#(2)
#Draw the graph above
axs[0].plot(...)
#(3)
#Draw the graph below
axs[1].plot(...)
#Caution
#The number of graphs can be changed freely
#ex) 2,3 instead of 1,If set to 1, 3 will be arranged vertically,,,
#dpi:resolution
#sharex=If set to False, it becomes just a subplot.
Below is the sample code.
#Define your favorite function
import matplotlib.pyplot as plt #Actually plot
import numpy as np #Data organization
def fun(x):
y = 2**x #Write your function here
return y
#prepare x,y data
X = np.linspace(1,10,num=100)
Y1 = fun(X)#Y data you want to plot
Y2 = np.exp(X)
#create 2 subplots vertically adjusted
fig, axs = plt.subplots(2,1,sharex=True,dpi=100)
fig.subplots_adjust(hspace=0)
#Graph above
axs[0].plot(X,Y1,color='g',label=r'$y=2^x$', linestyle='-.',)
axs[0].set_ylabel("yaxis1")
axs[0].set_ylim((1,100))
axs[0].tick_params(axis='y')
axs[0].legend(loc="upper right")
#Graph below
axs[1].plot(X,Y2,color='r', label=r'$y=e^x$')
axs[1].set_xlabel('xaxis')
axs[1].set_ylabel('yaxis2') # we already handled the x-label with ax1
axs[1].set_yscale("log") #Right y-axis set to log scale
axs[1].legend(loc="upper right")
I created the simplest one.
Structure & explanation of gif file creation. (For copy and paste)
import matplotlib.pyplot as plt #Actually plot
import numpy as np #Data organization
from matplotlib import animation as animation #Create gif file
#You probably have the data you want to plot that is changing over time
#X it,Y(t)When you do
#First, create a function to plot every frame
#This variable i'interval'Will increase little by little
def iplot(i, args,,,):
plt.clf()#Erase the graph in the previous frame(Delete if you want to keep)
#Draw a frame-by-frame plot here
#As i increases, the data to plot will change accordingly.
#ex) plt.plot(X,Y(i))
#Make a figure as usual
fig = plt.figure(dpi=100) #dpi:resolution
#gif file creation
#meaning:Increase i by interval for each frame by the number of frames in fig, and plot with the iplot function.
#fargs=(,,)Specifies an argument other than i of the iplot function
#i increases every interval
#You can specify how many frames to make with frames
ani = animation.FuncAnimation(fig, iplot,fargs=(args), interval = 1, frames = 50)
#save
#Specify filename
#write r, which method to use? There is no problem with imagegick for the time being
#Specify how many frames per second with fps
ani.save('filename.gif', writer='imagemagick', fps=20)
The sample code is below.
import matplotlib.pyplot as plt #Actually plot
import numpy as np #Data organization
from matplotlib import animation as animation #Create gif file
#Prepare X and Y to plot.
X = np.linspace(1,10,num=100)
Y = 2*X #y=2x
#Create a function to plot every frame
#This variable i(In the animation function below)'interval'Will increase little by little
def iplot(i,X,Y):
plt.clf()#Without this, the graph of the previous frame remains
plt.plot(X+i,Y)#This time y=Translate 2x in the x direction
plt.xlim((0,60))#Define the range
plt.xlabel('xaxis')
plt.ylabel('yaxis')
plt.text(2,18,"y=2(x-"+str(i)+")")
fig = plt.figure(dpi=100)
#Create gif file
ani = animation.FuncAnimation(fig, iplot,fargs=(X,Y), interval = 1, frames = 50)
#save
ani.save('filename.gif', writer='imagemagick', fps=20)
Since the advanced version has become long, I will write the following article at a later date. Contents --Reading and writing csv files --Reading and exporting HDF5 files
is. Then!
Recommended Posts