I tried to summarize all the Python visualization tools used in research by active science graduate students [Application]

Continuing from the previous session

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!

Introduction

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!

What you can do with this article

・ Color plot (pcolor)
· Share the x-axis and set the y-axis to right and left
・ The x-axis is the same and the graphs are arranged vertically.
・ Animation (gif file creation)

The following will be explained in another article (I will write this time) --Reading and writing csv files --Reading and exporting HDF5 files

Library to use

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

How to use color plot (pcolor)

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 ~~ Screen Shot 2020-03-20 at 13.26.09.png

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= Screen Shot 2020-03-20 at 14.35.07.png 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)

Share the x-axis and set the y-axis to right and left

This is the graph. Screen Shot 2020-03-18 at 23.24.28.png

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")

The x-axis is the same and the graphs are arranged vertically

I want to draw such a graph! Screen Shot 2020-03-18 at 23.49.39.png

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")

Animation (gif file creation)

I created the simplest one. filename.gif

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)

Finally

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

I tried to summarize all the Python visualization tools used in research by active science graduate students [Application]
I tried to summarize the code often used in Pandas
I tried to summarize the commands often used in business
I tried to summarize the commands used by beginner engineers today
I tried to summarize the contents of each package saved by Python pip in one line
[Python] I tried to summarize the set type (set) in an easy-to-understand manner.
I tried to summarize the Linux commands used by beginner engineers today-Part 1-
I tried to graph the packages installed in Python
I tried to summarize how to use pandas in python
I tried to summarize the string operations of Python
I tried to implement the mail sending function in Python
I tried to summarize what python strong people are doing in the competition professional neighborhood
I tried to summarize the frequently used implementation method of pytest-mock
I tried to summarize Python exception handling
I tried to implement PLSA in Python
I tried to summarize the umask command
I tried to implement permutation in Python
I tried to summarize the general flow up to service creation by self-education.
I tried to summarize the methods that are often used when implementing basic algo in Quantx Factory
I tried to implement PLSA in Python 2
Python3 standard input I tried to summarize
I tried to implement Bayesian linear regression by Gibbs sampling in python
I tried to open the latest data of the Excel file managed by date in the folder with Python
I tried to summarize the graphical modeling.
I tried to implement ADALINE in Python
I tried to implement PPO in Python
I tried to verify and analyze the acceleration of Python by Cython
I tried to analyze the New Year's card by myself using python
I tried to organize the evaluation indexes used in machine learning (regression model)
How to read all the classes contained in * .py in the directory specified by Python
I tried to summarize the operations that are likely to be used with numpy-stl
I tried to predict the change in snowfall for 2 years by machine learning
I tried to implement sentence classification & Attention visualization by Japanese BERT in PyTorch
[Introduction to Docker] I tried to summarize various Docker knowledge obtained by studying (Windows / Python)
I tried simulating the "birthday paradox" in Python
I tried the least squares method in Python
I tried to implement TOPIC MODEL in Python
I tried using the Datetime module by Python
I tried to implement selection sort in python
LeetCode I tried to summarize the simple ones
I want to display the progress in Python!
[First data science ⑤] I tried to help my friend find the first property by data analysis.
I tried to summarize the new coronavirus infected people in Ichikawa City, Chiba Prefecture
[First data science ⑥] I tried to visualize the market price of restaurants in Tokyo
I used Python to find out about the role choices of the 51 "Yachts" in the world.
[Python] I tried to summarize the array, dictionary generation method, loop method, list comprehension notation
I tried to summarize how to use matplotlib of python
I tried to summarize the basic form of GPLVM
I tried to touch the CSV file with Python
I tried to implement a pseudo pachislot in Python
I tried to implement Dragon Quest poker in Python
I tried to implement GA (genetic algorithm) in Python
[Python] I tried to graph the top 10 eyeshadow rankings
I want to write in Python! (3) Utilize the mock
I tried to solve the problem with Python Vol.1
I want to use the R dataset in python
Python OpenCV tried to display the image in text.
A super introduction to Django by Python beginners! Part 6 I tried to implement the login function
I tried to create a Python script to get the value of a cell in Microsoft Excel
I also tried to imitate the function monad and State monad with a generator in Python
I tried to summarize the languages that beginners should learn from now on by purpose