简体   繁体   English

在 Python 中绘制带有二维向量条目的 function

[英]Plotting a function with 2D vector entry in Python

I have the following function to plot:我有以下 function 到 plot:

f(x) = 3 + (x - (2  6)T )T · (x - (2  6)T)

where (2 6) is a vector, T represents transpose and x is a vector of size 2. My question is how can I implement a np.linspace so that I can get a continuous 2D function?其中(2 6)是一个向量, T表示转置, x是一个大小为 2 的向量。我的问题是如何实现np.linspace以便获得连续的 2D function?

I have written my function in the following form:我以以下形式编写了我的 function:

def f(x):
    a = np.array([[2],[6]])
    t = lambda x: 3 + np.dot((x - (a)).T, (x - a))
    return t(x)

x = np.array([[4],[1]]) # Some random (2,1) sized vector
y = f(x) # Returns an array sized (1,1)

For example, to plot a variation of the function f(x) = x^2 (x-squared) I can write the following code:例如,对于 plot function f(x) = x^2 (x-squared)的变体,我可以编写以下代码:

def f(x):
   return x**2

x = np.linspace(-5, 5, 20)
y = f(x)
plt.plot(x, y)

I want to know whether it is possible to plot a continuous function for a case where x input is two-dimensional vector.我想知道对于x输入是二维向量的情况,是否可以 plot 连续 function 。 If it is not feasible, how the first function should be plotted?如果不可行,第一个 function 应该如何绘制? A 3-D plot is not possible since my function only has x as its parameter. 3-D plot 是不可能的,因为我的 function 只有x作为其参数。

Edit : Edit

Dimension of your vectors is 2. You also have value of function for this vector.你的向量的维度是 2。你也有这个向量的 function 的值。 In total you have 3 parametrs, so I think it can't be plotted as 2D plot and you need to use 3D plot.(Your x vector is just a tuple, so you can use x[0] and x[1] as axis)总共你有 3 个参数,所以我认为它不能被绘制为 2D plot,你需要使用x plot。轴)

@deeenizka is right that we have to plot 3 dimensions. @deeenizka是对的,我们必须 plot 3 个维度。 One way to do it is to use a contour line plot.一种方法是使用轮廓线plot。

First we have to vectorize your function to compute the values of the function with an array of 2D vectors首先,我们必须对您的 function 进行矢量化,以使用二维向量数组计算 function 的值

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    a = np.array([[2],[6]])
    x = x - a
    return 3 + np.einsum('ij,ij->j',x ,x)

To get the input coordinate vectors we can use meshgrid and ravel the 2D arrays to pass them to the function f要获得输入坐标向量,我们可以使用meshgrid并将 2D ravel传递给 function f

x = np.linspace(-50, 50, 100)
y = np.linspace(-50, 50, 100)

X,Y = np.meshgrid(x, y)
data = np.vstack([X.ravel(), Y.ravel()])

We can plot the data with contourf after we reshaped the returned array of function values.在我们对返回的 function 值数组进行整形后,我们可以用轮廓函数contourf数据。

plt.figure(figsize=(8,6))
plt.contourf(X, Y, f(data).reshape(X.shape), levels=20)
plt.colorbar();

Out:出去:

你的功能轮廓

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

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