python - 如何在 matplotlib python 中定义边界?

标签 python matplotlib plot

我想绘制以下场方程:

  • dx/dt = x*(4*y+3*x-3)
  • dy/dt = y*(4*y+3*x-4)

但我不知道如何将边界限制为三角形:x>=0, y>=0, x<=1-y :

enter image description here

# 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 , 它分配 Ux 的实际计算值(或 Uy )和条件为 False 的索引,它分配 0。这里 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

enter image description here

关于python - 如何在 matplotlib python 中定义边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53988824/

相关文章:

python - 去除空格/制表符/换行符 - python

python - 将基于轮询的异步 API 包装为 Awaitable

python - 寻找最近连接的图算法

python - 使用 matplotlib 绘制轮廓时出错

python - 如何将数据拟合到温度/热曲线上?

python - 移植涉及 matplotlib 设置轴位置(以像素为单位)的 Matlab 代码

python - Pandas 在 1 个图的 11 个图中绘制 22 个系列

arrays - 如何在 Julia 0.6 中转置字符串向量(以便绘制多个图例)?

python - 如何通过 API 检索 Jenkins 作业的所有先前构建?

python - R^2 没有出现在 stats.probplot (python) 中