1

I'm trying to generate a grid of squares with a small offset between each and thought I would use my superior matplotlib skills. Unfortunately the output only shows one square, so I suspect that the matplotlib isn't getting the message to plot all the patch objects I am initializing, but despite much trawling of stackoverflow I cannot fix this issue.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.collections as coll

wid = 1
hei = 1
nrows = 5
ncols = 7
inbetween = 0.1

xx = np.arange(0, ncols, (wid+inbetween))
yy = np.arange(0, nrows, (hei+inbetween))

fig = plt.figure()
ax = plt.subplot(111, aspect='equal')

pat = []
for xi in xx:
    for yi in yy:
        sq = patches.Rectangle((xi, yi), wid, hei, fill=True)
        ax.add_patch(sq)

pc = coll.PatchCollection(pat)
ax.add_collection(pc)

plt.axis('off')
plt.show()
plt.savefig('test.png', dpi=90)

Any ideas as to what is going wrong?

driftingtides
  • 61
  • 1
  • 9

1 Answers1

1

There are two issues here. First, you only see (part of) one patch here, because the axes go from 0 to 1 and not up to ncols and nrows.

This can be counteracted by relimiting the axes

ax.relim()
ax.autoscale_view()

or by setting the limis manually, e.g. ax.axis([0,ncols+1,0,nrows+1]).

Second, the PatchCollection is not doing anything, because an empty list (pat=[]) is added to it. Either delete the two lines

pc = coll.PatchCollection(pat)
ax.add_collection(pc)

or replace ax.add_patch(sq) by pat.append(sq). Note that relim() does not work when using the PatchCollection and manually relimitting the axes would be required. enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Silly mistakes! I relimited the axes and added `pat.append(sq)` and it worked fine (apart from my other novice mistake of calling `plt.show()` before `plt.savefig()`. Thanks for the speedy answer. – driftingtides Jun 07 '17 at 16:46
  • ...so now you have each rectangle twice in the plot. (It shouldn't matter, but just that you are aware of it). – ImportanceOfBeingErnest Jun 07 '17 at 16:49
  • Thanks for pointing this out. I used `PatchCollection` to try to fix my first mistake but now I don't need it so I just use `ax.add_patch` in the `for` loop. – driftingtides Jun 07 '17 at 18:20