我是一名高中生,没有编码经验,但是我想编写一个带有颜色渐变的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
这是我的解决方案:
# 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一起安装,你可以通过jupyter notebook
在Anaconda提示符下键入来启动它。
jupyter笔记本仍然是同一语言吗?
“#注意:x是complex()对象,而*和+是为复数定义的”的含义
@HarleyGlayzer我只是
x
说要传递给fun
函数的参数不仅仅是一个整数,而是一个复数,并且Python可以理解*和+表示复数。同样,结果也是一个复数。