I am starting data scientist and I am doing a benchmark for maps.
I would like to visualize the TomTom map API in Jupyter notebook with folium to compare it with OpenStreetMap. Openstreet map is supported by folium so that is easy. This code is doing the trick:
import folium
OSM_map = folium.Map(location=[45.523, -122.675],
zoom_start=13,
tiles="OpenStreetMap")
Now, I would like to do the same with the TomTom maps API. On developer.tomtom.com I find that this is the request URL:
https://api.tomtom.com/map/1/tile/basic/main/0/0/0.png?view=Unified&key=*****
So I thought to implement this in folium. I don't get an error message but it is just displaying a gray map.
TomTom_map = folium.Map(
location=[45.523, -122.675],
zoom_start=10,
tiles='http://{s}.api.tomtom.com/map/1/tile/basic/main/{z}/{x}/{y}.png',
API_key = 'xxxxxx',
attr='TomTom')
I follow literally the example of the folium documentation but it does not work. Anyone knows how to solve this? That would be great :). Cheers.
Thanks Bob and szogoon,
It works now! I replaced the code with:
import folium
TomTom_map = folium.Map(
location=[45.523, -122.675],
zoom_start=10,
tiles= 'http://{s}.api.tomtom.com/map/1/tile/basic/main/{z}/{x}/{y}.png?
view=Unified&key=********',
attr='TomTom')
Related
I'm looking to somehow figure out a way to insert a geographic graph of British Columbia which is a part of Canada in my data analysis.
I have made this image here explaining what tree is being planted the most in Vancouver
Now I want to make a geograph kind of like this https://altair-viz.github.io/gallery/airports_count.html
to answer: how the density/distribution of species planted different in different neighbourhoods look like.
This is what I'm having trouble with.
Thus
from vega_datasets import data
world_map = alt.topo_feature(data.world_110m.url, 'countries')
alt.Chart(world_map).mark_geoshape().project()
and it's giving me a world map! Great! I tried zooming into just British Columbia but it's not really working out.
Can anyone give me any direction on where to go and how I should go about answering my question? I really wanted to use geoshape
I also found this if it's helpful
https://global.mapit.mysociety.org/area/960958.html
Thank you and I appreciate everyones advice!
Canadian provinces are not part of world_110m map in the example gallery. You would need to provide your own geojson and topojson file that contains that information in order to work with Altair and then follow the guidelines here How can I make a map using GeoJSON data in Altair?.
You can also work with geopandas together with Altair, which in many ways is more flexible. We are working on integrating info on this into the docs, but in the meantime you can view this preview version to get started https://deploy-preview-1--spontaneous-sorbet-49ed10.netlify.app/user_guide/marks/geoshape.html
Looks like you got your data from here
import pandas as pd
import numpy as np
import plotly.express as px
#loading data
df = pd.read_csv('street-trees.csv', sep=';')
#extracting coords
df['coords'] = df['Geom'].str.extract('\[(.*?)\]')
df['lon'] = df['coords'].str.split(',').str[0].astype(float)
df['lat'] = df['coords'].str.split(',').str[1].astype(float)
#getting neighborhood totals
df2 = pd.merge(df[['NEIGHBOURHOOD_NAME']].value_counts().reset_index(), df[['NEIGHBOURHOOD_NAME', 'lon', 'lat']].groupby('NEIGHBOURHOOD_NAME').mean().reset_index())
#drawing figure
fig = px.scatter_mapbox(df2,
lat='lat',
lon='lon',
color=0,
opacity=0.5,
center=dict(lon=df2['lon'].mean(),
lat=df2['lat'].mean()),
zoom=11,
size=0)
fig.update_layout(mapbox_style='open-street-map')
fig.show()
I am definitely not an expert but using Joel's advice ... you can download a geojson from here:
https://data.opendatasoft.com/explore/dataset/georef-canada-province%40public/export/?disjunctive.prov_name_en
Because I downloaded it I then had to open it rather than reference a url like most of the examples so
can_prov_file = 'C:/PyProjects/georef-canada-province.geojson'
with open(can_prov_file) as f:
var_geojson = geojson.load(f)
data_geojson = alt.InlineData(values=var_geojson, format=alt.DataFormat(property='features',type='json'))
# chart object
provinces = alt.Chart(data_geojson).mark_geoshape(
).encode(
color="properties.prov_name_en:O"
).project(
type='identity', reflectY=True
)
Worked for me. Best of luck.
So I am trying to do something which seems relatively simple but is proving incredibly difficult. I have a .csv file with addresses and their correspondent latitude/longitude, I just want to plot those on a California JSON map like this one in python:
https://github.com/deldersveld/topojson/blob/master/countries/us-states/CA-06-california-counties.json
I've tried bubble maps, scatter maps, etc. but to no luck I keep getting all kind of errors :(. This is the closest I've got, but that uses a world map and can't zoom in effectively like that json map up there. I am still learning python so please go easy on me ><
import plotly.express as px
import pandas as pd
df = pd.read_csv(r"C:\Users\FT4\Desktop\FT Imported Data\Calimapdata.csv")
fig = px.scatter_geo(df,lat='Latitude',lon='Longitude', hover_name="lic_type", scope="usa")
fig.update_layout(title = 'World map', title_x=0.5)
fig.show()
If anyone could help me with this I would appreciate it. Thank you
your example link is just a GeoJSON geometry definition. Are you talking about a Choropleth?
If so, check out geopandas - you should be able to link your data to the polygons in the shape definition you linked to by reading it in with geojson and then joining on the shapes with sjoin. Once you have data tied to each geometry, you can plot with geopandas's .plot method. Check out the user guide for more info.
Something along these lines should work:
import geopandas as gpd, pandas as pd
geojson_raw_url = (
"https://raw.githubusercontent.com/deldersveld/topojson/"
"master/countries/us-states/CA-06-california-counties.json"
)
gdf = gpd.read_file(geojson_raw_url, engine="GeoJSON")
df = pd.read_csv(r"C:\Users\FT4\Desktop\FT Imported Data\Calimapdata.csv")
merged = gpd.sjoin(gdf, df, how='right')
# you could plot this directly with geopandas
merged.plot("lic_type")
alternatively, using #r-beginners' excellent answer to another question, we can plot with express:
fig = px.choropleth(merged, geojson=merged.geometry, locations=merged.index, color="lic_type")
fig.update_geos(fitbounds="locations", visible=False)
fig.show()
I try to import an imageCollection to qgis from google ee with the code below. I do not receive any error message. The syntax check syas everything is ok, the map appears among the layers, the crs of the imageCollection and the project match - yet the map does not appear on the canvas.
What could be the problem?
from ee_plugin import Map
imageCollection = ee.ImageCollection("MODIS/006/MOD13Q1"),
geometry = ee.Geometry.MultiPoint();
dataset = ee.ImageCollection('MODIS/006/MOD13Q1')\
.filter(ee.Filter.date('2021-01-01', '2021-05-31'));
ndvi = dataset.select('EVI');
ndviVis = {
'min': 0.0,
'max': 8000.0,
'palette': [
'FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718', '74A901',
'66A000', '529400', '3E8601', '207401', '056201', '004C00', '023B01',
'012E01', '011D01', '011301'
]};
Map.setCenter(19.040236, 47.197913, 7.5)
Map.addLayer(ndvi, ndviVis, 'EVI');
The reason is that the plugin does not interpret image collection properly. It looks like a bug - please report it as an issue with the above script to reproduce on GitHub. It should run mosaic() by default for image collections.
A workaround is to replace the last line with:
Map.addLayer(ndvi.mosaic(), ndviVis, 'EVI');
Or with:
Map.addLayer(ndvi.mean(), ndviVis, 'EVI');
Or any other reducer.
I am trying to use plotly choropleth to draw the map, lets say for a random variable of num for each of the feature regions of the map in Italy. However, it does not work. below is the code that I use:
I have downloaded the GeoJson files for Italy from here.
import random
import pandas as pd
import plotly.express as px
import plotly.io as pio
import json
pio.renderers.default='browser'
with open('it-all.geo.json') as f:
geojson = json.load(f)
n_provinces = len(geojson['features'])
province_names = [geojson['features'][k]['properties']['name'] for k in range(n_provinces)]
randomlist = []
for i in range(0,110):
n = random.randint(1,30)
randomlist.append(n)
datadata = pd.DataFrame({'province':province_names, 'num':randomlist})
fig = px.choropleth(datadata, geojson=geojson, color="num",
locations="province", featureidkey="properties.name",
color_continuous_scale="Viridis")
fig.show()
What I am getting is a mixed shape map as below, can anyone please let me know what I am doing wrong, thanks!!
I tried doing the same thing with data from my country and had the same issues. I think that this data might not be readable by plotly. If you look at the website's demos for their maps, there are several javascript scripts running in order to create the maps. It's possible that they've put their geojson into a custom format so that you have to use their javascript services in order to create a comprehensible map.
I later found a different set of data, and was able to easily create a chorpleth map with plotly using the exact same code that didn't work with the original data. Hopefully you found a different dataset that you could use. Oftentimes governments will provide open data about census areas, province/state borders, etc.
I really like how folium works with python on jupyter notebooks (I haven't tried it, but judging from the tutorials). What I want to achieve is same functionality, but with zeppelin notebooks using spark.ipyspark. Folium functionality would be huge improvement of data plotting capabilities of zeppelin's notebooks.
What I tried is simple:
import folium
m = folium.Map(location=[45.5236, -122.6750])
m
This is only returning <folium.folium.Map at 0x10f4a3518>
What I tried next is to build HTML map, save it locally and then invoke it as output of zeppelin paragraph.
import folium
from IPython.display import HTML
from IPython.display import IFrame
m =folium.Map(
location=[45.5236, -122.6750],
tiles='Stamen Toner',
zoom_start=13
)
m.render_iframe = True
m.save('/Users/abc/m.html')
HTML("<iframe src=file:///Users/abc/m.html width=700 height=350></iframe>")
Which again gave me:
<IPython.core.display.HTML object>
Then I exchanged last row with:
IFrame("src=file:///Users/abc/m.html", width=700, height=350)
Which again:
<IPython.lib.display.IFrame at 0x112882c88>
When I try python's print using:
print("%html <iframe src=file:///Users/abc/m.html width=700, height=350></iframe>")
I get 700x350 blank white window as output of the paragraph. When I try to change src to for example "https://zeppelin.apache.org/" it works well.
I feel like two things are not working properly.
1. Folium module with zeppelin notebook which is not invoking map properly.
2. Showing local HTML page as output of zeppelin paragraph.
Does anybody tried this already? Was anybody successful to overcome this?
Thanks for advice, I was able to run it by adding:
html_string = m.get_root().render()
print("%html", html_string)
So now entire code looks like:
import folium
m =folium.Map(
location=[45.5236, -122.6750],
tiles='Stamen Toner',
zoom_start=13,
width=600,height=300
)
html_string = m.get_root().render()
print("%html", html_string)
EDIT:
using above described way was modifying appearance of entire zeppelin notebook. I used different method, using html_string = m._repr_html_(),which is according this link (github.com/python-visualization/folium/issues/781) used in jupyter for showing HTML in iframe.
So code now:
import folium
m =folium.Map(
location=[45.5236, -122.6750],
tiles='Stamen Toner',
zoom_start=13,
width=600,height=300
)
html_string = m._repr_html_()
print("%html", html_string)