How to plot triangle ,square or any polygon shape in Python Matplotlib

 How to plot triangle ,square or any polygon shape in Python Matplotlib


Code

from matplotlib.pyplot import *
from numpy import *
n = eval(input('enter the no. of sides greater than 2: '))
t = arange(0,360+(360/(n)),360/(n))
#t = arange(0,360,360/n)
x = 10*sin(radians(t))
y=10*cos(radians(t))
plot(x,y)
axis('equal')


Let's try to understand how this code work
  • First we have import maptlotlib and numpy module
  • Then we ask enter the no. of sides you want to plot 
    Note: It must be greater than 2
  • t basically define the no. of point for the graph
  • then we use our circle equation to plot
    Note : Please watch how to plot a circle to understand it much better
  • Axis equal to make sure our graph looks correct
Interactive Coding in Python
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interactive
def sides(n):
    #n = eval(input('enter the no. of sides greater than 2: '))
    t = np.arange(0,360+(360/(n)),360/(n))
   # t = np.arange(0,360,360/n)
    x = 10*np.sin(np.radians(t))
    y=10*np.cos(np.radians(t))
    plt.plot(x,y)
    plt.axis('equal')
interactive_plot = interactive(sides , n= (3,20))
interactive_plot 






Post a Comment

0 Comments