Tanggal :September 27, 2020

py36. Drawing Polygons in Python

Spread the love

To draw polygons, we have to give vertices as we loop over the polygon counterclockwise.

We use a curve with roots of -1,0,+1. We divide the x-axis based on these roots (will become 4 shaded regions).

Using list comprehensions we go make loops in x_1, x_2, x_3 and x_4, the four divisions of x that we chose.


# ex36.py

from __future__ import print_function, division
import numpy as np
import matplotlib.pyplot as plt

def y(x):
return x**3 - x

x = np.arange(-1.5,1.51,.01)
tol = 0.01

x_1 = x[(x >= -1.5) & (x <= (-1+tol))]
x_2 = x[(x >= -1) & (x <= (0+tol))]
x_3 = x[(x >= 0) & (x <= (1+tol))]
x_4 = x[(x >= 1) & (x <= (1.5+tol))]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y(x),'b')
ax.axhline(0, color = 'm')
plt.xlim(-1.5,1.5)
plt.xlabel('x')
plt.ylabel('y(x)')
plt.title('y(x) = $x^3$ - x')

# Counter clockwise loops
verts_left_to_right = [(xv,y(xv)) for xv in x_1]
verts_right_to_left = [(xv,0) for xv in np.flipud(x_1)]
verts = verts_left_to_right + verts_right_to_left
poly = plt.Polygon(verts, color = 'violet')
ax.add_patch(poly)

verts_left_to_right = [(xv,0) for xv in x_2]
verts_right_to_left = [(xv,y(xv)) for xv in np.flipud(x_2)]
verts = verts_left_to_right + verts_right_to_left
poly = plt.Polygon(verts, color = 'green')
ax.add_patch(poly)

verts_left_to_right = [(xv,y(xv)) for xv in x_3]
verts_right_to_left = [(xv,0) for xv in np.flipud(x_3)]
verts = verts_left_to_right + verts_right_to_left
poly = plt.Polygon(verts, color = 'red')
ax.add_patch(poly)

verts_left_to_right = [(xv,0) for xv in x_4]
verts_right_to_left = [(xv,y(xv)) for xv in np.flipud(x_4)]
verts = verts_left_to_right + verts_right_to_left
poly = plt.Polygon(verts, color = 'yellow')
ax.add_patch(poly)

plt.show()

Output:

Share

Leave a Reply

Your email address will not be published. Required fields are marked *