Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How define a boundary in matplotlib python?

Tags:

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:

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()
like image 960
user9812604 Avatar asked Dec 31 '18 15:12

user9812604


People also ask

How do you define a boundary in Python?

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.

How do I plot a line in Python matplotlib?

To plot a line plot in Matplotlib, you use the generic plot() function from the PyPlot instance. There's no specific lineplot() function - the generic one automatically plots using lines or markers. This results in much the same line plot as before, as the values of x are inferred.


1 Answers

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

enter image description here

like image 175
Sheldore Avatar answered Sep 20 '22 03:09

Sheldore