1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > python怎么安装bokeh_Python如何使用bokeh包和geojson数据绘制地图

python怎么安装bokeh_Python如何使用bokeh包和geojson数据绘制地图

时间:2021-07-22 18:23:28

相关推荐

python怎么安装bokeh_Python如何使用bokeh包和geojson数据绘制地图

最近要绘制伦敦区地图,查阅了很多资料后最终选择使用bokeh包以及伦敦区的geojson数据绘制。

bokeh是基于python的绘图工具,可以绘制各种类型的图表,支持geojson数据的读取及绘制地图。

安装bokeh

$ pip install bokeh

软件版本

python-3.7.7bokeh-2.0.0

数据来源

伦敦地图数据来源于Highmaps地图数据集。下载的是英国的地图数据united-kindom.geo.json。需要对得到的数据进行预处理才能得到只含伦敦地区的数据。这需要对geojson数据的格式有一定的了解。在对数据进行处理之前,先看如何绘制英国地图。

绘制英国地图

from bokeh.plotting import curdoc, figure

from bokeh.models import GeoJSONDataSource

# 读入英国地图数据并传给GeoJSONDataSource

with open("united-kindom.geo.json", encoding="utf8") as f:

geo_source = GeoJSONDataSource(geojson=f.read())

# 设置一张画布

p = figure(width=500, height=500)

# 使用patches函数以及geo_source绘制地图

p.patches(xs='xs', ys='ys', source=geo_source)

curdoc().add_root(p)

上述代码可以绘制出英国地图。将上述代码保存为test.py,在终端运行

$ bokeh serve --show test.py

这会自动打开浏览器,并显示英国地图。

运行结果如图:

获取伦敦地区数据

获取伦敦地区数据可以手动从united-kingdom.geo.json文件中筛选出伦敦的数据,也可以先用python先把数据过滤一遍,然后将数据传给bokeh。这需要对geojson文件格式有一定的了解,在此不详细介绍。

from bokeh.plotting import curdoc, figure

from bokeh.models import GeoJSONDataSource

import json

# 用json库读取数据

with open("united-kindom.geo.json", encoding="utf8") as f:

data = json.loads(f.read())

# 判断是不是伦敦地区数据

def isInLondon(district):

if 'type' in district['properties'] and 'london borough' in district['properties']['type'].lower():

return True

if 'type-en' in district['properties'] and 'london borough' in district['properties']['type'].lower():

return True

if 'woe-name' in district['properties'] and 'city of london' in district['properties']['woe-name'].lower():

return True

return False

# 过滤数据

data['features'] = list(filter(isInLondon, data['features']))

#

geo_source = GeoJSONDataSource(geojson=json.dumps(data))

p = figure(width=500, height=500)

p.patches(xs='xs', ys='ys', source=geo_source)

curdoc().add_root(p)

运行结果如图:

美化

上面的伦敦地图只是一个大概的轮廓,下面对地图添加一系列功能。

添加各区轮廓线

p.patches(xs='xs', ys='ys', fill_alpha=0.7, # 画轮廓线

line_color='white', # 线的颜色

line_width=0.5, # 线的宽度

source=geo_source)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。