I wanted to visualize 3D particle simulation with the Python visualization library Matplotlib.

When I tried to use 3D Scatter plot with matplotlib, the version on the server was old, Hajimaruyo (slow voice)

at first

I wanted to make the visualization of particle numerical calculations cool in 3D. In particular 00000.png 00010.png 00020.png 00030.png 00040.png ↑ I wanted to make something like this. Even if I was a first-class gnuplot teacher, I wanted to do it with gnuplot, but On the other hand, I wanted to use a different plotter once in a while, so I tried my best to make it with matplotlib.

matplotlib

matplotlib is a visualization library that runs on Python. Click here for script.

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

box_size = 4.0
R = 6400.0e+3

print mpl.__version__
fig = plt.figure()
#if version > 1.0.0
#ax = plt.add_subplot(111, projection='3d')

start = 0
stop = 1
step = 1

Nnode = 4
for step in range(start, stop, step):
	print step
	tag = []
	x = []
	y = []
	z = []
	for n in range(Nnode):
		data = np.loadtxt("./result/%05d_%05d_%05d.dat" % (step, Nnode, n), skiprows=2, delimiter="\t");
		tag.extend(data[:,1])
		x.extend(data[:,3])
		y.extend(data[:,4])
		z.extend(data[:,5])

	x_tag = [[], [], [], []]
	y_tag = [[], [], [], []]
	z_tag = [[], [], [], []]
	size_tag = [[], [], [], []]

	for i in range(len(x)):
		x[i] = x[i]/R
		y[i] = y[i]/R
		z[i] = z[i]/R
		x_tag[int(tag[i])].append(x[i])
		y_tag[int(tag[i])].append(y[i])
		z_tag[int(tag[i])].append(z[i])
		size_tag[int(tag[i])].append(1.0)


	clr = ["orange", "gray", "red", "black"]

	ax = Axes3D(fig)
	for tag in range(4):
		ax.scatter(x_tag[tag], y_tag[tag], z_tag[tag], s=size_tag[tag], c=clr[tag], edgecolor=clr[tag], alpha=0.1)

	ax.set_aspect('equal')
	ax.set_xlim3d(-box_size, box_size)
	ax.set_ylim3d(-box_size, box_size)
	ax.set_zlim3d(-box_size, box_size)
	ax.view_init(9.0, 45.0)
	#plt.show()
	plt.savefig("./img/%05d.png " % step)

Commentary

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

First, import.

box_size = 4.0
R = 6400.0e+3

Declaration of a constant.

print mpl.__version__
fig = plt.figure()
#if version > 1.0.0
#ax = plt.add_subplot(111, projection='3d')

I output the version of matplotlib. Since matplotlib uses different 3D plot methods depending on the version ...

start = 0
stop = 1
step = 1

Create a graph by incrementing step by step from start to stop.

	tag = []
	x = []
	y = []
	z = []

Array initialization.

	for n in range(Nnode):
		data = np.loadtxt("./result/%05d_%05d_%05d.dat" % (step, Nnode, n), skiprows=2, delimiter="\t");
		tag.extend(data[:,1])
		x.extend(data[:,3])
		y.extend(data[:,4])
		z.extend(data[:,5])

Since the calculation results are distributed in Nnode files, load them into data one by one with loadtxt. Use the extend method to plunge into the array defined earlier. In this case, the first column is the tag, the third column is the x coordinate, the fourth column is the y coordinate, and the fifth column is the z coordinate.

	x_tag = [[], [], [], []]
	y_tag = [[], [], [], []]
	z_tag = [[], [], [], []]
	size_tag = [[], [], [], []]

Create a two-dimensional array to plot by changing the color for each tag.

	for i in range(len(x)):
		x[i] = x[i]/R
		y[i] = y[i]/R
		z[i] = z[i]/R
		x_tag[int(tag[i])].append(x[i])
		y_tag[int(tag[i])].append(y[i])
		z_tag[int(tag[i])].append(z[i])
		size_tag[int(tag[i])].append(1.0)

	clr = ["orange", "gray", "red", "black"]

After dividing the coordinates by the standardized constant, the data is plunged into the corresponding array of tags. After that, define the color corresponding to the tag.

	ax = Axes3D(fig)
	for tag in range(4):
		ax.scatter(x_tag[tag], y_tag[tag], z_tag[tag], s=size_tag[tag], c=clr[tag], edgecolor=clr[tag], alpha=0.1)

Create an Axes3D class and flow data into scatter. This needs to be done for each tag. This time size_tag is fixed. Set the edge color to clr [tag]. This makes it possible to draw with borderless particles. Transmittance alpha is consistently 0.1.

	ax.set_aspect('equal')
	ax.set_xlim3d(-box_size, box_size)
	ax.set_ylim3d(-box_size, box_size)
	ax.set_zlim3d(-box_size, box_size)
	ax.view_init(9.0, 45.0)

This time, the aspect ratios are all equal. Also, set the range for each axis. Set the camera angle with view_init.

	#plt.show()
	plt.savefig("./img/%05d.png " % step)

Output. You can show () normally, but this time I will make it png with savefig and later make it an anime gif.

Right? Isn't it easy?

Recommended Posts

I wanted to visualize 3D particle simulation with the Python visualization library Matplotlib.
I wanted to solve the ABC164 A ~ D problem with Python
I wanted to use the Python library from MATLAB
[Python] I want to make a 3D scatter plot of the epicenter with Cartopy + Matplotlib!
I wanted to solve ABC160 with Python
I wanted to solve ABC172 with Python
[Python] I tried to visualize the prize money of "ONE PIECE" over 100 million characters with matplotlib.
I tried to visualize the model with the low-code machine learning library "PyCaret"
I wanted to solve NOMURA Contest 2020 with Python
I wanted to play with the Bezier curve
I wanted to install Python 3.4.3 with Homebrew + pyenv
I tried to easily visualize the tweets of JAWS DAYS 2017 with Python + ELK
I tried to touch the CSV file with Python
I tried to solve the soma cube with python
Try to operate DB with Python and visualize with d3
I want to inherit to the back with python dataclass
I tried to solve the problem with Python Vol.1
[Python] How to create a 2D histogram with Matplotlib
[Introduction to Python] Basic usage of the library matplotlib
I tried to find the entropy of the image with python
I tried to simulate how the infection spreads with Python
I tried using the Python library from Ruby with PyCall
[python] How to use the library Matplotlib for drawing graphs
What I did to welcome the Python2 EOL with confidence
[Python] I want to use the -h option with argparse
[Python] I tried to visualize tweets about Corona with WordCloud
[Python] I tried to visualize the follow relationship of Twitter
I captured the Touhou Project with Deep Learning ... I wanted to.
I tried to divide the file into folders with Python
[Python] How to import the library
I liked the tweet with python. ..
I want to debug with Python
I made a library to easily read config files with Python
I tried to solve the ant book beginner's edition with python
I want to know the weather with LINE bot feat.Heroku + Python
I want to output the beginning of the next month with Python
I tried to fix "I tried stochastic simulation of bingo game with Python"
[Introduction to Matplotlib] Axes 3D animation: I played with 3D Lissajous figures ♬
I tried to improve the efficiency of daily work with Python
[Python] Visualize Arashi's lyrics with WordCloud and try to understand what I wanted to convey to fans in the 20th year of formation.
What skills do I need to program with the FBX SDK Python?
[Python] Set the graph range with matplotlib
I tried to visualize AutoEncoder with TensorFlow
Add 95% confidence intervals on both sides to the diagram with Python / Matplotlib
I tried to get the authentication code of Qiita API with Python.
I want to analyze logs with Python
I want to play with aws with python
It's more recent, but I wanted to do BMI calculation with python.
I wanted to solve ABC159 in Python
I tried with the top 100 PyPI packages> I tried to graph the packages installed on Python
I installed the library with Visual Studio Code, but Unable to import
I tried to streamline the standard role of new employees with Python
I tried to visualize the text of the novel "Weathering with You" with WordCloud
I tried to get the movie information of TMDb API with Python
Match the colorbar to the figure with matplotlib
I really wanted to copy with selenium
The road to compiling to Python 3 with Thrift
I tried to extract named entities with the natural language processing library GiNZA
I tried using the Python library "pykakasi" that can convert kanji to romaji.
[Scientific / technical calculation by Python] Plot, visualize, matplotlib 2D data with error bars
I tried to automatically send the literature of the new coronavirus to LINE with Python