I am generating a pattern with a square and coloring red and green at different locations. I would like to color the white spaces between different squares yellow and print the coordinates of these yellow squares. I have shown the output below including the full code. I would be grateful if somebody can help.
import matplotlib.pyplot as plt
# Define the grid size and the number of squares
grid_size = 4
square_size = 1 # Size of each square
gap = 0.1 # Gap between squares
# Create a new figure
plt.figure(figsize=(6, 6), dpi=80)
# Lists to store the coordinates of the rectangles
green_rectangles = []
red_rectangles = []
# Add yellow rectangles to fill the gaps before drawing the squares
for row in range(grid_size):
for col in range(grid_size):
# Calculate the coordinates for the bottom-left corner of the gap
x = col * (square_size + gap)
y = row * (square_size + gap)
# Create a yellow rectangle for the gap
if row < grid_size - 1:
plt.Rectangle((x, y + square_size), square_size, gap, edgecolor='none', facecolor='yellow')
if col < grid_size - 1:
plt.Rectangle((x + square_size, y), gap, square_size + gap, edgecolor='none', facecolor='yellow')
# Loop through rows and columns to draw the squares
for row in range(grid_size):
for col in range(grid_size):
# Calculate the coordinates for the bottom-left corner of the square
x = col * (square_size + gap)
y = row * (square_size + gap)
# Create a square using plt.Rectangle
rectangle = plt.Rectangle((x, y), square_size, square_size, edgecolor='black', facecolor='black')
plt.gca().add_patch(rectangle)
# Add green rectangles to fill the vertical gaps
for row in range(grid_size):
for col in range(grid_size - 1): # Exclude the last column
x = (col + 1) * (square_size + gap) - gap
y = row * (square_size + gap)
green_rectangle = plt.Rectangle((x, y), gap, square_size, edgecolor='none', facecolor='green')
plt.gca().add_patch(green_rectangle)
green_rectangles.append((x, y))
# Add red rectangles to fill the horizontal gaps
for row in range(grid_size - 1): # Exclude the last row
for col in range(grid_size):
x = col * (square_size + gap)
y = (row + 1) * (square_size + gap) - gap
red_rectangle = plt.Rectangle((x, y), square_size, gap, edgecolor='none', facecolor='red')
plt.gca().add_patch(red_rectangle)
red_rectangles.append((x, y))
# Print the coordinates of the red and green rectangles
print("Green rectangles:")
for coord in green_rectangles:
print(coord)
print("nRed rectangles:")
for coord in red_rectangles:
print(coord)
# Set the aspect of the plot to be equal, so squares appear as squares
plt.gca().set_aspect('equal')
# Set limits to accommodate the gaps
plt.xlim(0, grid_size * (square_size + gap))
plt.ylim(0, grid_size * (square_size + gap))
# Remove axis values
plt.gca().set_xticks([])
plt.gca().set_yticks([])
# Add grid lines for better visualization
plt.grid(True, which='both', linestyle='--', linewidth=0.5)
# Show the plot
plt.show()