python - 使用 Matplotlib 绘制等高线图和线框图

标签 python matplotlib plot

我必须绘制函数 formula 的等高线图和线框图。这是我到目前为止的代码:

# Number of uniformly ditributed random numbers
n = 2000

def func_vec(x1s, x2s):
    return x1s * x1s + 4 * x2s * x2s

np.random.seed()
x1s = np.random.uniform(-1, 1, n)
x2s = np.random.uniform(-1, 1, n)
ys = func_vec(x1s, x2s)

fig = plt.figure()

# Scatter
ax1 = fig.add_subplot(1, 2, 1)
ax1.scatter(x1s, x2s, color = 'g', s = 2, edgecolor = 'none')
ax1.set_ylim([-1,1])
ax1.set_xlim([-1,1])

# Contour
ax1.contour(x2s, x1s, ys[np.newaxis,:].repeat(n, axis = 0))

# 3D visualization
ax2 = fig.add_subplot(1, 2, 2, projection = '3d')
X = x1s
Y = x2s
Z = ys
ax2.plot_wireframe(X, Y, Z, rstride = 1, cstride = 1)

plt.show()

我不明白的是 contour()plot_firewrame() 实际上是如何工作的?有人可以善意地向我解释一下吗(在指定功能的上下文中)?另外,我应该如何指定X、Y和Z?

这就是情节现在的样子: enter image description here

它应该是这样的(上面的散点图可以正常工作): enter image description here

最佳答案

这是将生成正确绘图的代码。任何遇到此问题的人都应该会发现代码非常不言自明:

# Number of uniformly ditributed random numbers
n = 2000

def func_vec(x1s, x2s):
    return x1s * x1s + 4 * x2s * x2s

np.random.seed()
x1s = np.random.uniform(-1, 1, n)
x2s = np.random.uniform(-1, 1, n)
ys = func_vec(x1s, x2s)

fig = plt.figure(22)

# Scatter
ax1 = fig.add_subplot(1, 2, 1)
ax1.scatter(x1s, x2s, color = 'g', s = 2, edgecolor = 'none')
ax1.set_ylim([-1,1])
ax1.set_xlim([-1,1])

# Contour
xi = np.linspace(-1,1,20)
yi = np.linspace(-1,1,20)
zi = griddata((x2s, x1s), ys, (xi[None,:], yi[:,None]), method = 'cubic')
ax1.contour(xi, yi, zi, 6, linewidths = 1, colors = ('#0000ff', '#0099ff', '#009999', '#999900', '#ff9900', '#ff0000'))

# 3D visualization
ax2 = fig.add_subplot(1, 2, 2, projection = '3d')
X, Y = np.meshgrid(xi, yi)
ax2.plot_wireframe(X, Y, zi, rstride = 1, cstride = 1)
ax2.view_init(28, -144) 

plt.show()

关于python - 使用 Matplotlib 绘制等高线图和线框图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18923502/

相关文章:

python - 使用 Python 启动 Excel 文件

python - 绘制二维 numpy 数组的图例

python - 单击条形图中的条形可生成该条形图中值的散点图

r - 绘制 R 中的哪个参数?

python 2.7 : can I make Matplotlib display values like Plotly?

python - Peeweebulk_create 返回 id

python - Windows 上的 GeoDjango : Try setting GDAL_LIBRARY_PATH in your settings

python - 如何使用 web 插件将 JSON 有效负载发送到 RabbitMQ?

python - 在条形图上叠加箱线图 matplotlib/python

python - text.on_change 对 Bokeh TextInput 没有响应