Reputation: 311
I want to plot some shapes digitised from a graph and use them to classify my data (where they plot in XY's) but I'm falling at the first hurdle!
An example of the "Field" I want to plot as a shape is this:
Here's my code so far:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Polygon
df = pd.read_csv("FieldTest.csv") # the data (80 points)
x, y = df["X"], df["Y"] # x y coordinates
points = np.column_stack((x,y))
poly = Polygon(points, ec='k')
fig,ax = plt.subplots(1)
ax.add_patch(poly)
plt.show()
But this returns a blank plot:
The final figure has 10 of these polygons and I plan to use the contains_point
function to then evaluate if a point lies within the polygon. But that's next steps once I can work out how to plot the polygons first...
Here's the data on pastebin
Update - simonp2207 solved this, and I sorted the points in order:
Upvotes: 2
Views: 1451
Reputation: 183
The only reason you aren't seeing the displayed polygon is because matplotlib doesn't seem to autoscale the axes for patch objects. Therefore, I recommend autoscaling the axes yourself, e.g.:
ax.set_xlim(min(x), max(x))
ax.set_ylim(min(y), max(y))
However, a word of warning. Your polygon isn't regular because the order of the points provided to the Polygon class is ordered by x-coordinate. In the case of convex polygons, you can order the points by their angle from the polygon's central coordinate so that the path from vertex to vertex forms a neat border around the polygon. In a non-convex polygon however, I'm not entirely sure this holds!
Upvotes: 2