user3578925
user3578925

Reputation: 931

matplotlib annotate basemap in data coordinates

I have a hammer projection plot which I am trying to add text at the center of the plot (latitude = 0, longitude = 0). For some reason, the string '0' is plotted at the bottom left of the figure.

I have the following code.

from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm


#data points
ra = [25,20,21]
dec = [25,20,21]

fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8])

# Get the hammer projection map
m = Basemap(projection='hammer',lon_0 = 0, rsphere = 1.0)
m.drawparallels(np.arange(-90.,90.,30.),labels=[1,0,0,0]) # draw parallels
m.drawmeridians(np.arange(-180.,180.,60.)) # draw meridians

m.plot(ra,dec,marker='o',linestyle='None',markersize=1,latlon=True)
ax.annotate('0', xy=(0, 0), xycoords='data',xytext = (0,0),textcoords='data')

plt.show()

I am also attaching the figure, where it is evident that the location of the char '0' is in the wrong place. Any ideas?

enter image description here

Upvotes: 2

Views: 6022

Answers (2)

Chien Nguyen
Chien Nguyen

Reputation: 179

In addition to @Suever's answer above, a one-liner alternative is possible using tuple unpacking:

plt.text(*m(lon, lat))

We just remember:

  • text (or annotate) uses x, y coordinates
  • transformation from long-lat to x-y is made with m(lon,lat) (where m is your Basemap object).

Upvotes: 0

Suever
Suever

Reputation: 65430

You have to first convert your latitude/longitude coordinates to their equivalent x,y coordinates using your Basemap instance. matplotlib does not do this automatically for you because it doesn't know anything about latitude and longitude.

# Convert from latitude/longitude to x,y
x, y = m(0,0)
ax.annotate('0', xy=(x, y), xycoords='data', xytext=(x, y), textcoords='data')

enter image description here

Within their own documentation, they demonstrate the use of text rather than annotate since there are no arrows.

x, y = m(0,0)
plt.text(x, y, '0')

Upvotes: 5

Related Questions