温馨提示:本文翻译自stackoverflow.com,查看原文请点击:matplotlib - How to use python to graph a 4-d graph for imaginary inputs of quadratic functions
3d graph math matplotlib python

matplotlib - 如何使用python为二次函数的虚输入图4-d图

发布于 2021-03-25 15:49:01

我是一名高中生,没有编码经验,但是我想编写一个带有颜色渐变的matplotlib 3d图形作为第四维度来绘制函数:

f(x)= x ^ 2 +1

对于所有实数和复数的值(A + B的)X,这将需要我有四个方面:实部X的X [现在称为X]中,(X + BI)的虚数部分双向的( x + bi)[现在称为W],(y + bi)的实部y [现在称为Y]和(y + bi)的虚部bi [现在称为Z]。

基本上,输入将是X,在格式(X + W) 并输出将是F(X) 其格式为(Y + Z) 我希望图形具有X,Y和Z轴,而W表示为图形表面上的颜色渐变。Z和W是虚数b * cmath.sqrt(-1)。我希望所有参数的范围都在(-20,20)之间。

我的笔记本电脑上装有python和anaconda,请帮忙。<3

查看更多

提问者
Harley Glayzer
被浏览
0
Jacob K 2020-10-24 07:36

这是我的解决方案:

# Import packages
import numpy as np
from mpl_toolkits.mplot3d import Axes3D   # Needed to create 3D plots
import matplotlib
import matplotlib.pyplot as plt
#%matplotlib notebook                     # Uncomment this if using Jupyter

# Define function
def fun(x):
    # Note: x is a complex() object, and * and + are defined for complex numbers
    return x*x + 1

# Create 1x1 figure with 3 axes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Define grid of x and w using a step of 0.05
X = W = np.arange(-20.0, 20.0, 0.05)
X, W = np.meshgrid(X,W)
complexVals = X + 1j*W      # Convert X/W grid into complex numbers

# Call the function on the complex numbers and extract the real/imag parts
Y_Z = fun(complexVals)
Y = Y_Z.real
Z = Y_Z.imag

# Create colormap for W
color_dimension = W
minn, maxx = color_dimension.min(), color_dimension.max()
norm = matplotlib.colors.Normalize(minn, maxx)
m = plt.cm.ScalarMappable(norm=norm, cmap='jet')
m.set_array([])
fcolors = m.to_rgba(color_dimension)

# Create surface
ax.plot_surface(X, Y, Z, facecolors=fcolors, vmin=minn, vmax=maxx, shade=False,
                linewidth=0, antialiased=False)

# Set axis labels
ax.set_xlabel('X (Re)')
ax.set_ylabel('Y (Re)')
ax.set_zlabel('Z = f(x) (Im)')

# Create colorbar and set title
cbr = plt.colorbar(m)
cbr.ax.set_title('W')

# Show plot with colorbar
plt.show()

这是输出:
3D_Plot

但是,如果你使用的是Anaconda,我强烈建议将此代码添加到Jupyter Notebook中。那你可以得到一个互动情节。
它已经与Anaconda一起安装,你可以通过jupyter notebook在Anaconda提示符下键入来启动它