如何使用 python 绘制二次函数虚输入的 4 维图

How to use python to graph a 4-d graph for imaginary inputs of quadratic functions

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

f(x) = x^2 + 1

对于 x 的所有实数和复数值 (a + bi),这需要我有四个维度:实部x of (x + bi) of x[现简称X],虚部bi of (x + bi)[现简称W],(y + bi)[现简称Y]的实部y,虚部bi的 (y + bi) [现在称为 Z].

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

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

这是我的解决方案:

# 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()

这是输出:

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