简体   繁体   English

matplotlib 在数据坐标中标注底图

[英]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).我有一个锤子投影 plot,我试图在 plot(纬度 = 0,经度 = 0)的中心添加文本。 For some reason, the string '0' is plotted at the bottom left of the figure.由于某种原因,字符串“0”绘制在图的左下方。

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.我还附上了该图,很明显字符“0”的位置在错误的位置。 Any ideas?有任何想法吗?

在此处输入图像描述

You have to first convert your latitude/longitude coordinates to their equivalent x,y coordinates using your Basemap instance. 您必须先使用Basemap实例将纬度/经度坐标转换为等效的x,y坐标。 matplotlib does not do this automatically for you because it doesn't know anything about latitude and longitude. matplotlib不会自动为您执行此操作,因为它对纬度和经度一无所知。

# 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')

在此输入图像描述

Within their own documentation , they demonstrate the use of text rather than annotate since there are no arrows. 在他们自己的文档中 ,他们演示了text的使用而不是注释,因为没有箭头。

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

In addition to @Suever's answer above, a one-liner alternative is possible using tuple unpacking:除了上面@Suever 的回答之外,还可以使用元组解包进行单行替代:

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

We just remember:我们只记得:

  • text (or annotate ) uses x, y coordinates text (或annotate )使用 x, y 坐标
  • transformation from long-lat to xy is made with m(lon,lat) (where m is your Basemap object).从 long-lat 到 xy 的转换是使用m(lon,lat)进行的(其中m是您的 Basemap 对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM