Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting a grid in Python

Tags:

python

plot

grid

I'm trying to start 2D contour plot for a flow net and I'm having trouble getting the initial grid to show up properly.

Given the number of columns and the number of rows, how can I write a function that will plot a grid so that all points in the given range appear?

I tried plotting for 4 columns and 3 rows of points by doing this:

r = 3

c = 4

x = [i for i in range(c)]

y = [i for i in range(r)]

plot(x,y,'ro')

grid()

show()

and get this error:

'ValueError: x and y must have same first dimension'

So I tried testing it on a 4x4 grid and got this and I get close to what I want, however it only plots points (0,0), (1,1), (2,2), and (3,3)

However, I also want the points (0,0), (1,0), (2,0), (3,0), (1,0), (1,1)...(3,2), (3,3) to appear, as I will later need to plot vectors from this point indicating the direction of flow for my flow net.

Sorry, I know my terminology isn't that great. Does anyone know how to do this and how to make it work for grids that aren't square?

like image 226
bang Avatar asked Jul 27 '26 06:07

bang


2 Answers

  • You could use itertools.product to generate the desired points.
  • Use plt.scatter to plot the points
  • Use plt.quiver to plot the vector field. (Relevant code taken from these SO answers)

import numpy as np
import matplotlib.pyplot as plt
import itertools
r = 3
c = 4
x = np.linspace(0, c, c+1)
y = np.linspace(0, r, r+1)

pts = itertools.product(x, y)
plt.scatter(*zip(*pts), marker='o', s=30, color='red')

X, Y = np.meshgrid(x, y)
deg = np.arctan(Y**3 - 3*Y-X)
QP = plt.quiver(X, Y, np.cos(deg), np.sin(deg))
plt.grid()
plt.show()

enter image description here

like image 103
unutbu Avatar answered Jul 29 '26 20:07

unutbu


r = 3
c = 4

x = [i % c for i in range(r*c)]
y = [i / c for i in range(r*c)]

print x
print y

Gives:

[0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]

When used to draw graph as you did it produces desired result.

like image 31
Fenikso Avatar answered Jul 29 '26 19:07

Fenikso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!