2

I want to plot a self-specified grid using Matplotlib in Python.

I know of the np.meshgrid function and can use it to obtain the array of different points I want to connect, but am unsure of how to then plot the grid.

Code example:

x = np.linspace(0,100,100)
y = np.linspace(0,10,20) 
xv, yv = np.meshgrid(x, y)

Now, how can I plot a grid of this xv array?

2 Answers 2

6

You can turn a grid on/off with grid(), but it's only possible to have the grid lines on axis ticks, so if you want it hand-made, what about this:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

xs = np.linspace(0, 100, 51)
ys = np.linspace(0, 10, 21)
ax = plt.gca()
# grid "shades" (boxes)
w, h = xs[1] - xs[0], ys[1] - ys[0]
for i, x in enumerate(xs[:-1]):
    for j, y in enumerate(ys[:-1]):
        if i % 2 == j % 2: # racing flag style
            ax.add_patch(Rectangle((x, y), w, h, fill=True, color='#008610', alpha=.1))
# grid lines
for x in xs:
    plt.plot([x, x], [ys[0], ys[-1]], color='black', alpha=.33, linestyle=':')
for y in ys:
    plt.plot([xs[0], xs[-1]], [y, y], color='black', alpha=.33, linestyle=':')
plt.show()

exapmple

Sign up to request clarification or add additional context in comments.

3 Comments

There is also ax.vline and ax.hline
Will it be possible to shade these blocks?
I added racing flag style block shading and made the lines dotted.
2

It's much faster by using LineCollection:

import pylab as pl
from matplotlib.collections import LineCollection

x = np.linspace(0,100,100)
y = np.linspace(0,10,20) 

pl.figure(figsize=(12, 7))

hlines = np.column_stack(np.broadcast_arrays(x[0], y, x[-1], y))
vlines = np.column_stack(np.broadcast_arrays(x, y[0], x, y[-1]))
lines = np.concatenate([hlines, vlines]).reshape(-1, 2, 2)
line_collection = LineCollection(lines, color="red", linewidths=1)
ax = pl.gca()
ax.add_collection(line_collection)
ax.set_xlim(x[0], x[-1])
ax.set_ylim(y[0], y[-1])

enter image description here

1 Comment

Thanks, I wouldn't say the coding is faster or easier than the accepted answer though? Or do you mean the computational time?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.