【Blender】How to visualize data with Blender and Python

Blender is a powerful open-source animation and 3D program. Blender’s user interface is written in Python, which is capable of being applied to data visualization.

This article discusses how to import data into STYLY to develop a creative platform. The article also explains the uploading technique of objects and 3D models into STYLY.

What is Python?

Python is a general-purpose and versatile programming language used by many companies and organizations to generate visualizations, manipulate data, or create a website.

Python is a popular language for data science and can be used for other numerical computations owing to its language specification.

Python is built into Blender, and many of Blender’s processes are managed by Python. Moreover, most of the add-ons are written in Python.

Therefore, Blender has a Python runtime built-in environment, allowing it to run Python in an almost complete form.

For example, this simple program can be used to create particle life and other applications in Blender.

Visualize data

This article demonstrates how to visualize data using Python.

Simply put, data visualization is the process of replacing numerical data with something that is more easily viewable.

Graphs in spreadsheet software are examples of data visualization.

Graphing is the process of converting numerical information into visual information.

Blender uses Python to convert numerical data into easy-to-visualize information.

This process involves the following characteristics:

  • Numerical data are represented in a visually rich manner.
  • Animation is used to display visible information through changes in numerical values as movement.

This allows to run the following applications:

  • Animating numerical data shows the movement of numerical values from multiple angles.
  • It is capable of creating infographics, etc.

Visualization of Seismograph Data

Data Acquisition

Earthquakes occur frequently in Japan, and the Japan Meteorological Agency constantly monitors the imminent occurrence of the earthquakes observed by releasing information to the public as strong-motion observation data.

The STYLY program below releases assets and other useful information for disaster prevention, planning, and other purposes:

Python assists in visualizing the shaking of an earthquake, which is a useful tool for disaster prevention.

Animations with these data offer the following information:

  • By visualizing the earthquake, we can visualize in advance what kind of shaking to occur and prepare for it.
  • We can create virtual reality (VR) of the earthquake experience.

Let us provide information on the data to be used.

First, select the Earthquake from the Strong-Motion Observation Data site

強震データ選択

Strong-motion data selection

At the time of writing this article, the latest information was on “February 13, 2021, 23:07 off the coast of Fukushima Prefecture.” Thus, we use this information.

Next, the location is displayed; thus, select the data you wish to use.

地震データのリスト

List of seismic data

Click on the “Waveform” under “Waveform Plot” in 1, and “Waveform” in 2 displays a graphical representation of the Waveform below. Click on the “Download” button, and “Get Data” will allow you to download the data in a CSV file.

This CSV file contains data for north and south shaking, east and west shaking, and up and down shaking every 1/100th of a second.

CSVデータの内容

CSV Data Contents

This time, we convert these data to animation data and import them as 3D data.

Explanation of Python code

The code used in this case is as follows

import bpy, csv

data = "FILEPATH" # (1)
current_scene = bpy.context.scene
target_object = current_scene.objects["Cube"] # (2)

scale = 100 # (3)
interval = 1 # (4)

current_frame = 1

with open( data, encoding='shift_jis' ) as csvfile: # (5)
reader = csv.reader( csvfile )
for i, row in enumerate( reader ):
if i < 8: continue # (6)
x, y, z = row[0:3]
x = float(x) / scale
y = float(y) / scale
z = float(z) / scale
target_object.location = (x, y, z)
target_object.keyframe_insert(data_path="location", frame=current_frame*interval)
current_frame += 1

The above code is annotated with (1) through (6) as comments, each of which is explained below:

  1. Specify the location of the CSV file 
  2. In this example of Cube (default cube), an object to which the motion is applied is specified.
  3. Reduce the shaking width. The larger the number, the smaller the shaking.
  4. Frames are inserted in between (the larger the number, the longer the playback time).
  5. Strong-motion observation data is in Shift-JIS, so encoding is specified.
  6. Ignore the first 8 lines as they are header data that will not be extracted.

Importing Python Code

Let’s get started using this in Blender.

To work with Python in Blender, use the built-in “Text Editor.”

Blenderのテキストエディタ

Blender’s text editor

When you switch to the text editor, you will see a blank screen like this, but press “New” at the top.

新規テキストの作成

Create new text

This presents the following empty text editor.

空のテキストエディタ

Empty text editor

Try pasting the above code here.

Note, copying the code from this article and pasting it into the text editor lead to an error because the indentation is lost.

Indentation is important in Python; so if pasting fails, try pasting from the Gist code.

貼りつけた後

After pasting

In this code, change the part of (1), which is a FILEPATH, to the actual file name.

The file name must be specified as an absolute path.

In a Windows environment, replace the backslash (“\” or circle symbol) with a forward-slash (“/”).

In other words, “C:\Data\data.csv” becomes “C:/Data/data.csv.”

Execution of the capture process

After setting this up, let’s get into the processing.

To execute, click the play button in the upper right corner.

If you do not see this button, the display area may be too small.

Pythonの実行

Running Python

If an error is present, you can identify the error by looking at the console screen.

If not, use “Toggle System Console” to view it.

コンソールの表示

Console Display

In most cases, you will get an error message, such as a wrong file name. Thus, correct the error and re-execute the code.

If the execution is successful, processing will begin. Since strong-motion observation data are a large data, processing will take some moments, so please leave it as it is until it is finished.

Confirmation of imported data

When the processing is complete, a keyframe will be placed on the timeline, as shown below:

処理後のタイムライン

Timeline after processing

Let’s take a look at the animation curves in the Graph Editor.

グラフエディタに切り替え

Switch to Graph Editor

After switching, select the Cube object displayed on the 3D view and assign the animation to the Cube object.

追加されたアニメーション

Added Animation

Here, X, Y, and Z position information and a graph have been added to the 1 in the upper left corner.

The graph is difficult to determine as it is, so try moving it with the mouse wheel or middle button.

グラフの表示移動・拡大

Move/expand graph display

Note 18007 frames are in this seismic data animation. If you try playing it as it is, the entire animation will not play. Thus, you must change the last frame.

終了フレーム

end frame

Change this number to 18007.

Next, under “Output Property,” the “Frame Rate” defaults are 24 fps, change this to 100.

Since no option is available for 100, select Custom.

カスタムを選択

Select Custom

Next, you will see the “FPS” box and specify 100.

FPSを設定

Set FPS

Before playback, change the playback setting.

The setting is to change the “Playback” > “Sync” setting to “Frame Dropping.”

再生設定

Playback Settings

This change is necessary because using the default setting “Play Every Frame” causes Blender to play all animation frames, resulting in the following problems:

  1. It will take longer than normal to playback if the processing cannot keep up.
  2. The playback will be slower when the screen refresh rate is low (for example, using a 60 Hz screen for a frame rate of 100).

Therefore, if the data cannot be displayed with this setting, the frame playback will be skipped, and priority will be given to time accuracy.

This change is important for data, especially for seismogram data, where real-time accuracy is important.

Press [Space] to start playback.

The playback will remain for a while, but gradually the shaking becomes more intense.

再生した地震計データ(実際はもっと滑らかに表示されます)

Seismograph data played back (actually displayed more smoothly)

It can also be output as FBX and uploaded to STYLY for playback.

Time series data

We import time series data in the next example.

In this example, we are dealing with two series of data, and the data we will use is the Japanese population trend data.

These data record the population by sex.

Explanation of Python code

The following code is used in this example:

import bpy, csv

data = "FILEPATH" # (1)
current_scene = bpy.context.scene
target_object_male = current_scene.objects["Male"]
target_object_female = current_scene.objects["Female"]

scale = 20000000 # (2)
interval = 10 # (3)

current_frame = 1

with open( data, encoding='shift_jis' ) as csvfile:
reader = csv.reader( csvfile )
for i, row in enumerate( reader ):
if i < 6: continue # (4)
if i > 126: continue # (5)
_,_,male,female = row[0:4]
male_scale = float(male) / scale
female_scale = float(female) / scale
target_object_male.scale = (1,1,male_scale) # (6)
target_object_female.scale = (1,1,female_scale) # (7)
target_object_male.keyframe_insert(data_path="scale", frame=current_frame*interval) # (8)
target_object_female.keyframe_insert(data_path="scale", frame=current_frame*interval) # (9)
current_frame += 1

The code is also available on Gist here.

The key points in the above code are as follows:

  1. Follow the example in the previous section and specify the file name here.
  2. Since the number is large, the image is displayed on a scale of 1:20,000,000.
  3. Since the number here is specified as 10, a keyframe is to be hit every 10 frames.
  4. The first 5 lines of the downloaded data are excluded because they are not data.
  5. The 127th and subsequent lines are also excluded because they are not data.
  6. Specify the male value as the scale value.
  7. Specify the female value as the scale value.
  8. Keyframes are set for male objects.
  9. Keyframes are set for female objects.

Preparation of objects for display

In the previous section, the default cube was used as the target object. Two series of data are employed, and objects are prepared.

In this case, we chose “Male” and “Female.”

We also specified the color of each object.

用意したオブジェクト

Prepared objects

Then, the origin is specified at the bottom of the object.

Follow the steps below to specify the limitation.

  1. Enter the edit mode of the target object and specify the area to be covered (in this case, the bottom part).
  2. Press [Shift]-[S] to bring up the “Snap” menu, then press “(Cursor to Selected)” (or [2] key).
  3. Return to the object mode and select the target object.
  4. Select “Origin to 3D Cursor” from the Origin Settings menu.
基点をオブジェクト下部に設定

Set the origin at the bottom of the object

The reason for this setting is to use the Z-axis scale value as a numerical visualization.

原点を下部に指定した場合の拡大縮小の挙動

Scaling behavior when the origin is specified at the bottom

As you can see, specifying a scale value for the Z-axis changes the size of the image while leaving the origin unchanged.

Data capturing process

If you perform the same capturing similar to that of the previous section, keyframes are keyframed in the same way.

In this case, 10 is specified as the interval, so a keyframe is specified every 10 frames.

10フレームごとに打たれたキーフレーム

Keyframes struck every 10 frames

Specify the last frame as 1212 and play this animation as follows:

再生した人口データ(実際はもっと滑らかに表示されます)

Reproduced population data (displayed more smoothly)

How to output animation of multiple objects individually

Like the seismometer animation, multiple objects can also be imported into STYLY. In this example, some ingenuity is required when outputting multiple objects that contain different animations.

The flow outputs each object as a separate FBX.

First, switch to “Nonlinear Animation.”

ノンリニアアニメーション

Non-linear animation

Then, press the “Strip Action (Push Down Animation)” button for both animations.

アクションをストリップ化

Strip actions

The display the changes as follows:

ストリップ化の状態

Stripping status

After this process, select a single object (in this case, Male or Female) and output FBX. At this time, make sure the “Selected Objects” is selected, and “All Actions” is deselected as shown below:

FBX設定

FBX Settings

When this is done for each object, two types of files are output.

Two ways to upload these files are:

  1. Upload each file STYLY as a separate object.
  2. Import into Unity, take the two FBX files, and upload them as a single prefab.

Moreover, follow the article on handling animations in Unity.

Below is an example of using Method 2 above to add post-effects such as bloom.

In this way, we can display the numerical data. By adding other animations and innovations, numerical data can be visualized memorably.

The program can also be used for various business graphic presentations.

Application of captured data

Let’s use the earthquake data in STYLY.

This time, we create a simple earthquake simulator.

We use the room model as discussed in the previous explanation of the Asset Browser and configure it to place objects on the ground.

The shaking is reproduced, but it is difficult to feel the shaking on the VR screen.

This time, we fix the scaffolding in a room and shake the surrounding scenery to simulate the earthquake experience.

地震シミュレーターのモデル

Earthquake Simulator Model

By placing several boxes on the ground, we can better understand the movement of the ground.

Since the ground and boxes have the same motion, select the ground and boxes, and merge them by pressing [Ctrl]+[J].

Next, we assign the seismic data to this ground.

The following code is used this time.

import bpy, csv

data = "FILEPATH"
current_scene = bpy.context.scene
target_object = current_scene.objects["Env"]

scale = 100
interval = 1

current_frame = 1

with open( data, encoding='shift_jis' ) as csvfile:
reader = csv.reader( csvfile )
for i, row in enumerate( reader ):
if i < 8: continue # (6)
x, y, z = row[0:3]
x = float(x) / scale * -1
y = float(y) / scale * -1
z = float(z) / scale * -1
target_object.location = (x, y, z)
target_object.keyframe_insert(data_path="location", frame=current_frame*interval)
current_frame += 1

If you use the code, please get it from Gist.

The code is similar to the previous code, but the bolded part has changed.

This was inverted by setting it to -1.

In this case, the room we are standing in is stationary, but the scenery around it is moving. By inverting the code, the illusion of motion becomes the actual motion.

When I ran the animation, keyframes were hit, which I output as FBX and uploaded via Unity.

STYLY looks like this.

 

When you display it in VR, you will feel the intensity of the shaking.

Some sensitive people may feel as if they are experiencing a strong shaking. Thus, pay attention to safety and be careful not to collide with surrounding objects.

Upload your 3D model to STYLY.

Create a STYLY account

Sign up for free

How to create an account

How to upload to STYLY

How to upload from Unity to STYLY

For questions about STYLY, bug reports, and requests for improvements, please contact the STYLY FORUM

https://en.forum.styly.cc/support/discussions

In this way, you can use Python to visualize and appealingly represent various types of data as if you were importing external data.

We encourage you to experiment with various other types of data.