[Python] Plot data by prefecture on a map (number of cars owned nationwide)

Purpose of this article

Draw a prefectural-level colored map like the one below in Python At the municipal level, go to here

how_many_cars_map.png

By the way, the data used the number of passenger cars owned nationwide.

There is a [Code List](# Code List) at the end of the page.

Commentary

Use a library called japanmap to create colored maps

pip install japanmap

Preparation of other libraries

import numpy as np
import pandas as pd
import cv2
from PIL import Image
import matplotlib.colors
import matplotlib.pyplot as plt
from japanmap import *

Read data The data was processed by downloading the 2019 Excel file from here.

df = pd.read_csv("how_many_cars.csv")
df = df.iloc[:53,:8]

Save the number of passenger cars by prefecture in dictionary format

for k,n in zip(df["Transport Bureau"], df["Passenger car"]):
    if k in ["Sapporo", "Hakodate", "Asahikawa", "Muroran", "Kushiro", "Obihiro", "Kitami"]:
        tmp=1
    else:
        tmp = pref_code(k)
    tmp = pref_names[tmp]
    #print(k,tmp)
    if tmp not in num_dict:
        num_dict[tmp] = n
    else:
        num_dict[tmp] += n

The contents of num_dict are still like this

num_dict


>> print(num_dict)
{'Mie Prefecture': 1161089.0,
 'Kyoto': 1007847.0,
  ...
 'Tottori prefecture': 346273.0,
 'Kagoshima prefecture': 955360.0}

Convert the created num_dict value from the number of units to color information (RGB)

n_min = min(num_dict.values())
n_max = max(num_dict.values())

#print(n_min)
#print(n_max)

cmap = plt.cm.rainbow
norm = matplotlib.colors.Normalize(vmin=n_min, vmax=n_max)

def color_scale(r):
    tmp = cmap(norm(r))
    return (tmp[0]*255, tmp[1]*255, tmp[2]*255)

for k,v in num_dict.items():
    num_dict[k] = color_scale(v)

Contents of the final num_dict

num_dict


>> print(num_dict)
{'Mie Prefecture': (19.5, 157.4059464288972, 241.021876181009),
 'Kyoto': (41.49999999999999, 128.85792190698177, 246.1066417260737),
  ...
 'Tottori prefecture': (127.5, 0.0, 255.0),
 'Kagoshima prefecture': (47.5, 120.63885699318257, 247.29821868892742)}

Plot by passing num_dict to japanmap

plt.figure(figsize=(10,8))
plt.imshow(picture(num_dict))

sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
plt.colorbar(sm)
plt.show()

that's all!

Code list

pip install japanmap
import numpy as np
import pandas as pd
import cv2
from PIL import Image
import matplotlib.colors
import matplotlib.pyplot as plt
from japanmap import *

df = pd.read_csv("how_many_cars.csv")
df = df.iloc[:53,:8]

num_dict={}

for k,n in zip(df["Transport Bureau"], df["Passenger car"]):
    if k in ["Sapporo", "Hakodate", "Asahikawa", "Muroran", "Kushiro", "Obihiro", "Kitami"]:
        tmp=1
    else:
        tmp = pref_code(k)
    tmp = pref_names[tmp]
    #print(k,tmp)
    if tmp not in num_dict:
        num_dict[tmp] = n
    else:
        num_dict[tmp] += n

n_min = min(num_dict.values())
n_max = max(num_dict.values())

#print(n_min)
#print(n_max)

cmap = plt.cm.rainbow
norm = matplotlib.colors.Normalize(vmin=n_min, vmax=n_max)

def color_scale(r):
    tmp = cmap(norm(r))
    return (tmp[0]*255, tmp[1]*255, tmp[2]*255)

for k,v in num_dict.items():
    num_dict[k] = color_scale(v)

plt.figure(figsize=(10,8))
plt.imshow(picture(num_dict))

sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
plt.colorbar(sm)
plt.show()

Recommended Posts

[Python] Plot data by prefecture on a map (number of cars owned nationwide)
Folium: Visualize data on a map with Python
Plot the environmental concentration of organofluorine compounds on a map using open data
Visualization of data by prefecture
[Python] Visualize overseas Japanese soccer players on a map as of 2021.1.1
A simple data analysis of Bitcoin provided by CoinMetrics in Python
Visualize prefectures with many routes by prefecture on a Japanese map
Impressions of touching Dash, a data visualization tool made by python
Get the number of readers of a treatise on Mendeley in Python
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
Map rent information on a map with python
Basic data frame operations written by beginners in a week of learning Python
A memo of a tutorial on running python on heroku
A memorandum of extraction by python bs4 request
Make a joyplot-like plot of R in python
A well-prepared record of data analysis in Python
[Python] Save the video data imported by OpenCV as a serial number jpg file
[Scientific / technical calculation by Python] Plot, visualization, matplotlib of 2D data read from file
Consolidate a large number of CSV files in folders with python (data without header)
Let's put out a ranking of the number of effective reproductions of the new coronavirus by prefecture
[Grasshopper] When creating a data tree on Python script
[Python] A program that counts the number of valleys
Group by consecutive elements of a list in Python
[Python] Randomly generate a large number of English names
IDWR bulletin data scraping the number of reports per fixed point of influenza and by prefecture
3. Natural language processing with Python 3-4. A year of corona looking back on TF-IDF [Data creation]
Preprocessing of prefecture data
A memorandum of stumbling on my personal HEROKU & Python (Flask)
[Python] How to make a list of character strings character by character
Notes on handling large amounts of data with python + pandas
Run a limited number of image presentation programs on PsychoPy
Analyzing data on the number of corona patients in Japan
A record of hell lessons imposed on beginner Python students
[Treasure Data] [Python] Execute a query on Treasure Data using TD Client
Build a python data analysis environment on Mac (El Capitan)
Easy on Mac! Plot of unit step response using Python
[Python] Clustering results by K-means are reduced in dimension by PCA and plotted on a scatter plot.
Fixed-point observation of specific data on the Web by automatically executing a Web browser on the server (Ubuntu16.04) (2) -Web scraping-