Reputation: 799
I am mapping some data, weather stations across London, and want to label each data point (the green points) with the names of the weather stations, for example, Bow, Westminster.
The map is created from a Geopandas dataframe, from the geometry column. Using this post: https://stackoverflow.com/questions/14432557/matplotlib-scatter-plot-with-different-text-at-each-data-point
I tried to annotate the text, but get the following error:
TypeError: 'Point' object is not iterable
.
Here is the map as it currently looks:
and here is the code:
f, ax = plt.subplots(1, figsize=(12, 12))
ax.set_title('Plot of London Grid for Learning weather stations with London boroughs and locations of Urban Mind datapoints', fontsize = 15)
boroughs.plot(alpha=1,edgecolor='w', facecolor='gray', linewidth=0.1, ax=ax)
london_umdata_geo.plot(ax=ax, marker="o",color="red",markersize=10.0,alpha=1.0, legend=True) #1,015 UM datapoints in London
stations_geo.plot(ax=ax, marker="X",color='green',markersize=20.0,alpha=1.0,legend=True)
n = stations_geo['Station Name'].tolist()
for i, txt in enumerate(n):
ax.annotate(txt, xy = stations_geo.loc[i,'geometry'])
plt.show()
The stations are the green points, other data points (which will not be labelled) are in red.
stations_geo
is a GeoPandas dataframe, which contains a geometry
column from which the points are plotted using matplotlib.
I am using a loop for the annotate method, supposedly to loop through the points in the geometry column and use these as the co-ordinates for the annotations, but matplotlib seems not to like the Point objects (which are Shapely points). However, these points are being used directly to create the green points in the first place, so I am not sure where I am going wrong.
Any help appreciated, thanks!
Upvotes: 0
Views: 963
Reputation: 339092
You already found the problem yourself ("matplotlib seems not to like the Point objects (which are Shapely points)").
So when confronted with such a problem, you may use the documentation as follows.
Look at the matplotlib documentation about what you may supply to the xy
argument of annotate
.
xy
: iterable
Length 2 sequence specifying the (x,y) point to annotate
Look at the object you have. In cause of doubt, use print(type(stations_geo.loc[i,'geometry']))
. It will show something like shapely.geometry.Point
. Look at the documentation of that object.
Identify a way to convert the one to the other. In this case you'll find
Coordinate values are accessed via
coords
,x
,y
, andz
properties.
Print stations_geo.loc[i,'geometry'].coords
, it will be a list of (a single) tuple(s).
So in order to convert a single shapely Point
to a python tuple, you would use its .coords
attribute and take the first (and only) element from that list.
xy = stations_geo.loc[i,'geometry'].coords[0]
Upvotes: 2