简体   繁体   English

Plot a 3d plot in Python 来自二维矩阵中的元素

[英]Plot a 3d plot in Python from elements in a 2D matrix

I would like to plot a function f(x 1, x 2 ) of two variables x 1 and x 2 in a 3D plot. The function is containted in a 2D matrix, with x 1 forming the rows and x 2 the columns.我想 plot a function f(x 1, x 2 ) 的两个变量 x 1和 x 2在 3D plot 中。function 包含在二维矩阵中,x 1构成行,x 2构成列。 How do I go about plotting this?我 go 如何绘制此图?

I have tried defining my function f as我尝试将我的 function f 定义为

x1_axis = np.arange(0, 10, 0.1)
x2_axis = np.arange(0, 10, 0.1)

f = [fun[x1, x2] for x1 in x1_axis and x2 in x2_axis]

where 'fun' is my matrix storing the values.其中“乐趣”是我存储值的矩阵。 This raises the error 'ValueError: The truth value of an array with more than one element is ambiguous.'这会引发错误“ValueError:具有多个元素的数组的真值不明确。”

Is there any other way to implement this?还有其他方法可以实现吗?

You can create a 2d function matrix, by passing a mesh into a funcion.您可以通过将网格传递给函数来创建 2d function 矩阵。

import numpy as np
import matplotlib.pyplot as plt

def fun(x1, x2):
    # Define your function here
    return x1 + x2

x1_axis = np.arange(0, 10, 0.1)
x2_axis = np.arange(0, 10, 0.1)

X1, X2 = np.meshgri

d(x1_axis, x2_axis)
F = fun(X1, X2)

You can than plot that using你可以比 plot 使用

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X1, X2, F)

plt.show()

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

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