Python如何使用bokeh包和geojson数据绘制地图


Posted in Python onMarch 21, 2020

最近要绘制伦敦区地图,查阅了很多资料后最终选择使用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

这会自动打开浏览器,并显示英国地图。
运行结果如图:

Python如何使用bokeh包和geojson数据绘制地图

获取伦敦地区数据

获取伦敦地区数据可以手动从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)

运行结果如图:

Python如何使用bokeh包和geojson数据绘制地图

美化

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

添加各区轮廓线

p.patches(xs='xs', ys='ys', fill_alpha=0.7, # 画轮廓线
    line_color='white', # 线的颜色
    line_width=0.5,   # 线的宽度
    source=geo_source)

现在地图区域轮廓很清晰。

添加颜色

# 为每一个地区增加一个color属性
for i in range(len(data['features'])):
  data['features'][i]['properties']['color'] = ['blue', 'red', 'yellow', 'orange', 'gray', 'purple'][i % 6]
p.patches(xs='xs', ys='ys', fill_alpha=0.7,
    line_color='white',
    line_width=0.5,
    color="color",  # 增加颜色属性,这里的"color"对应每个地区的color属性
    source=geo_source)

现在地图五颜六色。

增加图注

import random
# 随机产生数据用于展示
for i in range(len(data['features'])):
  data['features'][i]['properties']['number'] = random.randint(0, 20_000)
p = figure(width=500, height=500,
    tooltips="@name, number: @number" # 使用tooltips生成图注,@+属性名称,这里的name是数据中原本有的,number是新近添加的。
  )

现在鼠标放到区域上时,会显示"区域名, number: 数字"。

去掉坐标轴与背景线

p.axis.axis_label = None
p.axis.visible = False
p.grid.grid_line_color = None

最终代码

from bokeh.plotting import curdoc, figure
from bokeh.models import GeoJSONDataSource
import json
import random
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']))
for i in range(len(data['features'])):
  data['features'][i]['properties']['color'] = ['blue', 'red', 'yellow', 'orange', 'gray', 'purple'][i % 6]
  data['features'][i]['properties']['number'] = random.randint(0, 20_000)

geo_source = GeoJSONDataSource(geojson=json.dumps(data))
p = figure(width=500, height=500,
    tooltips="@name, number: @number")
p.patches(xs='xs', ys='ys', fill_alpha=0.7,
    line_color='white',
    line_width=0.5,
    color="color",
    source=geo_source)

p.axis.axis_label = None
p.axis.visible = False
p.grid.grid_line_color = None

curdoc().add_root(p)

伦敦地图完成了

Python如何使用bokeh包和geojson数据绘制地图

总结

最开始想用pyecharts做的,但是pyecharts并没有伦敦的地图。折腾半天,最后只好自己找geojson数据来画地图。

找到了很多关于地图的数据和工具,比如上文中提到的highmap数据集,以及DataV.altas,这个工具可以可视化地提取中国区域的地图数据,但感觉比起自己找数据,画中国地图还是pyecharts来得实在。

数据最重要。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python使用socket远程连接错误处理方法
Apr 29 Python
python中字符串前面加r的作用
Jun 04 Python
解决pip install的时候报错timed out的问题
Jun 12 Python
python正则表达式匹配[]中间为任意字符的实例
Dec 25 Python
关于python3中setup.py小概念解析
Aug 22 Python
python中JWT用户认证的实现
May 18 Python
Python爬取YY评级分数并保存数据实现过程解析
Jun 01 Python
python框架flask入门之路由及简单实现方法
Jun 07 Python
简述python&pytorch 随机种子的实现
Oct 07 Python
matplotlib bar()实现百分比堆积柱状图
Feb 24 Python
pytorch 权重weight 与 梯度grad 可视化操作
Jun 05 Python
Python PIL按比例裁剪图片
May 11 Python
Spring Boot中使用IntelliJ IDEA插件EasyCode一键生成代码详细方法
Mar 20 #Python
python+opencv实现移动侦测(帧差法)
Mar 20 #Python
Java Spring项目国际化(i18n)详细方法与实例
Mar 20 #Python
Python 自由定制表格的实现示例
Mar 20 #Python
python实现opencv+scoket网络实时图传
Mar 20 #Python
python实现同一局域网下传输图片
Mar 20 #Python
python实现udp传输图片功能
Mar 20 #Python
You might like
PHP6 mysql连接方式说明
2009/02/09 PHP
mysql 查询指定日期时间内sql语句实现原理与代码
2012/12/16 PHP
基于PHP实现简单的随机抽奖小程序
2016/01/05 PHP
Yii2搭建后台并实现rbac权限控制完整实例教程
2016/04/28 PHP
PHP设计模式之模板模式定义与用法详解
2018/12/20 PHP
php设计模式之职责链模式定义与用法经典示例
2019/09/19 PHP
Yii框架应用组件用法实例分析
2020/05/15 PHP
Aster vs Newbee BO5 第一场2.19
2021/03/10 DOTA
javaScript 判断字符串是否为数字的简单方法
2009/07/25 Javascript
javascript offsetX与layerX区别
2010/03/12 Javascript
jQuery EasyUI API 中文文档 - Spinner微调器使用
2011/10/21 Javascript
jQuery对Select的操作大集合(收藏)
2013/12/28 Javascript
jquery获取html元素的绝对位置和相对位置的方法
2014/06/20 Javascript
Angularjs中UI Router的使用方法
2016/05/14 Javascript
引入JavaScript时alert弹出框显示中文乱码问题
2017/09/16 Javascript
深入理解Vue生命周期、手动挂载及挂载子组件
2017/09/27 Javascript
理理Vue细节(推荐)
2019/04/16 Javascript
使用 Vue cli 3.0 构建自定义组件库的方法
2019/04/30 Javascript
vue 自定义右键样式的实例代码
2019/11/06 Javascript
python发腾讯微博代码分享
2014/01/10 Python
Python脚本实现DNSPod DNS动态解析域名
2015/02/14 Python
Python爬虫实例爬取网站搞笑段子
2017/11/08 Python
微信小程序跳一跳游戏 python脚本跳一跳刷高分技巧
2018/01/04 Python
Python格式化输出%s和%d
2018/05/07 Python
Python 对输入的数字进行排序的方法
2018/06/23 Python
Python匿名函数及应用示例
2019/04/09 Python
对Pytorch神经网络初始化kaiming分布详解
2019/08/18 Python
python针对mysql数据库的连接、查询、更新、删除操作示例
2019/09/11 Python
手把手教你Python yLab的绘制折线图的画法
2019/10/23 Python
python 消除 futureWarning问题的解决
2019/12/25 Python
美国玛丽莎收藏奢华时尚商店:Marissa Collections
2016/11/21 全球购物
Vinatis德国:法国领先的葡萄酒邮购公司
2020/09/07 全球购物
SQL语言面试题
2013/08/27 面试题
中医药大学毕业生自荐信
2013/11/08 职场文书
大学本科毕业生的自我鉴定范文
2013/11/19 职场文书
安全检查验收制度
2014/01/12 职场文书