Home > OS >  Change in coordinate density for np.meshgrid() in matplotlib
Change in coordinate density for np.meshgrid() in matplotlib

Time:02-23

I am plotting a vector field using the numpy function quiver() and it works. But I would like to emphasize the cowlick in the following plot:

enter image description here

I am not sure how to go about it, but increasing the density of arrows in the center could possibly do the trick. To do so, I would like to resort to some option within np.meshgrid() that would allow me to get more tightly packed x,y coordinate points in the center. A linear, quadratic or other specification does not seem to be built in. I am not sure if sparse can be modified to this end.

The code:

lim = 10
int = 0.22 *lim
x,y = np.meshgrid(np.arange(-lim, lim, int), np.arange(-lim, lim, int))

u = 3 * np.cos(np.arctan2(y,x)) - np.sqrt(x**2 y**2) * np.sin(np.arctan2(y,x))
v = 3 * np.sin(np.arctan2(y,x))   np.sqrt(x**2 y**2) * np.cos(np.arctan2(y,x))

color = x**2   y**2
plt.rcParams["image.cmap"] = "Greys_r"
mult = 1
plt.figure(figsize=(mult*lim, mult*lim))
plt.quiver(x,y,u,v,color, linewidths=.006, lw=.1)
plt.show()

CodePudding user response:

You can construct the points whereever you want to calculate your field on and quivers will be happy about it. The code below uses polar coordinates and stretches the radial coordinate non-linearly.

import numpy as np
import matplotlib.pyplot as plt

lim = 10
N = 10

theta = np.linspace(0.1, 2*np.pi, N*2)

stretcher_factor = 2

r = np.linspace(0.3, lim**(1/stretcher_factor), N)**stretcher_factor

R, THETA = np.meshgrid(r, theta)
x = R * np.cos(THETA)
y = R * np.sin(THETA)

# x,y = np.meshgrid(x, y)
r = x**2   y**2

u = 3 * np.cos(np.arctan2(y,x)) - np.sqrt(r) * np.sin(np.arctan2(y,x))
v = 3 * np.sin(np.arctan2(y,x))   np.sqrt(r) * np.cos(np.arctan2(y,x))

plt.rcParams["image.cmap"] = "Greys_r"
mult = 1
plt.figure(figsize=(mult*lim, mult*lim))
plt.quiver(x,y,u,v,r, linewidths=.006, lw=.1)

enter image description here

Edit: Bug taking meshgrid twice

CodePudding user response:

np.meshgrid just makes a grid of the vectors you provide. What you could do is contract this regular grid in the center to have more points in the center (best visible with more points), e.g. like so:

# contract in the center
a = 0.5  # how far to contract
b = 0.8  # how strongly to contract
c = 1 - b*np.exp(-((x/lim)**2   (y/lim)**2)/a**2)
x, y = c*x, c*y
plt.plot(x,y,'.k')
plt.show()

Alternatively you can x,y cooridnates that are not dependent on a grid at all:

x = np.random.randn(500)
y = np.random.randn(500)
plt.plot(x,y,'.k')
plt.show()

But I think you'd prefer a slightly more regular patterns you could look into poisson disk sampling with adaptive distances or something like that, but the key point here is that for using quiver, you can use ANY set of coordinates, they do not have to be in a regular grid.

  • Related