0

I am new to plotting images in python. Kindly appreciate your help in solving my issue. I have a list which contains dictionary of objects with list of X and Y coordinates of adjoining polygons. I was able to extract X and Y coordinates but when I plot the points using Matplotlib I am not getting proper shape of polygons.

import matplotlib.pyplot as plt

shapes = [{'shape_attributes': {'name': 'polygon', 'all_points_x': [35, 28, 27, 31, 40, 51, 62, 72, 74, 71, 65, 57, 41], 'all_points_y': [74, 55, 32, 16, 4, 6, 12, 35, 56, 74, 83, 86, 81]}, 'region_attributes': {}}, None, {'shape_attributes': {'name': 'polygon', 'all_points_x': [6, 16, 24, 44, 69, 77, 81, 82, 80, 76, 69, 62, 51, 26, 9, 7], 'all_points_y': [85, 77, 78, 83, 92, 100, 106, 115, 118, 120, 122, 125, 126, 112, 98, 92]}, 'region_attributes': {}}]

shapesCordinates = []
for shape in shapes:
    if shape is not None:
        x_cor = shape['shape_attributes']['all_points_x']
        y_cor = shape['shape_attributes']['all_points_y']
        for x, y in zip(x_cor, y_cor):
            shapesCordinates.append((x, y))
print(shapesCordinates)
shapesCordinates.append(shapesCordinates[0])
xs, ys = zip(*shapesCordinates)
plt.figure()
plt.plot(xs,ys) 
plt.show()
JohanC
  • 71,591
  • 8
  • 33
  • 66
mohit guru
  • 35
  • 7

1 Answers1

3

You might want to draw your polygons one by one. plt.plot will connect all the points in the list to the next, without leaving gaps.

import matplotlib.pyplot as plt

shapes = [{'shape_attributes': {'name': 'polygon', 'all_points_x': [35, 28, 27, 31, 40, 51, 62, 72, 74, 71, 65, 57, 41], 'all_points_y': [74, 55, 32, 16, 4, 6, 12, 35, 56, 74, 83, 86, 81]}, 'region_attributes': {}}, None, {'shape_attributes': {'name': 'polygon', 'all_points_x': [6, 16, 24, 44, 69, 77, 81, 82, 80, 76, 69, 62, 51, 26, 9, 7], 'all_points_y': [85, 77, 78, 83, 92, 100, 106, 115, 118, 120, 122, 125, 126, 112, 98, 92]}, 'region_attributes': {}}]
plt.figure()
for shape in shapes:
    if shape is not None:
        x_cor = shape['shape_attributes']['all_points_x']
        y_cor = shape['shape_attributes']['all_points_y']
        plt.plot(x_cor+x_cor[:1], y_cor+y_cor[:1])
plt.show()

example plot

JohanC
  • 71,591
  • 8
  • 33
  • 66