我有一个使用Cartopy贴图作为坐标系的绘图.我想单击图上的任何位置,标记它,并返回单击点的纬度和经度位置.I am just not sure how to transform the event data back to map coordinates.

我已经把Matplotlib Transformations Tutorial看了一遍,但我仍然不清楚.绘图上的导航工具栏甚至以经度/经度显示坐标,但我不确定如何访问它.

import matplotlib.pyplot as plt
import cartopy.crs as ccrs

fig = plt.figure()
ax = plt.axes(projection=ccrs.Sinusoidal())
ax.set_extent([0,10,0,10], crs=ccrs.PlateCarree())
ax.gridlines(draw_labels=True,dms=True,x_inline=False,y_inline=False)

def onclick(event): 
    ax.scatter(event.xdata, event.ydata)
    fig.canvas.draw()

    # I want to print xdata and ydata in terms of Latitude and Longitude
    print(event.xdata,event.ydata)

cid = fig.canvas.mpl_connect('button_press_event', onclick)

Example Plot Output

推荐答案

要将值转换回纬度和经度浮点数,只需在PlateCarree投影上使用transform_point方法.在这里,我使用网格视图中的格式化器对值进行了格式化,但显然您可以按照自己的喜好进行格式化.

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.mpl.ticker import LatitudeFormatter, LongitudeFormatter

fig = plt.figure()
plot_proj = ccrs.Sinusoidal()
data_proj = ccrs.PlateCarree()
ax = plt.axes(projection=plot_proj)
ax.set_extent([0,10,0,10], crs=data_proj)
gl = ax.gridlines(draw_labels=True,dms=True,x_inline=False,y_inline=False)

def onclick(event): 
    ax.scatter(event.xdata, event.ydata)
    fig.canvas.draw()

    # Get hold of latitude and longitude as floats.
    lon, lat = data_proj.transform_point(event.xdata, event.ydata, plot_proj)
    # Format in degrees, minutes and seconds.
    print(gl.yformatter.format_data(lat), gl.xformatter.format_data(lon))

cid = fig.canvas.mpl_connect('button_press_event', onclick)

plt.show()

enter image description here

3°8′39.215″N 2°44′46.914″E
6°41′19.267″N 6°5′21.873″E
2°52′25.117″N 8°46′25.903″E

Python相关问答推荐

Locust请求中的Python和参数

对某些列的总数进行民意调查,但不单独列出每列

重新匹配{ }中包含的文本,其中文本可能包含{{var}

Python上的Instagram API:缺少client_id参数"

如何在Python中将returns.context. DeliverresContext与Deliverc函数一起使用?

在单个对象中解析多个Python数据帧

CommandeError:模块numba没有属性generated_jit''''

使用特定值作为引用替换数据框行上的值

如何在达到end_time时自动将状态字段从1更改为0

Flask运行时无法在Python中打印到控制台

Polars map_使用多处理对UDF进行批处理

如何求相邻对序列中元素 Select 的最小代价

使用类型提示进行类型转换

上传文件并使用Panda打开时的Flask 问题

启动线程时,Python键盘模块冻结/不工作

多索引数据帧到标准索引DF

大型稀疏CSR二进制矩阵乘法结果中的错误

如何在表单中添加管理员风格的输入(PDF)

函数()参数';代码';必须是代码而不是字符串

将Pandas DataFrame中的列名的长文本打断/换行为_STRING输出?