Geopandas+Bokeh可视化GIS数据:HoverTool高程值转普通浮点数
解决Bokeh HoverTool中浮点数显示为科学计数法的问题
当然可以实现让高程值以简洁浮点数格式显示的需求!你之前尝试用float('@elev')报错,是因为Bokeh的HoverTool工具提示不支持直接在字段引用里用Python内置函数处理——得用Bokeh本身提供的字段格式化语法来搞定这个问题。
具体解决方案
在HoverTool的tooltips列表里,给@elev字段添加格式化规则就行,格式是@elev{格式化字符串},常用的格式选项有:
- 保留固定小数位数:比如
@elev{0.2f},会把1382.770000显示成1382.77 - 自动去除末尾多余零:用
@elev{,f},同样会把1382.770000显示成1382.77,若遇到整数型高程(如1000.000000)则会显示为1000
修改后的核心代码片段
把你原来的HoverTool定义改成下面这样即可:
#Add hover tools hover = HoverTool(tooltips = [ ('Climate Zone','@cZone'), ('County','@Name'), ('USAF','@USAF'), ('Elevation','@elev{0.2f}') # 这里是修改的核心部分 ])
完整修改后的代码
import pandas as pd import geopandas as gpd import json import bokeh.io from bokeh.io import output_notebook, show, output_file from bokeh.plotting import figure, show from bokeh.models import GeoJSONDataSource, HoverTool # prevent Bokeh from saving sketch into file / opening in a new tab bokeh.io.reset_output() bokeh.io.output_notebook() shapefile = 'data/USA Counties 20m/cb_2017_us_county_20m_with_cZone_USAF_coordinates_elevations.shp' #Read shapefile using Geopandas gdf = gpd.read_file(shapefile)[['CZONE', 'NAME', 'geometry','USAF','xcoord','ycoord','ELEV_IN_M']] #Rename columns. gdf.columns = ['cZone', 'Name', 'geometry','USAF','Long','Lat','elev'] #Reset index gdf = gdf.reset_index(drop=True) #Read data to json. json_raw = json.loads(gdf.to_json()) #Convert to String like object. json_data = json.dumps(json_raw) #Input GeoJSON source that contains features for plotting. geosource = GeoJSONDataSource(geojson = json_data) #Add hover tools - 修改了elev的显示格式 hover = HoverTool(tooltips = [ ('Climate Zone','@cZone'), ('County','@Name'), ('USAF','@USAF'), ('Elevation','@elev{0.2f}') ]) #Create figure object. p = figure(title = 'USA Climate Zone Map by County', plot_height = 450 , plot_width = 800, toolbar_location = "below") p.add_tools(hover) #Add patch renderer to figure. p.patches('xs','ys', source = geosource, line_color = 'black', line_width = 0.25, fill_alpha = 1) # Display figure & widget show(p)
原理说明
Bokeh的工具提示支持在字段引用(@字段名)后追加格式化字符串,语法和Python的str.format()类似,通过这种方式可以直接控制数值的显示样式,不需要在数据预处理阶段修改数值类型,也避免了直接调用Python函数导致的错误。
内容的提问来源于stack exchange,提问作者Noam Naveh
相关产品推荐
相关产品推荐

