[PYTHON] I want to see the graph in 3D! I can make such a dream come true.

You want to see it, right?

Trigonometric functions, logarithmic functions, cycloids ... There are so many functions, figures, and graphs in this world that you can count. You want to see such a graph in 3D, right?

So what are you going to do?

This time I would like to use Blender and Excel. Put the coordinate data in the Excel file and create an object with Blender based on it. image.png

Now that I understand how it works ...

Do you want to make it immediately?

Development environment

windows 10 python 3.7 Blender 2.8 pip 20.2.1

Create data in Excel

First, let's install a library to mess with Excel files.

$pip install openpyxl

The code looks like this

function_3Dgraph.py


import openpyxl
import math

class funcdate():
    def create_wb(self,wb_name):
        new_file=openpyxl.Workbook() #Create the data in the Excel file.
        new_file.save(wb_name+'.xlsx') #Save it once.
        print('Excel file is created')
        return new_file
    
    def write_wb(self,cell_name,cell_value,file_name):
        file=openpyxl.load_workbook(file_name+'.xlsx',data_only=True) #Read the Excel file.
        new_wb=file.active #Load the sheet.
        new_wb[cell_name]=cell_value #cell_mane(For example A1)Put a value in the cell.

    def write_func(self,t,file_name):
        file=openpyxl.load_workbook(file_name+'.xlsx',data_only=True)
        new_wb=file.active
        print(new_wb)
        for i in range(1,t+1):
            if(i==0):
                i=1
            x=math.cos(i*math.pi/180) #The formula here can be anything.
            y=math.sin(i*math.pi/180) #The formula here can be anything.
            new_wb['A'+str(i)]=i #I will put data in each coordinate.
            new_wb['B'+str(i)]=x
            new_wb['C'+str(i)]=y
            print(new_wb['A'+str(i)].value,new_wb['B'+str(i)].value,new_wb['C'+str(i)].value)
            
        else:
            file.save(file_name+'.xlsx')
            print('I was able to fill in')

    def get_func(self,file_name,t):
        file=openpyxl.load_workbook(file_name+'.xlsx',data_only=True)
        wb=file.active
        graph_t=wb['A'+str(t)].value #Enter the value of each cell in each coordinate.
        graph_x=wb['B'+str(t)].value
        graph_y=wb['C'+str(t)].value
        a=[graph_t,graph_x,graph_y]
        return a

    
test=funcdate()
test.create_wb('test_function')
test.write_func(360,'test_function')
print(test.get_func('test_function',10))

Let's run it now.

$python function_3Dgraph.py

When you execute it, the Excel file should be completed, so please open it. image.png It's OK if it is in the table like this. By the way, it looks like this in a graph. ・ X-axis and y-axis are separated image.png   ・ X-axis and y-axis combined image.png

Make a graph in Blender

First, let's download Blender. Download Blender Once downloaded, launch it and open the python editor. ↓ Here image.png Then try typing the code below. It is easy to see if you delete the first generated cube (x key).

$import bpy
$bpy.ops.mesh.primitive_uv_sphere_add(segments=32, ring_count=16, radius=1.0, calc_uvs=True, enter_editmode=False, align='WORLD', location=(0.0, 0.0, 0.0), rotation=(0.0, 0.0, 0.0))

If a sphere appears at the coordinates (0.0, 0.0, 0.0), it is successful. image.png

Let's add it now

function_3Dgraph.py


import openpyxl
import math
import bpy

class funcdate():
    def create_wb(self,wb_name):
        new_file=openpyxl.Workbook()
        new_file.save(wb_name+'.xlsx')
        print('Excel file is created')
        return new_file
    
    def write_wb(self,cell_name,cell_value,file_name):
        file=openpyxl.load_workbook(file_name+'.xlsx',data_only=True)
        new_wb=file.active
        new_wb[cell_name]=cell_value

    def write_func(self,t,file_name):
        file=openpyxl.load_workbook(file_name+'.xlsx',data_only=True)
        new_wb=file.active
        print(new_wb)
        for i in range(1,t+1):
            if(i==0):
                i=1
            x=math.cos(i*math.pi/180)
            y=math.sin(i*math.pi/180)
            new_wb['A'+str(i)]=i
            new_wb['B'+str(i)]=x
            new_wb['C'+str(i)]=y
            print(new_wb['A'+str(i)].value,new_wb['B'+str(i)].value,new_wb['C'+str(i)].value)
            
        else:
            file.save(file_name+'.xlsx')
            print('I was able to fill in')

    def get_func(self,file_name,t):
        file=openpyxl.load_workbook(file_name+'.xlsx',data_only=True)
        wb=file.active
        graph_t=wb['A'+str(t)].value
        graph_x=wb['B'+str(t)].value
        graph_y=wb['C'+str(t)].value
        a=[graph_t,graph_x,graph_y]
        return a

    
test=funcdate()
test.create_wb('test_function')
test.write_func(360,'test_function')
for i in range(1,360):
     bpy.ops.mesh.primitive_uv_sphere_add(segments=32, ring_count=16, radius=1.0, calc_uvs=True, enter_editmode=False, align='WORLD', location=test.get_func('test_function',i), rotation=(0.0, 0.0, 0.0))


The bpy library can only be used in Blender, so run it in Blender.

** and before ** Let's make the openpyxl library available in Blender.

Detailed explanation on how to insert

Start as an administrator to use openpyxl with Blender. (Because it is said that you do not have authority ...)

Put Blender in Script mode to execute the file you just created. You can still go. image.png Then open function_3Dgraph.py and run it. image.png

If the graph comes out, it's a success! image.png (1m of Blender is small, so it is difficult to understand, but it is a sine wave with an amplitude of 1. It will be easier to understand if the amplitude is set to 10.)

Well, the graph was completed like this.

By the way, the Excel file created by Blender is saved in C: \ Program Files \ Blender Foundation \ Blender 2.83.

Digression

Here's a little mathematical story ... This time, I made a graph by representing x and y with the parameter t. The formula looks like this.

 \left\{
\begin{array}{ll}
x=f(t) \\
y=g(t)
\end{array}
\right. 

This will create a 3D graph of $ y = f (x) $. Also, if $ t = z $, then $ ax = by = cz (a, b, c are arbitrary constants) $ and a three-dimensional straight line can be created. … So far, we have talked about orthogonal graphs. So what about the polar format? For example, suppose you have an expression like this:

r=f(θ)

image.png

The straight line represented by this equation is decomposed into a horizontal axis (x axis) and a vertical axis (y axis), respectively. image.png

 \left\{
\begin{array}{ll}
x=f(θ) \cos(θ)\\
y=f(θ) \sin(θ)
\end{array}
\right. 

Now you can draw a polar graph.       Actually, it's a good idea to use an Excel file for all this. ~~ If you don't use it, k ~~

Then why did you use it, for example ... image.png

It is used when the graph does not understand such a formula. If there are values in the Excel file, you can create a graph by referring to them.

image.png I think it's shrinking a little, but it's okay. There is no problem if you multiply it by n when taking the value ...

Afterword

This time I tried to make a 3D graph with Blender using Excel. Next, I would like to move this graph like an animation.

Recommended Posts

I want to see the graph in 3D! I can make such a dream come true.
I want to see a list of WebDAV files in the Requests module
I want to make the Dictionary type in the List unique
I want to make input () a nice complement in python
I want to make the second line the column name in pandas
I want to print in a comprehension
I want to create a graph with wavy lines omitted in the middle with matplotlib (I want to manipulate the impression)
(Matplotlib) I want to draw a graph with a size specified in pixels
I tried to display the altitude value of DTM in a graph
I want to be healed by Mia Nanasawa's image. In such a case, hit the Twitter API ♪
I want to make matplotlib a dark theme
I want to create a window in Python
I want to make a game with Python
I want to display the progress in Python!
I want to create a priority queue that can be updated in Python (2.7)
I want to set a life cycle in the task definition of ECS
Python program is slow! I want to speed up! In such a case ...
I want to see the file name from DataLoader
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I want to write in Python! (2) Let's write a test
Even in JavaScript, I want to see Python `range ()`!
I want to randomly sample a file in Python
I want to work with a robot in python.
[Python] I want to make a nested list a tuple
I want to write in Python! (3) Utilize the mock
I want to use the R dataset in python
Make a note of what you want to do in the future with Raspberry Pi
I want to make a blog editor with django admin
I want to make a click macro with pyautogui (desire)
NikuGan ~ I want to see a lot of delicious meat! !!
Put the lists together in pandas to make a DataFrame
I want to make a click macro with pyautogui (outlook)
I tried to make a stopwatch using tkinter in python
[Visualization] I want to draw a beautiful graph with Plotly
I want to align the significant figures in the Numpy array
I want to create a Dockerfile for the time being.
I didn't want to write the AWS key in the program
I tried to make a site that makes it easy to see the update information of Azure
[See in the photo] How a kaggle beginner can rank up from "novice" to "Contributor" in 10 minutes.
I tried to find out the difference between A + = B and A = A + B in Python, so make a note
[Twitter] I want to make the downloaded past tweets (of my account) into a beautiful CSV
[Linux] I want to know the date when the user logged in
LINEbot development, I want to check the operation in the local environment
I want to create a system to prevent forgetting to tighten the key 1
I wanted to solve the ABC164 A ~ D problem with Python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I want to create a pipfile and reflect it in docker
I want to make a parameter list from CloudFormation code (yaml)
I want to pass the G test in one month Day 1
I want to know the population of each country in the world.
I made a command to display a colorful calendar in the terminal
I want to save the trouble of inputting when debugging Paiza's skill check example in a local environment such as Jupyter [Python]
I tried to make a system to automatically acquire the program guide → register it in the calendar in one day
I want to load the pytest fixture as a library somewhere else (pytest may not exist in the environment)
I want to use complicated four arithmetic operations in the IF statement of the Django template! → Use a custom template
[Hi Py (Part 1)] I want to make something for the time being, so first set a goal.
I want to change the color by clicking the scatter point in matplotlib
I want to send a signal only from the sub thread to the main thread
[C language] I want to generate random numbers in the specified range
I came up with a way to make a 3D model from a photo.