How to plot a 2d structured mesh in matplotlib
IIUC, vlines
and hlines
would do:
plt.vlines(np.linspace(0,1,11), 0, 0.6)
plt.hlines(np.linspace(0,0.6,7), 0, 1)
If you already have mesh x,y
:
plt.vlines(x[0], *y[[0,-1],0])
plt.hlines(y[:,0], *x[0, [0,-1]])
Out:
You can np.transpose
the points you already have, while using a line plot()
rather than scatter()
.
import numpy as np
import matplotlib.pyplot as plt
x, y = np.meshgrid(np.linspace(0,1, 11), np.linspace(0, 0.6, 7))
plt.plot(x, y) # use plot, not scatter
plt.plot(np.transpose(x), np.transpose(y)) # add this here
plt.show()
You can of course have it colored in black with c='k'
I'd use two linecollections for this:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
x, y = np.meshgrid(np.linspace(0,1, 11), np.linspace(0, 0.6, 7))
plt.scatter(x, y)
segs1 = np.stack((x,y), axis=2)
segs2 = segs1.transpose(1,0,2)
plt.gca().add_collection(LineCollection(segs1))
plt.gca().add_collection(LineCollection(segs2))
plt.show()
Also see How to plot using matplotlib (python) colah's deformed grid?
Because if the grid is not deformed, it would be more efficient to draw a single linecollection, like
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
x, y = np.meshgrid(np.linspace(0,1, 11), np.linspace(0, 0.6, 7))
segs1 = np.stack((x[:,[0,-1]],y[:,[0,-1]]), axis=2)
segs2 = np.stack((x[[0,-1],:].T,y[[0,-1],:].T), axis=2)
plt.gca().add_collection(LineCollection(np.concatenate((segs1, segs2))))
plt.autoscale()
plt.show()