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.
Related
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 am trying to plot a text files with X,Y values(attached inline). I am first converting the text file into 2 array objects XAxis1 and YAxis1. The plot doesn't come out properly. Unable to set the X and Y axis values.
Any help is much appreciated.
(Sample1.txt)XAxis1 : 0.51,0.52,0.53,0.54,0.55,0.56,0.57,0.58,0.59,0.6,0.61,0.62,0.63,0.64,0.65,0.66,0.67,0.68,0.69,0.7
(Sample2.txt)YAxis1:
29.63,30.03,30.94,31.67,33.59,35.09,35.35,35.04,36.71,36.77,36.84,37.45,33.87,31.68,30.98,27.97,29.24,38.52,33.37,27.8
Sorry could not paste the code, some errors..
Some people have downvoted your question, because a google search can solve much bigger problems and this is not very exotic.
See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html
from matplotlib.pyplot import plot
ax_x = [
0.51,0.52,0.53,0.54,0.55,0.56,0.57,0.58,0.59,0.6,0.61,0.62,0.63,0.64,0.65,0.66,0.67,0.68,0.69,0.7]
ax_y = [
29.63,30.03,30.94,31.67,33.59,35.09,35.35,35.04,36.71,36.77,36.84,37.45,33.87,31.68,30.98,27.97,29.24,38.52,33.37,27.8]
plot(ax_x, ax_y)
In case reading from file is a problem, I recommend saving everything in a useful format.
See https://www.programiz.com/python-programming/json
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 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')
I am trying to use Folium for geographical information reading from a pandas dataframe.
The code I have is this one:
import folium
from folium import plugins
import pandas as pd
...operations on dataframe df...
map_1 = folium.Map(location=[51.5073219, -0.1276474],
zoom_start=12,
tiles='Stamen Terrain')
markerCluster = folium.plugins.MarkerCluster().add_to(map_1)
lat=0.
lon=0.
for index,row in df.iterrows():
lat=row['lat]
lon=row['lon']
folium.Marker([lat, lon], popup=row['name']).add_to(markerCluster)
map_1
df is a dataframe with longitude, latitude and name information. Longitude and latitude are float.
I am using jupyter notebook and the map does not appear. Just a white empty box.
I have also tried to save the map:
map_1.save(outfile='map_1.html')
but also opening the file doesn't work (using Chrome, Firefox or Explorer).
I have tried to reduce the number of markers displayed and below 300 markers the code works and the map is correctly displayed. If there are more than 300 Markers the map returns to be be blank.
The size of the file is below 5 MB and should be processed correctly by Chrome.
Is there a way around it (I have more than 2000 entries in the dataframe and I would like to plot them all)? Or to set the maximum number of markers shown in folium?
Thanks
This might be too late but I stumbled upon the same problem and found a solution that worked for me without having to remove the popups so I figured if anybody has the same issue they can try it out. Try replacing popup=row['name'] with popup=folium.PopUp(row['name'], parse_html=True) and see whether it works. You can read more about it here https://github.com/python-visualization/folium/issues/726