YohanRoth
YohanRoth

Reputation: 3253

plt.add_patch causes an error, how do I add a rectangle over a set of points?

All of my attempts failed. I tried to draw rectangle over set of points with pyplot but I keep getting different errors. Can someone help? I need to add rectangle of size width = 4 and height= 2sqrt(3)

import matplotlib.pyplot as plt
import matplotlib.patches as patches

def main():
    print("hello")

if __name__ == "__main__":
    x = []
    y = []

    for k in range(30):
      for l in range(30):
        x.append(4*k + 2*(l % 2))
        y.append(2*l*3**(1/2))

    rect = patches.Rectangle((0,0),4,2*3**(1/2),linewidth=1,edgecolor='b',facecolor='none') 
    plt.plot(x, y, 'ro')
    plt.axis([0, 10, 0, 10])


    #plt.add_patch(rect)

    plt.show()

Upvotes: 0

Views: 693

Answers (1)

kabanus
kabanus

Reputation: 25895

add_patch is an axes method, not something directly under pyplot. Just change your commented line to:

plt.gca().add_patch(rect)

gca() gets the current active axes in pyplot.

Upvotes: 2

Related Questions