如何使用Axes3D使我的表面图出现?

时间:2018-11-18 07:15:41

标签: python matplotlib

我正在尝试使用Python Matplotlib创建表面图。我已经阅读了文档,试图找出我的代码错误的地方,或者是否遗漏了任何东西,但是遇到了麻烦。

我写的代码是

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

def computeCost(X, y, theta):
    m = len(y)
    predictions = np.dot(X, theta)
    squareErros = (predictions - y) ** 2
    J = (1 / (2 * m)) * sum(squareErrors)

    return J

data = np.loadtxt("./data1.txt", delimiter=',')
X = data[:, 0].reshape(-1, 1)
y = data[:, 1].reshape(-1, 1)
m = len(y)
X = np.concatenate((np.ones((m, 1)), X), axis=1)

theta0_vals = np.linspace(-10, 10, 100) # size (100,)
theta1_vals = np.linspace(-1, 4, 100) # size (100,)
J_vals = np.zeros((len(theta0_vals), len(theta1_vals)))

for i in range(len(x_values)):
    for j in range(len(y_values)):
        t = np.array([theta0_vals[i], theta1_vals[j]]).reshape(-1, 1)
        J_vals[i][j] = computeCost(X, y, t) # size (100, 100)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(theta0_vals, theta1_vals, J_vals)

plt.show()

当我调用plt.show()时,没有任何输出。我希望看到的表面图与此类似:

enter image description here

有人会友好地让我知道我对曲面图库的使用哪里出错了吗?谢谢。


编辑

我已经尝试运行here提供的演示代码,并且工作正常。这是该代码:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np


fig = plt.figure()
ax = fig.gca(projection='3d')

# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)

# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

1 个答案:

答案 0 :(得分:1)

我认为我已经通过更改最后两行代码来解决了这个问题

ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(theta0_vals, theta1_vals, J_vals)

ax = plt.axes(projection='3d')
surf = ax.plot_surface(theta0_vals, theta1_vals, J_vals, rstride=1, cstride=1, cmap='viridis', edgecolor='none')

进行此更改后,我得到了如下表面图:

enter image description here

为此提供参考的链接是this