How to draw polygons with Python? How to draw polygons with Python? python python

How to draw polygons with Python?


Using matplotlib.pyplot

import matplotlib.pyplot as pltcoord = [[1,1], [2,1], [2,2], [1,2], [0.5,1.5]]coord.append(coord[0]) #repeat the first point to create a 'closed loop'xs, ys = zip(*coord) #create lists of x and y valuesplt.figure()plt.plot(xs,ys) plt.show() # if you need...


Another way to draw a polygon is this:

import PIL.ImageDraw as ImageDrawimport PIL.Image as Imageimage = Image.new("RGB", (640, 480))draw = ImageDraw.Draw(image)# points = ((1,1), (2,1), (2,2), (1,2), (0.5,1.5))points = ((100, 100), (200, 100), (200, 200), (100, 200), (50, 150))draw.polygon((points), fill=200)image.show()

Note that you need to install the pillow library. Also, I scaled up your coordinates by the factor of 100 so that we can see the polygon on the 640 x 480 screen.

Hope this helps.


Also, if you're drawing on window, use this:

dots = [[1,1], [2,1], [2,2], [1,2], [0.5,1.5]]from tkinter import Canvasc = Canvas(width=750, height=750)c.pack()out = []for x,y in dots:    out += [x*250, y*250]c.create_polygon(*out, fill='#aaffff')#fill with any color html or name you want, like fill='blue'c.update()

or also you may use this:

dots = [[1,1], [2,1], [2,2], [1,2], [0.5,1.5]]out = []for x,y in dots:    out.append([x*250, y*250])import pygame, sysfrom pygame.locals import *pygame.init()DISPLAYSURF = pygame.display.set_mode((750, 750), 0, 32)pygame.display.set_caption('WindowName')DISPLAYSURF.fill((255,255,255))#< ; \/ - colourspygame.draw.polygon(DISPLAYSURF, (0, 255,0), out)while True:    for event in pygame.event.get():        if event.type == QUIT:            pygame.quit()            sys.exit()    pygame.display.update()

First needs tkinter, second - pygame. First loads faster, second draws faster, if you put DISPLAYSURF.fill and than pygame.draw.polygon with a bit different coordinates into loop, it will work better than the same thing in tkinter. So if your polygon is flying and bouncing around, use second, but if it's just stable thing, use first. Also, in python2 use from Tkinter, not from tkinter.I've checked this code on raspberrypi3, it works.

------------EDIT------------

A little bit more about PIL and PYPLOT methods, see another answers:

matplotlib uses tkinter, maybe matplotlib is easier-to-use, but it's basically cooler tkinter window.

PIL in this case uses imagemagick, which is really good image editing tool

If you also need to apply effects on image, use PIL.

If you need more difficult math-figures, use matplotlib.pyplot.

For animation, use pygame.

For everything you don't know any better way to do something, use tkinter.

tkinter init is fast. pygame updates are fast. pyplot is just a geometry tool.