【问题标题】:Polygon containment test in matplotlib artistmatplotlib 艺术家中的多边形包含测试
【发布时间】:2014-06-17 11:01:38
【问题描述】:

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

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

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

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

FeatureArists 的默认收容测试是 None,所以我必须添加自己的收容测试。

如何在 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()

【问题讨论】:

  • 您可能希望将您的标题更改为更笼统的内容,以便问题被视为更有帮助并获得更多浏览量。

标签: python matplotlib polygon shapely cartopy


【解决方案1】:

好问题。可悲的是,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()

如果遏制测试的数量增加得比这个形状文件中的多得多,我也会查看"preparing" 每个国家/地区的几何图形,以获得相当大的性能提升。

HTH

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    相关资源
    最近更新 更多