python - 如何在 matplotlib python 中定义边界?
问题描述
我想绘制以下场方程:
- dx/dt = x*(4*y+3*x-3)
- dy/dt = y*(4*y+3*x-4)
但我不知道如何将边界限制为三角形x>=0, y>=0, x<=1-y
::
# stream plot with matplotlib
import numpy as np
import matplotlib.pyplot as plt
def velocity_i(x,y):
vx = x*(3*x+4*y-3)
vy = y*(3*x+4*y-4)
return vx, vy
n=100
x = np.linspace(0, 1, n)
y = np.linspace(0, 1, n)
X, Y = np.meshgrid(x, y)
Ux, Uy = velocity_i(X, Y)
vels = (Ux**2+Uy**2)**0.5
plt.figure(figsize=(5,4))
stream = plt.streamplot(X, Y,
Ux,Uy,
arrowsize=1,
arrowstyle='->',
color= vels,
density=1,
linewidth=1,
)
plt.xlabel(r"$\Omega_{\rm m}$",fontsize='14')
plt.ylabel(r"$\Omega_{\rm r}$",fontsize='14')
plt.colorbar(stream.lines)
plt.xlim((-.05,1.05))
plt.ylim((-.05,1.05))
plt.show()
解决方案
使用 NumPy 掩码和np.where函数可以非常简单地实现这一点。我只显示完成工作所需的相关两行代码(由注释突出显示)。
说明:X<=1-Y
检查您所需的边界条件,然后在该条件成立的所有那些索引处,它分配(或)True
的实际计算值,在条件为 的索引处,它分配 0。这里充当一种条件掩码。Ux
Uy
False
X<=1-Y
Ux, Uy = velocity_i(X, Y)
Ux = np.where(X<=1-Y, Ux, 0) # <--- Boundary condition for Ux
Uy = np.where(X<=1-Y, Uy, 0) # <--- Boundary condition for Uy
vels = (Ux**2+Uy**2)**0.5
推荐阅读
- database - Tableau - 如何绘制相同维度的两个不同过滤器
- django - Django getstream 用户对象不可迭代
- android-studio - 创建 APK 时 setTheme(R.style.AppTheme) 不起作用
- bison - Bison -d 不创建 tab.h
- c# - Selenium C# ElementNotFound 异常处理
- django - 找不到Django第二页
- c# - C# - Xamarin.Forms - 依赖服务和事件
- arrays - 从数组的哈希中选择属性中的最大值
- android - 解析为对象而不是数组时出现Json错误:JSONObject中的getJSONObject(java.lang.String)无法应用于(int)
- maven - 在命令行快速运行/执行 Maven 项目