另一种选择是使用gmplot。它基本上是一个围绕 Google Maps javascript API 的 python 包装器,允许您生成 .html 文件,这些文件在后台使用地图呈现您的地块。
在这里,我用它来绘制卫星图像背景下的随机游走(默认情况下不支持这种地图类型,但让它工作起来非常简单):
from gmplot import GoogleMapPlotter
from random import random
# We subclass this just to change the map type
class CustomGoogleMapPlotter(GoogleMapPlotter):
def __init__(self, center_lat, center_lng, zoom, apikey='',
map_type='satellite'):
super().__init__(center_lat, center_lng, zoom, apikey)
self.map_type = map_type
assert(self.map_type in ['roadmap', 'satellite', 'hybrid', 'terrain'])
def write_map(self, f):
f.write('\t\tvar centerlatlng = new google.maps.LatLng(%f, %f);\n' %
(self.center[0], self.center[1]))
f.write('\t\tvar myOptions = {\n')
f.write('\t\t\tzoom: %d,\n' % (self.zoom))
f.write('\t\t\tcenter: centerlatlng,\n')
# This is the only line we change
f.write('\t\t\tmapTypeId: \'{}\'\n'.format(self.map_type))
f.write('\t\t};\n')
f.write(
'\t\tvar map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);\n')
f.write('\n')
initial_zoom = 16
num_pts = 40
lats = [37.428]
lons = [-122.145]
for pt in range(num_pts):
lats.append(lats[-1] + (random() - 0.5)/100)
lons.append(lons[-1] + random()/100)
gmap = CustomGoogleMapPlotter(lats[0], lons[0], initial_zoom,
map_type='satellite')
gmap.plot(lats, lons, 'cornflowerblue', edge_width=10)
gmap.draw("mymap.html")
您可以在浏览器中打开生成的 .html 文件,并像使用 Google 地图一样进行交互。
不幸的是,这意味着你不会得到一个漂亮的matplotlib 图形窗口或任何东西,所以为了生成一个图像文件,你需要自己截取屏幕截图或破解一些东西来为你呈现 HTML。
要记住的另一件事是,您可能需要Google Maps API key,否则您最终会像我一样得到一张丑陋的深色水印地图:
另外,由于您想将值描述为颜色,您需要手动将它们转换为颜色字符串并使用gmap.scatter() 方法。如果您对这种方法感兴趣,请告诉我,以便我尝试编写一些代码来做到这一点。
更新
这是一个支持将值编码为卫星图像散点图中颜色的版本。为了达到这个效果,我使用了matplotlib 的颜色图。您可以根据需要更改颜色图,请参阅选项列表 here。我还包含了一些代码来从文件apikey.txt 中读取 API 密钥,这允许每个研究人员在不更改代码的情况下使用自己的个人密钥(如果没有找到这样的文件,则像往常一样默认为没有 API 密钥)。
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from matplotlib.cm import ScalarMappable
from gmplot import GoogleMapPlotter
from random import random
class CustomGoogleMapPlotter(GoogleMapPlotter):
def __init__(self, center_lat, center_lng, zoom, apikey='',
map_type='satellite'):
if apikey == '':
try:
with open('apikey.txt', 'r') as apifile:
apikey = apifile.readline()
except FileNotFoundError:
pass
super().__init__(center_lat, center_lng, zoom, apikey)
self.map_type = map_type
assert(self.map_type in ['roadmap', 'satellite', 'hybrid', 'terrain'])
def write_map(self, f):
f.write('\t\tvar centerlatlng = new google.maps.LatLng(%f, %f);\n' %
(self.center[0], self.center[1]))
f.write('\t\tvar myOptions = {\n')
f.write('\t\t\tzoom: %d,\n' % (self.zoom))
f.write('\t\t\tcenter: centerlatlng,\n')
# Change this line to allow different map types
f.write('\t\t\tmapTypeId: \'{}\'\n'.format(self.map_type))
f.write('\t\t};\n')
f.write(
'\t\tvar map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);\n')
f.write('\n')
def color_scatter(self, lats, lngs, values=None, colormap='coolwarm',
size=None, marker=False, s=None, **kwargs):
def rgb2hex(rgb):
""" Convert RGBA or RGB to #RRGGBB """
rgb = list(rgb[0:3]) # remove alpha if present
rgb = [int(c * 255) for c in rgb]
hexcolor = '#%02x%02x%02x' % tuple(rgb)
return hexcolor
if values is None:
colors = [None for _ in lats]
else:
cmap = plt.get_cmap(colormap)
norm = Normalize(vmin=min(values), vmax=max(values))
scalar_map = ScalarMappable(norm=norm, cmap=cmap)
colors = [rgb2hex(scalar_map.to_rgba(value)) for value in values]
for lat, lon, c in zip(lats, lngs, colors):
self.scatter(lats=[lat], lngs=[lon], c=c, size=size, marker=marker,
s=s, **kwargs)
initial_zoom = 12
num_pts = 40
lats = [37.428]
lons = [-122.145]
values = [random() * 20]
for pt in range(num_pts):
lats.append(lats[-1] + (random() - 0.5)/100)
lons.append(lons[-1] + random()/100)
values.append(values[-1] + random())
gmap = CustomGoogleMapPlotter(lats[0], lons[0], initial_zoom,
map_type='satellite')
gmap.color_scatter(lats, lons, values, colormap='coolwarm')
gmap.draw("mymap.html")
作为示例,我使用了一系列单调递增的值,这些值在 coolwarm 颜色图中很好地从蓝色阴影映射到红色: