2

我有以下代码,最初是从这里收集的。,它使用matplotlib,shapely,cartopy来绘制世界地图。

单击时,我需要确定它是在哪个国家/地区进行的。我可以向pick_event画布添加回调,但是,它会在每个艺术家上调用。(cartopy.mpl.feature_artist.FeatureArtist,对应于一个国家)。

给定一个艺术家和一个具有 x、y 坐标的鼠标事件,我如何确定包含?

我试过artist.get_clip_box().contains了,但它不是真正的多边形,而是一个普通的矩形。

s的默认包含测试FeatureAristNone,所以我必须添加自己的包含测试。

如何在 FeatureArtist 中正确检查鼠标事件点的包含情况?

import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import cartopy.io.shapereader as shpreader
import itertools, pdb, subprocess, time, traceback
from itertools import *
import numpy as np
from pydoc import help as h

shapename = 'admin_0_countries'
countries_shp = shpreader.natural_earth(resolution='110m',
                                        category='cultural', name=shapename)

earth_colors = np.array([(199, 233, 192),
                                (161, 217, 155),
                                (116, 196, 118),
                                (65, 171, 93),
                                (35, 139, 69),
                                ]) / 255.
earth_colors = itertools.cycle(earth_colors)

ax = plt.axes(projection=ccrs.PlateCarree())


def contains_test ( artist, ev ):
    print "contain test called"
    #this containmeint test is always true, because it is a large rectangle, not a polygon
    #how to define correct containment test
    print "click contained in %s?: %s" % (artist.countryname, artist.get_clip_box().contains(ev.x, ev.y))
    return True, {}

for country in shpreader.Reader(countries_shp).records():
    # print country.attributes['name_long'], earth_colors.next()
    art = ax.add_geometries(country.geometry, ccrs.PlateCarree(),
                      facecolor=earth_colors.next(),
                      label=country.attributes['name_long'])

    art.countryname = country.attributes["name_long"] 
    art.set_picker(True)
    art.set_contains(contains_test)
    def pickit ( ev ):
        print "pickit called"
        print ev.artist.countryname



def onpick ( event ):
    print "pick event fired"

ax.figure.canvas.mpl_connect("pick_event", onpick)


def onclick(event):
    print 'button=%s, x=%s, y=%s, xdata=%s, ydata=%s'%(event.button, event.x, event.y, event.xdata, event.ydata)

ax.figure.canvas.mpl_connect('button_press_event', onclick)
plt.show()
4

1 回答 1

2

好问题。可悲的是,FeatureArtist 看起来不是 PathCollection 的子类,技术上应该如此,但它只是继承自 Artist。这意味着,正如您已经发现的那样,收容测试并未针对艺术家进行定义,事实上,在当前状态下解决问题并不是特别容易。

也就是说,我可能不会使用 matplotlib 包含功能来解决这个问题。鉴于我们有匀称的几何形状,而收容是这种工具的基础,我会跟踪创造艺术家的匀称几何形状,并对其进行审问。然后,我将简单地使用以下函数连接到 matplotlib 的通用事件处理:

def onclick(event):
    if event.inaxes and isinstance(event.inaxes, cartopy.mpl.geoaxes.GeoAxes):
        ax = event.inaxes
        target = ccrs.PlateCarree()
        lon, lat = target.transform_point(event.xdata, event.ydata,
                                          ax.projection)
        point = sgeom.Point(lon, lat)
        for country, (geom, artist) in country_to_geom_and_artist.items():
            if geom.contains(point):
                print 'Clicked on {}'.format(country)
                break

这个函数的难点是根据纬度和经度来掌握 x 和 y 坐标,但之后,它是一个简单的例子,即创建一个形状点并检查每个国家几何图形的包含情况。

完整的代码如下所示:

import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import cartopy.io.shapereader as shpreader
import cartopy.mpl.geoaxes
import itertools
import numpy as np
import shapely.geometry as sgeom


shapename = 'admin_0_countries'
countries_shp = shpreader.natural_earth(resolution='110m',
                                        category='cultural', name=shapename)

earth_colors = np.array([(199, 233, 192), (161, 217, 155),
                         (116, 196, 118), (65, 171, 93),
                         (35, 139, 69)]) / 255.
earth_colors = itertools.cycle(earth_colors)

ax = plt.axes(projection=ccrs.Robinson())

# Store a mapping of {country name: (shapely_geom, cartopy_feature)}
country_to_geom_and_artist = {}

for country in shpreader.Reader(countries_shp).records():
    artist = ax.add_geometries(country.geometry, ccrs.PlateCarree(),
                               facecolor=earth_colors.next(),
                               label=repr(country.attributes['name_long']))
    country_to_geom_and_artist[country.attributes['name_long']] = (country.geometry, artist)


def onclick(event):
    if event.inaxes and isinstance(event.inaxes, cartopy.mpl.geoaxes.GeoAxes):
        ax = event.inaxes
        target = ccrs.PlateCarree()
        lon, lat = target.transform_point(event.xdata, event.ydata,
                                          ax.projection)
        point = sgeom.Point(lon, lat)
        for country, (geom, artist) in country_to_geom_and_artist.items():
            if geom.contains(point):
                print 'Clicked on {}'.format(country)
                break

ax.figure.canvas.mpl_connect('button_press_event', onclick)
plt.show()

如果收容测试的数量增加得比这个形状文件中的多得多,我也会考虑“准备”每个国家的几何图形,以获得相当大的性能提升。

高温高压

于 2014-05-28T13:43:40.773 回答