如何在 matplotlib python 中定义边界? [英] How define a boundary in matplotlib python?

查看:31
本文介绍了如何在 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 :

 #使用matplotlib的流图将numpy导入为np导入matplotlib.pyplot作为plt定义速度_i(x,y):vx = x*(3*x+4*y-3)vy = y*(3*x+4*y-4)返回 vx, vyn = 100x = 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.5plt.figure(figsize =(5,4))stream = plt.streamplot(X,Y,Ux,Uy,arrowize = 1,arrowstyle ='->',颜色= vels,密度= 1,线宽= 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 掩码和

I want to plot the following field equations:

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

but I do not know how can I restrict the boundary to a triangle: 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()

解决方案

This is quite straightforwardly achievable using NumPy masking and np.where function. I am only showing the relevant two lines of code (highlighted by a comment) needed to get the job done.

Explanation: X<=1-Y checks your required boundary condition and then at all those indices where this condition holds True, it assigns the actual computed value of Ux (or Uy) and at indices where the condition is False, it assigns 0. Here X<=1-Y acts as kind of a conditional mask.

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

这篇关于如何在 matplotlib python 中定义边界?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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