简体   繁体   English

如何使用带有使用matplotlib的单个矢量或数组输入的函数来绘制表面?

[英]How can I plot a surface using a function with a single vector or array input using matplotlib?

I want to plot a function R^2 -> R using numpy and matplotlib. 我想使用numpy和matplotlib绘制函数R ^ 2->R。

In most matplotlib examples, a function with two inputs is used, as here: 在大多数matplotlib示例中,使用带有两个输入的函数,如下所示:

import numpy as np
import matplotlib.pyplot as mplot
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import Axes3D as m3d

def f(x,y,sign=1.0):
    out = (np.sin(x - y/8)**2 + np.sin(x + y/8)**2)/(np.sqrt((x - 8.6998)**2 + (y - 6.7665)**2) + 1)
    return out

x = np.linspace(-5,5,num=100)
y = x
xi, yi = np.meshgrid(x,y)
zi = f(xi,yi)
fig = mplot.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(xi,yi,zi,cmap=cm.coolwarm)

Now, this is fine, except that I want to plot functions that I am also optimizing. 现在,这很好,除了我要绘制同时也在优化的函数。 Those typically use a single vector input, as here: 这些通常使用单个向量输入,如下所示:

def f(x,sign=1.0):
    # Objective function
    out = sign*(x[0]**3 + 3*x[0]**2 - 2*x[0]*x[1] + 3*x[0] + x[1]**3 + 3*x[1]**2 + 3*x[1])
    return out

How would I go about generating a surface plot using such a function? 我将如何使用这样的函数生成表面图? I would like to use the same functions for both my plots and my optimization routines, since transcribing them is both wasteful and error-prone. 我想对绘图和优化例程使用相同的函数,因为转录它们既浪费又容易出错。

If the input x is a 3-D array representing a regular mesh, you can do, assuming a shape (2, m, n) : 如果输入x是表示规则网格的3-D数组,则可以假设形状为(2, m, n)

def f(x, sign=1.0):
    x1 = x[0, :]
    x2 = x[1, :]
    # Objective function
    out = sign*(x1**3 + 3*x1**2 - 2*x1*x2 + 3*x1 + x2**3 + 3*x2**2 + 3*x2)
    return out

such that out will be a 2-D array with shape (m, n) , ready to be plot with matplotlib: 使得out将是一个2-d阵列形状(m, n)准备与matplotlib情节:

ax.plot_surface(x[0, :], x[1, :], f(x), cmap=cm.coolwarm)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM