import plotly.express as px
df = px.data.election()
geojson = px.data.election_geojson()
fig = px.choropleth(
df, geojson=geojson, color='Joly',
locations="district", featureidkey="properties.district",
projection="mercator", range_color=[0, 6500],
hover_data=['Coderre', 'Bergeron', 'Joly'])
# auto-computed to fit trace data in map
fig.update_geos(fitbounds="locations", visible=False)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_ebola.csv')
df.head()
colors = ['rgb(239,243,255)','rgb(189,215,231)','rgb(107,174,214)','rgb(33,113,181)']
months = {6:'June',7:'July',8:'Aug',9:'Sept'}
df_sept = df.query('Month == 9')
fig = go.Figure()
fig.add_trace(go.Choropleth(
locationmode = 'country names',
locations = df_sept['Country'],
z = df_sept['Value'],
text = df_sept['Country'],
))
fig.update_geos(showframe = False, lonaxis_range= [ -15.0, -5.0 ], lataxis_range= [ 0.0, 12.0 ],)
fig = go.Figure(go.Scattergeo())
fig.update_geos(
resolution=50, # resolution 1:50m
showcoastlines=True, coastlinecolor="RebeccaPurple",
showland=True, landcolor="LightGreen",
showocean=True, oceancolor="LightBlue",
showlakes=True, lakecolor="Blue",
showrivers=True, rivercolor="Blue",
scope="usa",
showcountries=True, countrycolor="Black",
showsubunits=True, subunitcolor="Blue",
)
df_airports = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
df_flight_paths = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_aa_flight_paths.csv')
fig = go.Figure()
fig.add_trace(go.Scattergeo(
locationmode = 'USA-states',
lon = df_airports['long'],
lat = df_airports['lat'],
hoverinfo = 'text',
text = df_airports['airport'],
mode = 'markers',
marker = dict(
size = 2,
color = 'rgb(255, 0, 0)',
line = dict(
width = 3,
color = 'rgba(68, 68, 68, 0)'
)
)))
flight_paths = []
for i in range(len(df_flight_paths)):
fig.add_trace(
go.Scattergeo(
locationmode = 'USA-states',
lon = [df_flight_paths['start_lon'][i], df_flight_paths['end_lon'][i]],
lat = [df_flight_paths['start_lat'][i], df_flight_paths['end_lat'][i]],
mode = 'lines',
line = dict(width = 1,color = 'red'),
opacity = float(df_flight_paths['cnt'][i]) / float(df_flight_paths['cnt'].max()),
)
)
fig.update_layout(
title_text = 'Feb. 2011 American Airline flight paths<br>(Hover for airport names)',
showlegend = False,
geo = dict(
scope = 'north america',
projection_type = 'azimuthal equal area',
showland = True,
landcolor = 'rgb(243, 243, 243)',
countrycolor = 'rgb(204, 204, 204)',
),
)
fig.show()
import plotly.express as px
fig = px.scatter_geo(lat=[0,15,20,35], lon=[5,10,25,30], hover_name = ['t0<br>temp', 't1', 't2', 't3'])
fig.update_geos(fitbounds="locations")
fig.update_traces(mode="markers")
df = px.data.gapminder().query("year == 2007")
fig = px.scatter_geo(df, locations="iso_alpha",
size="pop", # size of markers, "pop" is one of the columns of gapminder
)
fig.show()
import geopandas
geo_df = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities'))
fig = px.scatter_geo(geo_df,
lat=geo_df.geometry.y,
lon=geo_df.geometry.x,
hover_name="name")
fig.show()
import plotly.express as px
fig = px.line_geo(lat=[0,15,None, 20,35], lon=[5,10,None, 25,30], hover_name = ['t0<br>temp', 't1', None, 't2', 't3'])
fig.update_geos(fitbounds="locations")
df = px.data.gapminder().query("year == 2007")
fig = px.line_geo(df, locations="iso_alpha",
color="continent", # "continent" is one of the columns of gapminder
projection="orthographic")
fig.show()
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
dtype={"fips": str})
import plotly.express as px
fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',
color_continuous_scale="Viridis",
range_color=(0, 12),
scope="usa",
labels={'unemp':'unemployment rate'}
)
fig.show()
# convert geopandas Dataframe from geojson
gdf = geopandas.GeoDataFrame.from_features(counties['features'])
# convert geopandas to geojson
gjson = gdf[['geometry', 'GEO_ID']].to_json() # str
gjson = json.loads(gjson) # json
fig = px.choropleth(gdf, geojson=gjson, locations='GEO_ID', featureidkey="properties.GEO_ID", color='CENSUSAREA',
scope="usa",
)
fig.show()
df = px.data.election()
geo_df = geopandas.GeoDataFrame.from_features(
px.data.election_geojson()["features"]
).merge(df, on="district")
fig = px.choropleth(geo_df,
geojson=geo_df.geometry,
locations=geo_df.index,
color="Joly",
projection="mercator")
fig.update_geos(fitbounds="locations", visible=False)
fig.show()
import wget
wget.download("https://plotly.github.io/datasets/ne_50m_rivers_lake_centerlines.zip")
geo_df = geopandas.read_file("zip://ne_50m_rivers_lake_centerlines.zip")
import shapely.geometry
import numpy as np
lats = []
lons = []
names = []
for feature, name in zip(geo_df.geometry, geo_df.name):
if isinstance(feature, shapely.geometry.linestring.LineString):
linestrings = [feature]
elif isinstance(feature, shapely.geometry.multilinestring.MultiLineString):
linestrings = feature.geoms
else:
continue
for linestring in linestrings:
x, y = linestring.xy
lats = np.append(lats, y)
lons = np.append(lons, x)
names = np.append(names, [name]*len(y))
lats = np.append(lats, None) # seperate lines with None
lons = np.append(lons, None)
names = np.append(names, None)
fig = px.line_geo(lat=lats, lon=lons, hover_name=names)
fig.update_layout(
margin = dict(l=0, r=0, b=0, t=0, pad=0)
)
fig.update_geos(
resolution=50,
showcoastlines=True, coastlinecolor="RebeccaPurple",
showland=True, landcolor="FloralWhite",
showocean=True, oceancolor="CornflowerBlue",
showlakes=True, lakecolor="CornflowerBlue",
showrivers=True, rivercolor="CornflowerBlue"
)
fig.show()
df = px.data.gapminder().query("year==2007")
df.head()
fig = px.choropleth(df, locations="iso_alpha",
color="lifeExp", # lifeExp is a column of gapminder
hover_name="country", # column to add to hover information
color_continuous_scale=px.colors.sequential.Plasma)
fig.show()
fig = px.choropleth(locations=["CA", "TX", "NY"], locationmode="USA-states", color=[1,2,3], scope="usa")
fig.show()
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_ebola.csv')
colors = ['rgb(239,243,255)','rgb(189,215,231)','rgb(107,174,214)','rgb(33,113,181)']
months = {6:'June',7:'July',8:'Aug',9:'Sept'}
fig = go.Figure()
for i in range(6,10)[::-1]:
df_month = df.query('Month == %d' %i)
fig.add_trace(go.Scattergeo(
lon = df_month['Lon'],
lat = df_month['Lat'],
text = df_month['Value'],
name = months[i],
marker = dict(
size = df_month['Value']/50,
color = colors[i-6],
line_width = 0
)))
df_sept = df.query('Month == 9')
fig.add_trace(go.Choropleth(
locationmode = 'country names',
locations = df_sept['Country'],
z = df_sept['Value'],
text = df_sept['Country'],
colorscale = [[0,'rgb(0, 0, 0)'],[1,'rgb(0, 0, 0)']],
autocolorscale = False,
showscale = False,
geo = 'geo2' # plot in an individual figure
))
fig.add_trace(go.Scattergeo(
lon = [21.0936],
lat = [7.1881],
text = ['Africa'],
mode = 'text',
showlegend = False,
geo = 'geo2'
))
fig.update_layout(
title = go.layout.Title(
text = 'Ebola cases reported by month in West Africa 2014<br> \
Source: <a href="https://data.hdx.rwlabs.org/dataset/rowca-ebola-cases">\
HDX</a>'),
geo = go.layout.Geo(
resolution = 50,
scope = 'africa',
showframe = False,
showcoastlines = True,
landcolor = "rgb(229, 229, 229)",
countrycolor = "white" ,
coastlinecolor = "white",
projection_type = 'mercator',
lonaxis_range= [ -15.0, -5.0 ],
lataxis_range= [ 0.0, 12.0 ],
domain = dict(x = [ 0, 1 ], y = [ 0, 1 ])
),
geo2 = go.layout.Geo(
scope = 'africa',
showframe = False,
landcolor = "rgb(229, 229, 229)",
showcountries = False,
domain = dict(x = [ 0, 0.6 ], y = [ 0, 0.6 ]),
bgcolor = 'rgba(255, 255, 255, 0.0)',
),
legend_traceorder = 'reversed'
)
fig.show()