I'm using Bokeh and Geopandas to plot an interactive map of Germany. Germany has total 16 states but the plot shows only 15. It does not display the map of Berlin, which is the capital city (Berlin is also a state). I'm using the shapefile as an input to plot the map. I have tried different shapefiles and looked for different solutions but I'm unable to find the root of the problem. Please have a look at the code and the output.
`
import pandas as pd
# Import geopandas package
import geopandas as gpd
# Read in shapefile and examine data
germany = gpd.read_file('Igismap/Germany_Polygon.shp')
pop_states = germany
vargeojson = pop_states.to_json()
import json
from bokeh.io import show, output_notebook
from bokeh.models import (ColumnDataSource,
GeoJSONDataSource, HoverTool,
LinearColorMapper)
from bokeh.layouts import column, row, widgetbox
from bokeh.plotting import figure
output_notebook()
# Input GeoJSON source that contains features for plotting
geosource = GeoJSONDataSource(geojson = vargeojson)
tools = "pan, wheel_zoom, box_zoom, reset"
p = figure(title = 'All states of Germany',
plot_height = 600 ,
plot_width = 600,
toolbar_location = 'right',
tools = tools)
p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None
# Add patch renderer to figure.
states = p.patches('xs','ys', source = geosource,
line_color = "grey",
line_width = 0.25,
fill_alpha = 1)
# Create hover tool
p.add_tools(HoverTool(renderers = [states],
tooltips = [('Lander','#name')]))
show(p)
`
Click here to see the output of above code.... and
Click here to see the desired output
Related
I'm learning Python applied to data science and I'm trying to create an interactive map of my city, Madrid (Spain), showing the last election results. All I'm doing is in this GitHub link:
https://github.com/BernardoJoseLlamasVerna/Madrid_Elections_2021
You will see draft operations and looking for the best way to represent my data on a map:
https://github.com/BernardoJoseLlamasVerna/Madrid_Elections_2021/blob/main/Madrid_Elections_2021.ipynb
I'm following an example found on Internet about Wisconsin elections and fixes perfectly with what I would like to do with my data. I have downloaded it and stored on my repo to show you what I'm trying:
https://github.com/BernardoJoseLlamasVerna/Madrid_Elections_2021/blob/main/maps.ipynb
I've tried to do the same with my data, but nothing appears (even errors). The code is as follows:
from bokeh.io import output_notebook
from bokeh.plotting import figure, ColumnDataSource
from bokeh.io import output_notebook, show, output_file
from bokeh.plotting import figure
from bokeh.models import GeoJSONDataSource, LinearColorMapper, ColorBar, HoverTool
from bokeh.palettes import brewer
output_notebook()
import json
# res_w_states["clinton_share"] = res_w_states["clinton"] / res_w_states["total"]
#Convert data to geojson for bokeh
wi_geojson=GeoJSONDataSource(geojson=data.to_json())
color_mapper = LinearColorMapper(palette = brewer['RdBu'][10], low = 0, high = 1)
color_bar = ColorBar(color_mapper=color_mapper, label_standoff=8,width = 500, height = 20,
border_line_color=None,location = (0,0), orientation = 'horizontal')
hover = HoverTool(tooltips = [ ('Municipio','#Municipio'),('P.P.', '#P.P.'),
('P.S.O.E.','#P.S.O.E.'),
('Votos Totales','#Votos Totales')])
p = figure(title="Elecciones Madrid 2021", tools=[hover])
p.patches("xs","ys",source=wi_geojson,
fill_color = {'field' :'P.P.', 'transform' : color_mapper})
p.add_layout(color_bar, 'below')
show(p)
I've been analysing wi_geojson comparing between mine and what I copied and they seem to follow the same structure.
**QUESTION: ** anyone could give me a hint about what is wrong with my code, data, etc?
Thank you for your help.
P.D.: if anyone could also post a link with better interactive mapping, I would be so glad.
Thanks to mosc9575 I could manage a solution...
The problem was the Bokeh version (1.3.4); once updated (2.3.2) I could figure out my map. Now I have to fix the municipalities names XDD.
I have a large dataset from which I am interested in this part:
temp lat long
7.1 47 13
19 49 16
I tried using folium:
import requests
from xml.etree import ElementTree
import folium
from folium.plugins import MarkerCluster
MarkerCluster()
map2 = folium.Map(location=[47.031, 13.001999], tiles='CartoDB dark_matter', zoom_start=11)
marker_cluster = folium.plugins.MarkerCluster().add_to(map2)
But I get SyntaxError: unexpected EOF while parsing.
Then I tried using bokeh by copy-pasting an Internet example just to see if it works:
from bokeh.io import output_file, output_notebook, show
from bokeh.models import (
GMapPlot, GMapOptions, ColumnDataSource, Circle, LogColorMapper, BasicTicker, ColorBar,
DataRange1d, PanTool, WheelZoomTool, BoxSelectTool
)
from bokeh.models.mappers import ColorMapper, LinearColorMapper
from bokeh.palettes import Viridis5
map_options = GMapOptions(lat=37.88, lng=-122.23, map_type="roadmap", zoom=6)
plot = GMapPlot(
x_range=bokeh.Range1d(), y_range=bokeh.Range1d(), map_options=map_options
)
plot.title.text = "Hey look! It's a scatter plot on a map!"
show(plot)
But I get NameError: name 'bokeh' is not defined.
Is there any other way to plot a point or to fix the errors?
I tried to reproduce your Folium example with the following code :
from folium.plugins import MarkerCluster
m = folium.Map(location=[47.031, 13.001999], zoom_start=5)
marker_cluster = MarkerCluster().add_to(m)
folium.Marker(
location=[47.031, 13.001999],
popup='Add popup text here.',
icon=folium.Icon(color='green', icon='ok-sign'),
).add_to(marker_cluster)
m
It works just well :
Maybe there is another part of your code which was triggering the EOS error. An EOS error usually occurs because of missing commas, parenthesis etc.
If you are interested in the different types of folium Markers, there is an official Notebook with interesting examples.
I'm running this in Jupyter Notebook. I'll attach my full code. I'm using a csv file from Kaggle to plot the cumulative coronavirus cases throughout different countries in the world.
Here's the link to the Kaggle dataset download: https://www.kaggle.com/sudalairajkumar/novel-corona-virus-2019-dataset
I'm using the "covid_19_data.csv" file.
import chart_studio.plotly as py
import plotly.graph_objs as go
import pandas as pd
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot, plot
init_notebook_mode(connected = True)
cf.go_offline()
df = pd.read_csv('covid_19_data.csv')
data = dict(type = 'choropleth',
locations = df['Country/Region'],
z = df['Confirmed'],
text = df['Province/State'],
colorbar = {'title':'Cases of COVID-19'} )
layout = dict(title = '2020 Global Coronavirus Cases', geo = dict(showframe = False, projection = {'type':'natural earth'}))
choromap = go.Figure(data = [data],layout = layout)
iplot(choromap)
The output is a gray map of the world. There is a legend with color, and a title as well. I'm confused why the data is not being plotted!
I created a small excel file listing the confirmed cases, deaths, and recovered cases of the Coronavirus here in the U.S, but I can't seem to get the choropleth map working.
Here's my code:
import pandas as pd
import chart_studio.plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
col_Names=["State", "Country", "Time Discovered", "Confirmed", "Deaths","Recovered"]
df = pd.read_csv("coronavirusUS.csv", names=col_Names)
data = dict(type='choropleth',
colorscale= 'magma',
locations = df['State'],
locationmode= 'USA-states',
z = df['Confirmed'],
text = df['Confirmed'],
marker = dict(line=dict(color='rgb(255, 255, 255)', width=2)),
colorbar = {'title':'Coronavirus in the U.S'})
layout = dict(title = 'Coronavirus in the US',
geo= dict(scope = 'usa',
showlakes = True,
lakecolor = 'rgb(85, 173, 240)'))
choromap = go.Figure(data = [data], layout = layout)
iplot(choromap)
And then my map comes out looking like this:
empty map
As you can see, the colorbar is accurate, but the map itself is blank. Except for the lakes.
Here's the .csv file I'm referring to.
data table
I'm using jupyter notebook.
I've tried switching from a .xls to .csv, but that didn't work.
Thanks in advance.
I have some sample code to plot a map of Ontario using Bokeh. The code reads in the shapefile and converts it to a geojson file as suggested from examples available in the internet.
The shapefile source data is the Ontario census subdivision geographic boundary from the StatsCan website downloaded as a shapefile.
Image screenshot: https://imgur.com/xn1Zzdh
The result so far is an empty chart and I can't figure out what's wrong.
The shapefile is loaded first as a geopandas dataframe and converted to geojson.
Apologies for my lack of stackoverflow etiquette. I'm a new user.
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import geopandas
import os
from bokeh.plotting import figure, output_file, show, save,output_notebook
from bokeh.models import GeoJSONDataSource, LinearColorMapper, ColorBar
from bokeh.palettes import brewer
pd.options.display.max_rows = 10
workspace = r'C:\Users\user\Documents\lcsd000b16a_e'
CSD_LAYER = geopandas.read_file(os.path.join(workspace,r"lcsd000b16a_e.shp"))
ONT_CSD = CSD_LAYER[CSD_LAYER['PRUID']=='35']
ONT_CSD['geometry'].head()
1372 POLYGON ((7202895.13143 1077367.822855, 720382...
1373 POLYGON ((7205717.394285 1098087.974285, 72058...
1374 POLYGON ((7169056.905715 1216085.682855, 71693...
1614 POLYGON ((7162217.717145 948748.982855, 716229...
1809 POLYGON ((7506330.95143 1116872.145715, 750632...
# # Get the CRS of our grid
CRS = ONT_CSD.crs
print('FROM:' + str(CRS))
ONT_CSD = ONT_CSD.to_crs(epsg=3857) #transform to webmercator
print('TO: '+ str(ONT_CSD.crs))
FROM:{'init': 'epsg:3347'}
TO: {'init': 'epsg:3857', 'no_defs': True}
import json
#read data to json file
ONT_CSD_json = json.loads(ONT_CSD.to_json())
#convert to string like object
ONT_CSD_JSON_DATA = json.dumps(ONT_CSD_json)
#Input GeoJSON source that contains features for plotting.
geosource = GeoJSONDataSource(geojson = ONT_CSD_JSON_DATA)
#Create figure object.
p = figure(title = 'test', plot_height = 600 , plot_width = 950)
p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None
#Add patch renderer to figure.
p.patch('xs','ys', source = geosource,
line_color = 'black', line_width = 1, fill_alpha = 0.75)