Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple lines on a plot using Matplotlib

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The expected output is

enter image description here

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading