[solved] how to use matplotlib in Python to draw 3D surface graph (3D graph with free rotation)

1. Demand

During the electromagnetic design of the motor, some parameters need to be optimized, so the data is derived from the electromagnetic simulation software Maxwell, and some of the data are shown in the figure below.

However, the influence of parameters cannot be seen directly, so it is adjusted to matrix form, as shown in the figure below.

In this way, although the influence of input parameters (current and diameter) on output parameters (torque) can be seen intuitively, it is not beautiful enough. Therefore, it is hoped to produce a three-dimensional diagram.

So our demand is to draw the above table into a three-dimensional diagram. Matlab or Python can draw three-dimensional drawings. Since this computer can't bring MATLAB, choose a lighter and free Python to draw.

2. Effect

3. Source code

# -*- coding: utf-8 -*-
Created on Wed Nov  4 11:50:31 2021

@author: 29235

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

fig = plt.figure()
ax = Axes3D(fig)

X = np.array([40, 40.5, 41, 41.5, 42, 42.5, 43, 43.5, 44, 44.5, 45, 45.5, 46])
Y = np.array([73, 73.4, 73.8, 74.2, 74.6, 75])
X, Y = np.meshgrid(X, Y)

print("X Dimension information",X.shape)
print("Y Dimension information",Y.shape)

Z = np.array([[6.589055889,6.64902114,6.708506801,6.76873195,6.826929116,6.883863945,6.941234139,7.000980041,7.054255481,7.109803791,7.164581639,7.218312404,7.270706248

print("Z Axis data dimension",Z.shape)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow')
ax.set_xlabel('I(A)', color='b')
ax.set_ylabel('D(mm)', color='g')
ax.set_zlabel('T(Nm)', color='r')


I wrote this code in spyder, because when running the code with spyder, the generated pictures will be drawn with spyder's Plots by default, so the resulting pictures are static and cannot be rotated.

It is said on the Internet that the picture viewer provided by matplotlib can rotate to view three-dimensional pictures, but I didn't find a way to draw without Plots in spyder.

So I thought of a way.

4. Special requirements (free rotation)

Open the command line and change the directory to the directory where the drawing code is located.

Activate the environment. (because I use the self built environment to process data, I need to activate the environment. If you use the default environment to draw, you don't need this step)

Enter the command python I_D_T_Data_Process.py

That is, run the. py file directly, which will call the graphics display provided by matplotlib. At this point, you can freely rotate the three-dimensional diagram.

Tags: Python

Posted on Thu, 04 Nov 2021 00:42:07 -0400 by JasonMWaldo