编写一段python 代码,画出函数: z=x3+ y3+x2+ y2+xy的 3D图

#python#3D图
请编写一段python 代码,画出函数: z=x3+ y3+x2+ y2+xy的 3D图
(要求:x轴和y轴坐标刻度范围是(-20,20),并且x轴和y轴的标签分别为:“x”“y”)

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

def func(x, y):
    return x**3 + y**3 + x**2 + y**2 + x*y

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = y = np.linspace(-1, 1, 100)
X, Y = np.meshgrid(x, y)
Z = func(X, Y)

ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.show()

试一下

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

# Define the function
def f(x, y):
    return x**3 + y**3 + x**2 + y**2 + x*y

# Create x,y coordinates
x = y = np.arange(-20, 21, 1)

# Create the mesh grid
X, Y = np.meshgrid(x, y)

# Calculate the function value for each point in the grid
Z = f(X, Y)

# Plot the 3D surface
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()


首先定义了要绘制的函数 f(x, y),然后创建了 x 和 y 坐标,并使用 np.meshgrid() 创建了一个网格,计算了在每个网格点上的函数值,并使用 plot_surface() 函数绘制了3D图形。最后,我们使用 set_xlabel(), set_ylabel(), 和 set_zlabel() 函数给三个坐标轴添加了标签,并使用 plt.show() 显示图形。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^