Home > Mobile >  Multiple lines on a plot using Matplotlib
Multiple lines on a plot using Matplotlib

Time:07-14

I am generating 4 rectangles using ax.add_patch. I want to connect these rectangles using single lines as shown in the expected output.

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

fig,ax = plt.subplots(1)
n=2
for i in range(0,n):
    for j in range(0,n):
        rect = mpl.patches.Rectangle((200 200*i,200 200*j),10*n, 10*n, linewidth=1, edgecolor='black', facecolor='black')
        ax.add_patch(rect)

ax.set_xlim(left = 0, right = 220*n)
ax.set_ylim(bottom = 0, top = 220*n)
plt.show()

The current output is

enter image description here

The expected output is

enter image description here

CodePudding user response:

Try placing vertical and horizontal lines at those positions

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

fig,ax = plt.subplots(1)
n=2
for i in range(0,n):
    for j in range(0,n):
        rect = mpl.patches.Rectangle((200 200*i,200 200*j),10*n, 10*n, linewidth=1, edgecolor='black', facecolor='black')
        ax.add_patch(rect)
    ax.hlines(200 200*i 10, 200, 400, zorder=0)
    ax.vlines(200 200*i 10, 200, 400, zorder=0)

ax.set_xlim(left = 0, right = 220*n)
ax.set_ylim(bottom = 0, top = 220*n)
plt.show()

enter image description here

CodePudding user response:

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

fig,ax = plt.subplots(1)
w = 10
xy = 200
n=2
coords = []

ax.add_patch(mpl.patches.Rectangle((xy w,xy w),xy,xy, linewidth=1, fill=0, edgecolor='blue'))

for i in range(0,n):
    for j in range(0,n):
        rect = mpl.patches.Rectangle((xy xy*i,xy xy*j),w*n, w*n, linewidth=1, edgecolor='black', facecolor='black')
        ax.add_patch(rect)
        coords.append([rect.get_xy(), rect.get_height(), rect.get_width()])

ax.set_xlim(left = 0, right = 220*n)
ax.set_ylim(bottom = 0, top = 220*n)
plt.show()

Output enter image description here

  • Related