wosker4yan
wosker4yan

Reputation: 187

How to unpack list of lists into x and y values for plotting a polygon?

I have a list of points that

import matplotlib.pyplot as plt

polygons = [[(5.0, 0.05), (10.0, 0.05), (10.0, -0.05), (5.0, -0.05)],
 [(0.0, 0.05), (5.0, 0.05), (5.0, -0.05), (0.0, -0.05)]]

coord = []
for item in polygons:
    coord.extend(item)
coord.append(coord[0]) #repeat the first point to create a 'closed loop'
xs, ys = zip(*coord) #create lists of x and y values

plt.figure()
plt.fill(xs,ys,'k') 
plt.ylim(-1, 1)
plt.xlim(0, 10)
plt.show()

And get the following picture: enter image description here which is wrong the plot should look like this, two rectangles next to each other: enter image description here

How can I loop through the list in a correct way and assign the values to corresponding x and y to plot the correct image?

Upvotes: 2

Views: 415

Answers (2)

wosker4yan
wosker4yan

Reputation: 187

This worked , but the problem is that the plot is not uniform. There is a boundary between the first polygon and the second one. Now the question is how to fill uniformely so there is no boundary.

import matplotlib.pyplot as plt

polygons = [[(5.0, 0.05), (10.0, 0.05), (10.0, -0.05), (5.0, -0.05)],
 [(0.0, 0.05), (5.0, 0.05), (5.0, -0.05), (0.0, -0.05)]]

for item in polygons:
        xs, ys = zip(*item)
        plt.fill(xs,ys, 'k')


plt.show()

enter image description here

Upvotes: 0

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

It's a problem of points ordering. A possible approach is to sort your coordinates using topological sort (please install networkx to do so):

import networkx as nx

G = nx.DiGraph()
for polygon in polygons:
    G.add_edges_from(zip(polygon[:-1], polygon[1:]))
coord = list(nx.topological_sort(G))
coord.append(coord[0])

And now you can plot coord.

Upvotes: 1

Related Questions