分段定义的曲面的Python图 [英] Python plot of a piecewise defined surface

查看:52
本文介绍了分段定义的曲面的Python图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为不同区域以不同方式定义的表面绘制 3d 图.以 f(x,y) 为例,如果 x > y 定义为 1,如果 x <= y 定义为 x^2.

I am trying to make a 3d plot of a surface that is defined in different ways for different regions. As an example, take f(x,y) that is defined as 1 if x > y and as x^2 if x <= y.

我用逻辑运算符定义了f,并尝试使用"plot_surface"函数对其进行绘制,并在网格中对其进行评估.不幸的是,我收到一条错误消息,说包含多个元素的数组的真值不明确".

I defined f with logical operators, and tried to plot it with the "plot_surface" function, evaluating it in a grid. Unfortunately, I got an error saying that "the truth value of an array with more than one element is ambiguous".

你知道有什么方法可以解决这个问题吗?

Do you know any way of solving this?

推荐答案

从 Serenity 发布的链接中获取,您需要使用 np.piecewise 定义 f

Taking from the link posted by Serenity you need to define f using np.piecewise

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

num_steps = 500
x_arr = np.linspace(0,100, num_steps)
y_arr = np.linspace(0,100, num_steps)

def zfunc(x, y):
    return np.piecewise(x, [x>y, x<=y], [lambda x: 1, lambda x: x**2])

x,y = np.meshgrid(x_arr, y_arr)
z =zfunc(x,y)

fig=plt.figure()
ax=fig.add_subplot(1,1,1,projection='3d')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')

ax.plot_surface(x,y,z,cmap='viridis') #cmap to make it easier to see 
ax.view_init(30, 70)
plt.show()

为您提供此情节:

这篇关于分段定义的曲面的Python图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆