首页 > 解决方案 > Matplotlib 的“ax1.add_collection(mylinecollection)”的底图等价物是什么?

问题描述

我正在从关系数据库中提取纬度/经度。点是线段的顶点,并且数据库表被组织成可以根据线号对点进行分组并根据点序号对点进行排序。具体来说,数据库表有以下字段:latitude、longitude、line_number、pt_order_number。

我已将所有线段拉入线集合。它使用 Matplotlib 按预期绘制ax1.add_collection(mylinecollection)。请注意,我使用线集合而不是ax1.plot(long,lat)循环,因为某些数据集有数千条线和数万个点(线集合更快更清晰)。

但是,我需要使用 Basemap 绘制这些线集(这样我就有了一个很好的阴影浮雕和比例尺)。底图无法通过.add_collection(),我不确定替代方案是什么。我在底图教程中找不到答案或明显的替代方法(但也许我错过了)。谢谢你的帮助。

当前代码:

# note linecollection variable produced in function; performs as expected with "ax1.add_collection(linecollection)"
latitude_range = [34.012965603200001, 34.721878621999998]
longitude_range = [-116.76151759999999, -116.33691841200002]

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from mpl_toolkits.basemap import Basemap

south, north = latitude_range[0], latitude_range[1]
west, east = longitude_range[0], longitude_range[1]
center = [(east+west)/2, (north+south)/2]

m = Basemap(llcrnrlon=west, llcrnrlat=south, urcrnrlon=east, urcrnrlat=north,
            resolution='c', epsg=4326,
            lon_0=center[0], lat_0=center[1])

m.arcgisimage(service = "World_Shaded_Relief", xpixels = 2000)
m.add_collection(linecollection) # throws error "AttributeError: 'Basemap' object has no attribute 'add_collection'"

plt.show()

标签: pythonpython-2.7matplotlibmatplotlib-basemap

解决方案


提供上述评论作为答案:

底图使用轴:

fig, ax = plt.subplots()
m = Basemap(..., ax=ax) 

在这个轴上你可以调用任何你喜欢的方法,例如

ax.add_collection(...)

确保首先将线集合的坐标转换为底图单位。


推荐阅读