Adding points to pyplot choropeth map - python

I have created a choropleth map in python with pyplot on US census data. Now I want to add points to this map denoting the location of towns using longitude and latitude. My code below successfully renders the choropleth but not the points on top
fig1 = px.choropleth(population, locations=population['StateAbbr'], locationmode='USA-states',
color='per1910',color_continuous_scale='inferno',
range_color=(0, .15),scope='usa',labels={'StateAbbr':'per1910'},hover_name='StateAbbr',)
go.Figure(data=go.Scattergeo(
lon = champs['Lon'],
lat = champs['Lat'],
text = champs['School'],
mode = 'markers',
marker_color = 'blue',
))
fig1.update_layout(title_text = 'Census: 1910 Championships: 1872-1915')
fig1.show()

Related

How to center plotly scatter_geo to a specific country in python

I use the scatter_geo function from plotly.express to plot geographical data on a map.
import geopandas as gpd
import plotly.express as px
fig = px.scatter_geo(gdf,
lat = 'latitude',
lon = 'longitude',
geojson='geometry',
scope='europe',
animation_frame = 'year')
fig.show()
How can I archive that the map is centered to only one country, in my case Germany? The parameter scope accepted only continents. There are two more parameters, center and fitbounds, that sounds useful, but I don't understand to fill in the right value.
center (dict) – Dict keys are 'lat' and 'lon' Sets the center point of
the map.
fitbounds (str (default False).) – One of False, locations or geojson.
Dummie data:
geometry latitude longitude value year
0 POINT (13.72740 51.05570) 51.0557 13.7274 35.55 1838
1 POINT (13.72740 51.05570) 51.0557 13.7274 35.15 1842
There are two ways to specify a specific latitude and longitude: by writing it directly or by adding it in a layout update. Adding it via layout update is more flexible and adjustable. For the scope, select Europe to draw the area by country. To zoom in on the map, use projection_scalse instead of zoom. I was not sure about the center of Germany so I used the data you presented, please change it.
fig = px.scatter_geo(gdf,
lat = 'latitude',
lon = 'longitude',
geojson='geometry',
scope='europe',
center=dict(lat=51.0057, lon=13.7274),
animation_frame = 'year')
Update layout
import plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.scatter_geo(df,
locations="iso_alpha",
size="pop",
projection="natural earth"
)
fig.update_layout(
autosize=True,
height=600,
geo=dict(
center=dict(
lat=51.0057,
lon=13.7274
),
scope='europe',
projection_scale=6
)
)
fig.show()

How to draw bounderies between countries and countries' states on pyplot.go.Figure with go.Scattergeo

So, I am doing a map that shows the flow of people among some cities in Brazil by drawing lines on the map, representing the path, and setting its opacity according to the count of occurrences. To do so, I am following this code (third map, the one about flights on US).
My question is, can I draw the borders between countries? And, if possible, also between Brazilian states?
In the documentation, there is an argument of the function called "geojson", but I'am not sure on how to use it, or if it is even useful for me.
Note that I have GeoJSON data for both countries and states.
Here's the code to generate the my map:
import pandas as pd
import plotly.graph_objects as go
fig = go.Figure()
for i in range(len(my_df)):
fig.add_trace(
go.Scattergeo(
lon = [my_df['res_longitude'][i], my_df['nasc_longitude'][i]],
lat = [my_df['res_latitude'][i], my_df['nasc_latitude'][i]],
mode = 'lines',
line = dict(width = 1,color = 'red'),
opacity = min(1, float(my_df['flow'][i]) / float(my_df['flow'].quantile(.95))),
)
)
fig.update_layout(
showlegend = False,
margin ={'l':0,'t':0,'b':0,'r':0},
mapbox = {
'center': {'lon': -50.3206, 'lat': -16.4984},
'style': "stamen-terrain",
'zoom': 3}
)
and here's the result:
Since I don't have the geojson data and the latitude and longitude information to draw the line, I'll use the official reference you referenced to answer your question.
Using the choropleth map, add a sum column with 0 to the data used in this sample.
Specify the geojson you obtained to geojson=usa_geo.
We associate the geojson state name with the state in the data.
I set the map fill to a light gray.
Note: The center setting of the map is automatically calculated since we are using fitbounds for the location.
from urllib import request
import json
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
# usa geojson data
# https://eric.clst.org/tech/usgeojson/
usa_json = open('./data/gz_2010_us_040_00_500k.json', 'r')
usa_geo = json.load(usa_json)
# Choropleth Maps with go.Choropleth
# https://plotly.com/python/choropleth-maps/
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')
# https://plotly.com/python/lines-on-maps/
df_flight_paths = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_aa_flight_paths.csv')
# dummy data column
dfs = pd.concat([df, pd.Series([0]*len(df),name='count')], axis=1)
fig = go.Figure()
fig.add_trace(go.Choropleth(
geojson=usa_geo,
locations=df['state'],
z = dfs['count'].astype(float),
featureidkey='properties.NAME',
colorscale = [[0,'rgb(200, 200, 200)']],
showlegend=False,
coloraxis=None,
colorbar=None
))
fig.update_traces(showscale=False)
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()),
showlegend=False
)
)
fig.update_layout(
autosize=False,
width=1000,
height=600,
margin={"r":0,"t":0,"l":0,"b":0},
geo=dict(
scope='north america', # you chenge 'south america'
fitbounds="locations", # It is associated width 'px.Choropleth'
visible=True,
showland=True,
#center=dict(lon=34.05795, lat=-179.25450),
# The center designation of the map has no effect as this is automatically calculated
)
)
fig.show()

Folium Heatmap with color bar Values

In my project I receive a DataFrame with scores for cities in the US. I can plot the HeatMap using Folium however I would like to add a colorbar to showcase the numerical values of these scores, based on the color of the HeatMap. Is there a way to do it?.
My code so far
cities = pd.read_csv ('../datasets/us.csv'))
cord = cities [["latitude","longitude","score"]]
#create map
base_map = folium.Map(
width = "100%",
height = "100%",
location = [-15.788497,-47.879873],
zoom_start = 4
)
base_map = base_map.add_child(plugins.HeatMap(cord,radius = 20, min_opacity = 0.1))

Plotly: How to set colorbar position for a choropleth map?

I can't find anything in the documentation about controlling where to place the colorbar, just whether or not it should be shown and with what color scale, etc. Can this be done?
If it helps, I am implementing my choropleth map with Dash.
The answer:
fig.data[0].colorbar.x=-0.1
or:
fig.update_layout(coloraxis_colorbar_x=-0.1)
Some details:
You haven't provided any code so I'll refer to an example from the docs where the position of the colorbar along the x-axis defaults to 1.2. You can change this directly through, for example:
fig.data[0].colorbar.x=-0.1
And get:
Complete code:
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')
fig = go.Figure(data=go.Choropleth(
locations=df['code'], # Spatial coordinates
z = df['total exports'].astype(float), # Data to be color-coded
locationmode = 'USA-states', # set of locations match entries in `locations`
colorscale = 'Reds',
colorbar_title = "Millions USD",
))
fig.update_layout(
title_text = '2011 US Agriculture Exports by State',
geo_scope='usa', # limite map scope to USA
)
fig.data[0].colorbar.x=-0.1
fig.show()

Using Bokeh to plot lat/long points with varying radii (varying size) and varying color based on values

I have a code that produces a map of the united states with points at specified lat longs coordinates. Each of these points is tagged with a value that I want to use to indicate how large the point should be and what color the point should be. The code is below:
points = pd.read_csv(f)
lat = []
lon = []
heat = []
const = []
for i in range(points.shape[0]):
lat.append(points.iat[i,0])
lon.append(points.iat[i,1])
heat.append(points.iat[i,2])
const.append(points.iat[i,3])
source = ColumnDataSource(
data = dict(
lat = lat,
lon = lon,
radius = heat,
constr = const,
)
)
TOOLS = 'box_zoom,wheel_zoom,hover'
state_xs = [states[code]["lons"] for code in states]
state_ys = [states[code]["lats"] for code in states]
p = figure(title="Bound Portfolio", toolbar_location="left",
plot_width=1100, plot_height=700, tools = TOOLS)
p.patches(state_xs, state_ys, fill_alpha=0.3, fill_color = "orange",
line_color="#884444", line_width=2, line_alpha=0.3)
circle = Circle(x="lon", y="lat", size=4.5, fill_color="blue", fill_alpha=0.5, line_color=None)
#circle = Circle(x="lon", y="lat", size=4.5, fill_color="blue", fill_alpha=0.5, line_color=None)
p.add_glyph(source, circle)
lat, lon, heat, and const are lists that I have created by reading the rows of a pandas dataframe. I want the values of heat (1-10) to be the radius of the point in question. I want each unique value in const to map to a unique color for the point in question. I have not been able to figure out how to make this code work. I have tried putting in many variations for the size of circle and it has not worked... the same applies for the color.
Here is an example with unique alpha, color and size.
Key is to store values in a columndatasource then pass this as an argument into a figure method - i.e. .circle("xname", "yname", source=source)
from bokeh.io import show
from bokeh.plotting import figure, ColumnDataSource
lat = [0,1,2,3]
lon = [10,20,30,40]
radius = [1,2,3,4]
constr = [100,200,300,400]
colors= ['#014636', '#016c59','#02818a', '#3690c0']
alpha=[0.8,0.1,0.3,0.5]
source = ColumnDataSource(
data = dict(
lat = lat,
lon = lon,
radius = radius,
constr = constr,
colors=colors,
alpha=alpha
)
)
p = figure(title="Bound Portfolio",
plot_width=1100, plot_height=700)
p.circle("lon","lat",source=source, fill_alpha="alpha", fill_color = "colors",
line_color="colors", line_width=2, line_alpha=0.3,radius="radius")

Categories