I'm trying to draw a grid of cells using Matplotlib where each border (top, right, bottom, left) of a cell can have a different width (random number between 1 and 5). I should note also that the width and height of the inner area of a cell (white part) can vary between 15 and 20.
I want to know how to get the coordinates of each cell in order to avoid any extra space between the cells.
I tried several ideas however I did not get the right coordinates.
CodePudding user response:
You could draw thin rectangles with a random thickness, in horizontal and vertical orientation to simulate the edges of the cells:
import matplotlib.pyplot as plt
import random
fig, ax = plt.subplots()
color = 'darkgreen'
size = 20
m, n = 4, 3
for i in range(m 1):
for j in range(n 1):
if j < n: # thick vertical line
w1 = random.randint(0, 5)
w2 = random.randint(w1 1, 6)
ax.add_patch(plt.Rectangle((i * size - w1, j * size), w2, size, color=color, lw=0))
if i < m: # thick horizontal line
h1 = random.randint(0, 5)
h2 = random.randint(h1 1, 6)
ax.add_patch(plt.Rectangle((i * size, j * size - h1), size, h2, color=color, lw=0))
ax.autoscale() # fit all rectangles into the view
ax.axis('off') # hide the surrounding axes
plt.tight_layout()
plt.show()