使用plotly神器绘制地图(Python版--demo虽易,操作不易,且学且珍惜)
Hi,好久不见,我是翻滚的老鼠屎。步入二年级的老鼠屎看着师兄师姐找工作步履维艰,深感压力,然而无奈最近身体一直出问题,有心发奋却无力用功。回到****发现多了好多小伙伴,惊喜的同时更加有了动力。谢谢大家一直以来对老鼠屎的支持和鼓励,你们的爱是我的翅膀,给我穿越风雨的力量
上学期写过一篇关于地图制作的博客,这里介绍第二种方法,利用plotly绘制地图。然而博主研究的过程中遇到很多问题,到现在也未解决,所以在这里将结果和问题一起呈现,欢迎大神赐教
Plotly是一个用于做分析和可视化的在线平台,曾被网友称为“有史以来最牛逼”可视化神器,其功能强大到不仅与多个主流绘图软件的对接,而且还可以像Excel那样实现交互式制图,而且图表种类齐全。有关于python中使用plotly的介绍可以参考其官方文档。
一、安装
plotly的安装直接pip install即可。如果不成功,可以参考博主的旧博文进行安装。
二、地图上画线
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected='True')
#需要连线的点
nyc_london = [ dict(
type = 'scattergeo',
lat = [ 40.7127, 51.5072 ],
lon = [ -74.0059, 0.1275 ],
mode = 'lines',
line = dict(
width = 2,
color = 'blue',
),
) ]
#布局
layout = dict(
title = 'London to NYC Great Circle',
showlegend = False,
geo = dict(
resolution = 50,
showland = True,
showlakes = True,
landcolor = 'rgb(204, 204, 204)',
countrycolor = 'rgb(204, 204, 204)',
lakecolor = 'rgb(255, 255, 255)',
projection = dict( type="equirectangular" ),
coastlinewidth = 2,
lataxis = dict(
range = [ 20, 60 ],
showgrid = True,
tickmode = "linear",
dtick = 10
),
lonaxis = dict(
range = [-100, 20],
showgrid = True,
tickmode = "linear",
dtick = 20
),
)
)
fig = dict( data=nyc_london, layout=layout )
iplot( fig, validate=False, filename='d3-great-circle' )
上面是对其官方的demo的修改。官方demo满心欢喜想要运行时会报错。这里将其原先demo中引用的库
import plotly.plotly as py
改为
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected='True')
同时,将最后一句原本的"py.iplot..."改为"iplot...",代码可以在jupyter notebook上运行。效果如下(仅仅是截图,真正效果是交互性的,可以实现地图缩小、放大等功能):
三、地图上画气泡
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected='True')
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_us_cities.csv')
df.head()
df['text'] = df['name'] + '<br>Population ' + (df['pop']/1e6).astype(str)+' million'
limits = [(0,2),(3,10),(11,20),(21,50),(50,3000)]
colors = ["rgb(0,116,217)","rgb(255,65,54)","rgb(133,20,75)","rgb(255,133,27)","lightgrey"]
cities = []
scale = 5000
for i in range(len(limits)):
lim = limits[i]
df_sub = df[lim[0]:lim[1]]
city = dict(
type = 'scattergeo',
locationmode = 'USA-states',
lon = df_sub['lon'],
lat = df_sub['lat'],
text = df_sub['text'],
marker = dict(
size = df_sub['pop']/scale,
# sizeref = 2. * max(df_sub['pop']/scale) / (25 ** 2),
color = colors[i],
line = dict(width=0.5, color='rgb(40,40,40)'),
sizemode = 'area'
),
name = '{0} - {1}'.format(lim[0],lim[1]) )
cities.append(city)
layout = dict(
title = '2014 US city populations<br>(Click legend to toggle traces)',
showlegend = True,
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showland = True,
landcolor = 'rgb(217, 217, 217)',
subunitwidth=1,
countrywidth=1,
subunitcolor="rgb(255, 255, 255)",
countrycolor="rgb(255, 255, 255)"
),
)
fig = dict(data=cities, layout=layout)
iplot(fig, validate=False, filename='d3-bubble-map-populations')
这段代码同样是对其官方demo的修改,可以直接在jupyter notebook上运行成功,效果如下:
四、plotly调用mapbox绘制散点图
这里,首先要申请一个Mapbox Access Token,根据提示即可申请。之后,便可以写代码进行可视化。
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected='True')
mapbox_access_token ="xxx"
data = [
go.Scattermapbox(
lat=['38.91427','38.91538','38.91458',
'38.92239','38.93222','38.90842',
'38.91931','38.93260','38.91368',
'38.88516','38.921894','38.93206',
'38.91275'],
lon=['-77.02827','-77.02013','-77.03155',
'-77.04227','-77.02854','-77.02419',
'-77.02518','-77.03304','-77.04509',
'-76.99656','-77.042438','-77.02821',
'-77.01239'],
mode='markers',
marker=dict(
size=9
),
text=["The coffee bar","Bistro Bohem","Black Cat",
"Snap","Columbia Heights Coffee","Azi's Cafe",
"Blind Dog Cafe","Le Caprice","Filter",
"Peregrine","Tryst","The Coupe",
"Big Bear Cafe"],
)
]
layout = go.Layout(
autosize=True,
hovermode='closest',
mapbox=dict(
accesstoken=mapbox_access_token,
bearing=0,
center=dict(
lat=38.92,
lon=-77.07
),
pitch=0,
zoom=10
),
)
fig = dict(data=data, layout=layout)
iplot(fig, filename='Multiple Mapbox')
这里同样是对官方样例的修改,然而修改后在jupyter notebook中仍然报错。最后笔者是在kesci的运行环境中运行成功的。效果如下: