首页 > 解决方案 > 如何在 matplotlib python 中定义边界?

问题描述

我想绘制以下场方程:

但我不知道如何将边界限制为三角形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()

标签: pythonmatplotlibplot

解决方案


使用 NumPy 掩码和np.where函数可以非常简单地实现这一点。我只显示完成工作所需的相关两行代码(由注释突出显示)。

说明X<=1-Y检查您所需的边界条件,然后在该条件成立的所有那些索引处,它分配(或)True的实际计算值,在条件为 的索引处,它分配 0。这里充当一种条件掩码。UxUyFalseX<=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

在此处输入图像描述


推荐阅读