我正在尝试在世界地图上添加一个图例。每一点都是来自不同推文的不同类型的设备。
这是我的代码:
import geocoder
import json
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
def openJSON(file, path):
with open(path + file + '.json', 'r') as fp:
data = json.load(fp)
return data
def App_users(data):
android_users = []
iphone_users = []
other_users = []
#3 types of users: Android, Iphone and others:
for a, b, c, d in data:
if "Twitter for Android" in d:
android_users.append([a, b])
elif "Twitter for iPhone" in d:
iphone_users.append([a, b])
else:
other_users.append([a, b])
data = (android_users, iphone_users, other_users)
return data
if __name__ == '__main__':
posXY_add = []
for d in data[0:50]:
if d["user"]["location"] != None:
g = geocoder.google(d["user"]["location"])
if g.latlng != None:
a = g.latlng + [g.address] + [str(d["source"])]
posXY_add.append(a)
data = App_users(posXY_add)
map = Basemap(llcrnrlat=-70, urcrnrlat=70,
llcrnrlon=-180, urcrnrlon=180, epsg=3395)
map.arcgisimage(service='ESRI_Imagery_World_2D', xpixels = 1500, verbose= True)
colors = ['r', 'g', 'b']
increment = 0
for app in data:
for item in app:
if len(item) == 2:
lat, lon = item[0], item[1]
x, y = map(lon, lat)
map.plot(x, y, colors[increment] + 'o')
increment += 1
plt.title("Geo-position Twitter Devices")
plt.show()
您有什么建议来改善我的地图吗?不同的颜色,不同的地图?我正在使用Pycharm的Python 2.7。我的样本数据是:
([[21.8974003, 83.39496319999999], [40.2671941, -86.1349019], [10.4805937, -66.90360629999999]], [[50.719164, -1.880769], [37.0903748, -94.5134078], [44.9862701, -93.39398279999999], [47.6062095, -122.3320708], [-27.4697707, 153.0251235], [20.593684, 78.96288]], [[43.2648545, -79.9492978], [39.1767262, -94.4867155], [33.7489954, -84.3879824], [39.7392358, -104.990251], [38.8761634, -77.0337777], [41.0082376, 28.9783589], [36.0753128, -95.95646269999999], [36.0595387, -95.90582429999999], [29.7604267, -95.3698028], [21.3014947, 106.6291304], [21.3014947, 106.6291304], [-16.6868982, -49.2648114], [10.4805937, -66.90360629999999], [45.037149, -92.825929], [33.760818, -78.967556], [45.49340369999999, -73.82329179999999], [39.750545, 37.0150217]])
传说的一部分:它是你把传说编成了一情节以同样的方式-只需调用plt.legend()
与m.plot()
具有label
参数。因此,在您的情况下,它将是:
handle_dict = {
"Andriod" : 0,
"iPhone" : 0,
"Other" : 0
}
colors = ['r', 'g', 'b']
increment = 0
for app in data:
for item in app:
if len(item) == 2:
lat, lon = item[0], item[1]
x, y = map(lon, lat)
map.plot(x, y, colors[increment] + 'o', label =
handle_dict[type_phone] if handle_dict[type_phone] == 0
else "_no-legend_")
handle_dict[type_phone] += 1
increment += 1
plt.legend()
plt.title("Geo-position Twitter Devices")
plt.show()
您还必须修改代码以标识要绘制的电话的类型(因此有变量type_phone
)。
这是有关图例以修改图例的文档的链接。
使地图变得更好:就我个人而言,我喜欢使用map.shadedrelief()
这些世界视图-它不那么暗map.bluemarble()
,您可以轻松地更好地看到这些点。map.arcgisimage()
此处实际上不需要参数,因为您拥有的是世界视图而不是放大视图-如果使用内置函数,它会更快地生成地图。我还将添加markeredgewidth
参数以map.plot()
使标记边缘宽度为零以外的值,因为现在您的点看起来就像它们与背景融合在一起。这会使您的点更加突兀。
哦-如果可以的话,也花点时间升级到Python 3。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句