In [1]:
#Download sample data from bokeh module if needed
import bokeh
#bokeh.sampledata.download()


#from https://stackoverflow.com/questions/27934885/how-to-hide-code-from-cells-in-ipython-notebook-visualized-with-nbviewer

from IPython.display import HTML

HTML('''<script>
code_show=true; 
function code_toggle() {
 if (code_show){
 $('div.input').hide();
 } else {
 $('div.input').show();
 }
 code_show = !code_show
} 
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''')
Out[1]:
In [3]:
#Eigth Example

#Geopandas is used to visualize and work with geographic data
import geopandas as geo
#json is used to format shapefiles to be readable with bokeh. 
import json
'''WMTSTileSource  uses OpenStreetMap as basemap for figure. 
GeoJSONDataSource creates a geo dataframe from JSON to use in Bokeh'''
from bokeh.models import WMTSTileSource, GeoJSONDataSource, HoverTool

#other modules needed
from bokeh.io import output_notebook, show, output_file
from bokeh.plotting import figure


#Define workspace to simplify coding
#wksp = r"P:\NRE_5585\DiFalcoProject"
wksp = "/Users/steven/Desktop/DiFalcoProject"

#shapefile containing the town of Mansfield polygon
#town = geo.read_file('%s\Mansfieldproj.shp'%wksp)
town = geo.read_file('%s/MansfieldLine.shp'%wksp).rename(
    columns={'IMS_LEGEND': 'name'})

#bike trails within this region of CT, rename trailnames for hovertool use
bike = geo.read_file("%s/BikeTrails.shp"%wksp).rename(
    columns={'TRAILNAME': 'name'})

#Joushua's Trust Trails within Mansfield CT, rename trailnames for hovertool use
JTtrails = geo.read_file ("%s/JTproj.shp"%wksp).rename(
    columns={'ident': 'name'})

#Town trails within Mansfield CT, rename trailnames for hovertool use
TownTrails= geo.read_file("%s/Total_Trails.shp"%wksp).rename(
    columns={'Trail_Name':'name'})

#Defining figure, Bokeh maps run on mercator scale
p = figure(title = 'Hiking Trails Mansfield', plot_height = 700 , plot_width = 950, 
           x_range=(-8060000, -8030000), y_range=(5120000, 5138000),
          x_axis_type="mercator", y_axis_type="mercator")

#Title font size increased
p.title.text_font_size = "20pt"

"""Creating a json and using this in the GeoJSONDataframe seems to work better 
than other examples that create a function that extracts the X and Y from the 
shapely geometry column created with reading in through geopandas  """

#Loop to go through trails and create multi-line glyphs and input into figure.
for data, name, color in zip([bike, JTtrails, TownTrails], 
                             ["Bike Trails", "Joshuas Trust", "Town Trails"], 
                             ["Red", "Purple", "Orange"]):
    #define coordinate system from a correctly projected shapefile (done in Arc)
    CRS=JTtrails.crs 
    #setting geometry of trail to this projection
    data['geometry'] = data['geometry'].to_crs(crs=CRS) 
    #creating and loading a json file from data source
    data_json = json.loads(data.to_json()) 
    data_jData = json.dumps(data_json) #writing created json file 
    #setting geoJSON dataframe with json file just created
    geosource_data = GeoJSONDataSource(geojson= data_jData) 
    #to read polyline shapefiles, a multi_line glyph is used to read the 
    #locations of the line from the geoJSON datasource
    p.multi_line(xs='xs',ys='ys', source = geosource_data, legend = name, 
                 line_width = 2, color = color)
      
#Loop to go through polygon shapefile to create a patch glyph
for data, name, color in zip([town], ["Mansfield"], ["Black"]):
    CRS=JTtrails.crs
    data['geometry'] = data['geometry'].to_crs(crs=CRS)
    data_json = json.loads(data.to_json())
    data_jData = json.dumps(data_json)    
    geosource_data = GeoJSONDataSource(geojson= data_jData)
    #patches is the glyph used to plot polygons into figure
    p.multi_line('xs','ys', source = geosource_data, legend= name, color = color, line_width = 3)

#hovertool information to identify trail by name column, 
#mode = mouse reads trailname at crosshairs location
hover = HoverTool(tooltips=[("Name", "@name")],mode='mouse')
#adds this hovertool with specified conditions above
p.add_tools(hover)

#adds a background map from open street map
wmts= WMTSTileSource(url='http://c.tile.openstreetmap.org/{Z}/{X}/{Y}.png')
p.add_tile(wmts)

#Creates a clickable legend 
p.legend.location = "top_left"
p.legend.label_text_font_size = "14pt"
p.legend.click_policy= "hide"

#output_file("MansfieldHikingTrails.html") #to create html of this figure
output_notebook()
show(p)
Loading BokehJS ...
In [4]:
#Geopandas is used to visualize and work with geographic data
import geopandas as geo
#json is used to format shapefiles to be readable with bokeh. 
import json

from bokeh.models import GeoJSONDataSource, HoverTool

#terrain map to be used as background tile
from bokeh.tile_providers import STAMEN_TERRAIN

#imports color palette with a list of different colors in a range
from bokeh.palettes import Plasma256

#This adds specific pattern of adding color from column in shapefile
from bokeh.transform import factor_cmap

#other modules needed
from bokeh.io import output_notebook, show #output_file
from bokeh.plotting import figure


#Define workspace to simplify coding
wksp = "/Users/steven/Desktop/DiFalcoProject"

#shapefile containing the town of Mansfield polygon
town = geo.read_file('%s/Mansfieldproj.shp'%wksp).rename(columns={'TOWN': 'PAR_ID'})

#open space clipped to Mansfield CT
openSpace = geo.read_file('%s/OpenSpaceMansfieldClip.shp'%wksp)

#DEEP Open Space for surrounding towns 
deep = geo.read_file("%s/OpenSpaceSurrounding.shp"%wksp)


#Defining figure, Bokeh maps run on mercator scale
p = figure(title = 'Open Space Mansfield', plot_height = 700 , plot_width = 950, 
           x_range=(-8055000, -8030000), y_range=(5120000, 5138000),
          x_axis_type="mercator", y_axis_type="mercator")

#Title font size increased
p.title.text_font_size = "20pt"


'''applies colors for each polygon based on parcel ID, those without Parcel 
ID in openSpace will be printed grey
interestingly, there are some parcels like those on border of Coventry that connect 
to parcels with boundries across the two towns'''

#define factors in which colors will be applied
factors = list(set(openSpace['PAR_ID']))
color = factor_cmap(field_name="PAR_ID",palette=Plasma256, factors=factors, nan_color="Grey")

#Loop to go through polygon shapefile to create a patch glyph
for data, name, color in zip([openSpace, deep], 
                             ["Protected Open Space", "Other Towns"], 
                             [color, color]):
    CRS=town.crs
    data['geometry'] = data['geometry'].to_crs(crs=CRS)
    data_json = json.loads(data.to_json())
    data_jData = json.dumps(data_json)    
    geosource_data = GeoJSONDataSource(geojson= data_jData)
    #patches is the glyph used to plot polygons into figure
    p.patches('xs','ys', source = geosource_data, legend= name, 
              color = color, line_width = 3, fill_alpha = 0.4)

#add town layer into figure    
town_json = json.loads(town.to_json())
town_jData = json.dumps(town_json)    
geosource_town = GeoJSONDataSource(geojson= town_jData)
p.patches('xs', 'ys', source=geosource_town, legend="Town", 
          color="Black", line_width= 3, fill_alpha=0.0)

#adds a background map 
p.add_tile(STAMEN_TERRAIN)

"""To turn off hovertool when using figure, 
click second to last tab on right(Hover)"""

hover = HoverTool(tooltips=[("Parcel ID", "@PAR_ID")],mode='mouse')
#adds this hovertool with specified conditions above
p.add_tools(hover)


#Creates a clickable legend 
p.legend.location = "top_left"
p.legend.label_text_font_size = "14pt"
p.legend.click_policy= "hide"

#output_file("MansfieldOpenSpace.html") #to create html of this figure
output_notebook()
show(p)
Loading BokehJS ...
In [ ]: