[英]Plot 3D graph using Python
I trying to plot a graph of a function f(x, y) = x**x*y
, but I'm getting an error:我试图 plot 的图表 function f(x, y) = x**x*y
,但我得到一个错误:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
def f(x,y):
return x**x*y
x = np.arange(-4.0, 4.0, 0.1)
y = np.arange(-4.0, 4.0, 0.1)
z = f(x, y)
X, Y, Z = np.meshgrid(x, y, z)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z)
plt.xlabel('x')
plt.ylabel('y')
plt.show()
First error is:第一个错误是:
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:2: RuntimeWarning: invalid value encountered in power /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:2:RuntimeWarning:power遇到无效值
And the second is:第二个是:
ValueError: Argument Z must be 2-dimensional. ValueError:参数 Z 必须是二维的。
You can try:你可以试试:
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
The meshgrid
function returns coordinate matrices from coordinate vectors. meshgrid
从坐标向量返回坐标矩阵。 . . Then, you can apply the function and plot it.然后,您可以应用 function 和 plot 它。
For the "RuntimeWarning: invalid value encountered in power" warning, that is related to the decimal power on numpy
objects.对于“RuntimeWarning:power遇到无效值”警告,这与numpy
对象的十进制幂有关。 Please have a look at this topic NumPy, RuntimeWarning: invalid value encountered in power for more details.请查看此主题NumPy,RuntimeWarning:在电源中遇到无效值以获取更多详细信息。
Full code:完整代码:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
def f(x,y):
return x**x*y
x = np.arange(-4.0, 4.0, 0.1)
y = np.arange(-4.0, 4.0, 0.1)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z)
plt.xlabel('x')
plt.ylabel('y')
plt.show()
Output: Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.