0

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.

enter image description here

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.

1
  • 1
    What have you tried to do on your own? Commented Dec 30, 2022 at 17:03

1 Answer 1

1

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()

rectangles with randomm thickness

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

Comments

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.