[Write to map with plotly] Dynamic visualization with plotly [python]

python==3.8 plotly==4.10.0

Introduction of map plot

About easy scatter_geo and line_geo

You can make a figure by specifying the longitude and latitude, or by specifying the country name from iso-code. The country code is here

There are several datasets in plotly, so let's use one that already has the country name and information entered. You can check the supported data from github (https://github.com/plotly/datasets)

The country name is in iso_alpha, and I will color-code it based on the continent name.

Immediately plot

import plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.scatter_geo(df, locations="iso_alpha",
                  color="continent",
                  projection="orthographic")
fig.show()

image.png

This time I chose a globe-like format, but you can also specify a map or hemispherical display.

(Use the line_geo function to connect the lines)

image.png

The plot format must be passed to projection in character format,

'equirectangular', 'mercator', 'orthographic', 'natural earth', 'kavrayskiy7', 'miller', 'robinson', 'eckert4', 'azimuthal equal area', 'azimuthal equidistant', 'conic equal area', 'conic conformal', 'conic equidistant', 'gnomonic', 'stereographic', 'mollweide', 'hammer', 'transverse mercator', 'albers usa', 'winkel tripel', 'aitoff', 'sinusoidal'

Can be specified. Or if you want to discuss only a specific area You can also specify scope,

 'world', 'usa', 'europe', 'asia', 'africa', 'north america', 'south america', 'albers usa'

You can enlarge the area of

You can also change the size of the point by passing a value to size You can also create animations by passing numerical and time data to animation_frame. It creates an animation in which the values change in the specified order.

import plotly.express as px
df = px.data.gapminder()
fig = px.scatter_geo(df, 
  locations="iso_alpha", 
  color="continent",
  hover_name="country", 
  size="pop",
  animation_frame="year",
  projection="natural earth")
fig.show()

bbb.gif

More detailed story

You can use FIPScode to color-code by subdivisions such as small states. To do that, you need to prepare a geojson file and pass the country code and state code, which is difficult to explain. I think it's a good idea to check as much as you need, when you need it. Since some geojson is included as a plotly dataset, it is recommended to apply it to what you want to execute while looking at the code and data.

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.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

image.png

import plotly.express as px

df = px.data.gapminder().query("year == 2007")
avg_lifeExp = (df['lifeExp']*df['pop']).sum()/df['pop'].sum()

fig = px.choropleth(df, locations="iso_alpha", color="lifeExp",
                    color_continuous_scale=px.colors.diverging.BrBG,
                    color_continuous_midpoint=avg_lifeExp,
                    title="World Average Life Expectancy in 2007 in years was %.1f" % avg_lifeExp)
fig.show()

image.png

import plotly.express as px
df = px.data.carshare()
fig = px.scatter_mapbox(df, lat="centroid_lat", lon="centroid_lon", color="peak_hour", size="car_hours",
                  color_continuous_scale=px.colors.cyclical.IceFire, size_max=15, zoom=10,
                  mapbox_style="carto-positron")
fig.show()

image.png

that's all

reference

Recommended Posts

[Write to map with plotly] Dynamic visualization with plotly [python]
[Various image analysis with plotly] Dynamic visualization with plotly [python, image]
Write to csv with Python
[Time series with plotly] Dynamic visualization with plotly [python, stock price]
[Python] Write to csv file with Python
[Talking about the drawing structure of plotly] Dynamic visualization with plotly [python]
[Density visualization] Plotly and dynamic visualization [python3, hist, kde, join, contour, heat map]
Write CSV data to AWS-S3 with AWS-Lambda + Python
I want to write to a file with Python
Logistics visualization with Python
I tried to draw a route map with Python
Write multiple records to DynamoDB with Lambda (Python, JavaScript)
[Python] A memo to write CSV vertically with Pandas
A program to write Lattice Hinge with Rhinoceros with Python
For those who want to write Python with vim
Connect to BigQuery with Python
Connect to Wikipedia with Python
Post to slack with Python 3
Let's write python with cinema4d.
Switch python to 2.7 with alternatives
[Python] Technique to reduce dimensions with DP (Dynamic Programming) [AtCoder]
[Visualization] I want to draw a beautiful graph with Plotly
How to write offline real-time Solving E05 problems with Python
How to write a Python class
Python: How to use async with
Link to get started with python
Create folders from '01' to '12' with python
Nice to meet you with python
Try to operate Facebook with Python
Output to csv file with Python
Convert list to DataFrame with python
MP3 to WAV conversion with Python
To do tail recursion with Python2
How to get started with Python
Write FW to TWE-Lite with TWE-Lite R.
What to do with PYTHON release?
Unable to install Python with pyenv
How to use FTP with Python
How to calculate date with python
Easy data visualization with Python seaborn.
Easily post to twitter with Python 3
Data analysis starting with python (data visualization 1)
I want to debug with Python
Data analysis starting with python (data visualization 2)
Write a batch script with Python3.5 ~
Don't write Python if you want to speed it up with Python
Try to display google map and geospatial information authority map with python
[Capacity indicator, Gantt chart, UI] Plotly dynamic visualization [python, gauge display, Gantt chart]
How to write offline real time Solve F01 problems with Python
Write documentation in Sphinx with Python Livereload
[Python] Calendar-style heat map (with holiday display)
The 16th offline real-time how to write problem was solved with Python
Try to reproduce color film with Python
Try logging in to qiita with Python
Change Python 64bit environment to 32bit environment with Anaconda
English speech recognition with python [speech to text]
Convert memo at once with Python 2to3
HTML email with image to send with python
[Visualization of ratio] Plotly and dynamic visualization [python, pie, sunburst, sanky, treemap, fannele,]
Memo to ask for KPI with python
Python to remember only with hello, worlds