Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make trapezoid and parallelogram in python using matplotlib

I have tried the following to produce a regular polygon:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, aspect='equal')
ax2.add_patch(
    patches.RegularPolygon(
        (0.5, 0.5),
        3,
        0.2,
        fill=False      # remove background
    )
)

fig2.savefig('reg-polygon.png', dpi=90, bbox_inches='tight')
plt.show()   

While this produces a triangle, I haven't found any way to produce a trapezoid and and a parallelogram.
Are there any commands to do this? Or can I transform the regular polygon into one of the other shapes?

like image 433
Vikas Bhargav Avatar asked Apr 04 '17 10:04

Vikas Bhargav


People also ask

Is matplotlib Pyplot same as matplotlib?

Pyplot is an API (Application Programming Interface) for Python's matplotlib that effectively makes matplotlib a viable open source alternative to MATLAB. Matplotlib is a library for data visualization, typically in the form of plots, graphs and charts.


2 Answers

You would need to use a matplotlib.patches.Polygon and define the corners yourself.

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

fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')

# Parallelogram
x = [0.3,0.6,.7,.4]
y = [0.4,0.4,0.6,0.6]
ax.add_patch(patches.Polygon(xy=list(zip(x,y)), fill=False))

# Trapez
x = [0.3,0.6,.5,.4]
y = [0.7,0.7,0.9,0.9]
ax.add_patch(patches.Polygon(xy=list(zip(x,y)), fill=False))

plt.show()  

enter image description here

For filled patches with size greater than 1 x 1

fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
ax.set_xlim(0, 3)
ax.set_ylim(0, 3)

x = [0, 1.16, 2.74, 2, 0]
y = [0, 2.8, 2.8, 0, 0]
ax.add_patch(patches.Polygon(xy=list(zip(x,y)), fill=True))

x = [0.3,0.6,.5,.4]
y = [0.7,0.7,0.9,0.9]
ax.add_patch(patches.Polygon(xy=list(zip(x,y)), fill=True, color='magenta'))

enter image description here

like image 196
ImportanceOfBeingErnest Avatar answered Sep 21 '22 19:09

ImportanceOfBeingErnest


One simple way to do it is creating a list of lists as the end points of the polygon( parallelogram/trapezoid) and plotting(or rather tracing) them.

import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, aspect='equal')

points = [[0.2, 0.4], [0.4, 0.8], [0.8, 0.8], [0.6, 0.4], [0.2,0.4]] #the points to trace the edges.
polygon= plt.Polygon(points,  fill=None, edgecolor='r')
ax2.add_patch(polygon)
fig2.savefig('reg-polygon.png', dpi=90, bbox_inches='tight')
plt.show() 

Also, note that you should use Polygon instead of RegularPolygon.

like image 43
ABcDexter Avatar answered Sep 19 '22 19:09

ABcDexter