Tech이야기~!
welcom 자세히보기

Computer/Python

[Python] 코로나바이러스 시각화 지도 히스토리

Enhold 2020. 3. 16. 02:59

 

 

DataSet https://github.com/jihoo-kim/Coronavirus-Dataset

 

jihoo-kim/Coronavirus-Dataset

[CSV] Dataset of CoronaVirus disease 2019 (COVID-19) in South Korea (from KCDC) - jihoo-kim/Coronavirus-Dataset

github.com

DataSet2 : https://www.kaggle.com/kimjihoo/coronavirusdataset

 

Coronavirus-Dataset

Dataset of COVID-19 in South Korea

www.kaggle.com

*주말 데이터는 업데이트안함

 time 데이터셋 정보

  • date: 일자
  • test: 누적 검사 수 (진행 중인 검사 포함)
  • negative: 누적 음성 결과 수
  • confirmed: 누적 양성 결과 수 (확진)
  • released: 누적 격리 해제 수
  • deceased: 누적 사망 수

 

import numpy as np
import pandas as pd
import geopandas as gpd
from geopandas.tools import geocode
import math
from collections import namedtuple

import folium
from folium import Choropleth, Circle, Marker
from folium.plugins import HeatMap, MarkerCluster, TimestampedGeoJson

import datetime
import os


import json
from folium.features import DivIcon
geo_path = '../bokeh-app/input/geo/Si-Do/TL_SCCO_CTPRVN.json'
kr_geo_data = json.load(open(geo_path, encoding='utf-8'))
df_con = pd.read_csv('C:/Users/MSI/Untitled Folder/corona_con_kor.csv')
df_on = pd.read_csv('C:/Users/MSI/Untitled Folder/corona_con_kor.csv')

def prepare_df_date(df):
    # turning date field into timestamps
    df['date'] = pd.to_datetime(df['date'])
    df['Confirmed'] = df['Confirmed'].fillna(0)
    return df
df_con = prepare_df_date(df_con)
df_on = prepare_df_date(df_on)

Animation

 최근에는 GeoJason을 통한 경로 및 마커 위치등  애니메이션을 적용하는 옵션과 함께 작동이 제대로 움직이지 않습니다.

def create_geojson_features(df_con,df_on,
                            radius_max=1000,
                            radius_min = 2, 
                            fill_color_confirmed = '#FC766AFF',
                            fill_color_recovered = '#0A5E2AFF',
                            fill_color_death = '#E80018',
                            weight = 1,
                            fill_opacity = 0.5
                            ):

    print('> Creating GeoJSON features...')

    features = []
    feature = []
    # df_con
    for _, row in df_con.iterrows():
        radius = np.sqrt(row['Confirmed'])
        if radius != 0:
          if radius < radius_min:
            radius = radius_min

          if radius > radius_max:
            radius = radius_max
            
          popup = str(row['city']) + str(row['Confirmed'])
        
          feature = {
              'type': 'Feature',
              'geometry': {
                  'type':'Point', 
                  'coordinates':[row['longitude'],row['latitude']]
              },
              'properties': {
                  'time': row['date'].__str__(),
                  'style': {'color' : fill_color_confirmed},
                  'icon': 'circle',
                  'iconstyle':{
                      'fillColor': fill_color_confirmed,
                      'fillOpacity': fill_opacity,
                      'stroke': 'true',
                      'radius': radius,
                      'weight': weight,
                      'popup': popup
                  }
              }
        }
        features.append(feature)
        
    for _, row in df_on.iterrows():
        radius = np.sqrt(row['Confirmed'])
        if radius != 0:
          if radius < radius_min:
            radius = radius_min

          if radius > radius_max:
            radius = radius_max
        popups = str(row['city']) + str(row['Confirmed'])
        size=radius,radius
        feature = {
            'type': 'Feature',
            'geometry': {
                'type':'Point',
                'coordinates':[row['longitude'],row['latitude']]
            },
            'properties': {
                'time': row['date'].__str__(),
                'style': {'color' : fill_color_confirmed},
                'icon': 'marker',
                'iconstyle': { 'iconUrl': 'https://cdn.iconscout.com/icon/premium/png-512-thumb/coronavirus-4-613136.png', 
                              'iconSize': [radius, radius],
                              'fillOpacity': 0.1,
                              'Popup': popups
                             }
            }
        }
        features.append(feature)
        

    
    print('> finishing GeoJSON features...')
    return features

이 함수는 GeoJson을 Folium 맵으로 가져옵니다.

def make_map(features, caption):
    print('> Making map...')
    coords=[36, 127]
    map = folium.Map(location=coords, 
                               control_scale=True, 
                               zoom_start=6.5,
                               tiles='cartodbpositron',  
                               detect_retina = True
                              )
    
    folium.Choropleth(
        geo_data=kr_geo_data,
        name='choropleth',
        key_on='feature.properties.name',
        fill_color='yellow',
        fill_opacity=0.15,
        line_opacity=0.7
        ).add_to(map)


    TimestampedGeoJson(
        {'type': 'FeatureCollection',
        'features': features}
        , period='P1D'
        , duration='P1D'
        , add_last_point=True
        , auto_play=False
        , loop=False
        , max_speed=1
        , loop_button=True
        , date_options='MM/DD/YYYY'
        , time_slider_drag_update=True
        , transition_time = 500
    ).add_to(map)
  
    
    map.caption = caption
    print('> Done.')
    map.save(os.path.join('Corona_kr.html'))
    
    return map
features = create_geojson_features(df_con, df_on, fill_opacity=0.3, weight = 1)
make_map(features, caption = "Coronavirus propagation in korea, 2020.")

from bokeh.models import ColumnDataSource
from bokeh.plotting import output_notebook, figure, show
from bokeh.palettes import Blues8, Spectral3


plot = figure(plot_width=1200, plot_height=600, title='Corona19 virus graph in Korea', x_axis_label='date',x_axis_type='datetime',
              y_axis_label='Peoples')
    
plot.line(Origin_df['date'], Origin_df['confirmed'], line_width=2, line_color='green', legend_label='Confirmed')
plot.circle(Origin_df['date'], Origin_df['confirmed'], fill_color="green",line_color='green', size=8)
plot.line(Origin_df['date'], Origin_df['released'], line_width=2, line_color='blue', legend_label='Released')
plot.circle(Origin_df['date'], Origin_df['released'], fill_color="blue",line_color='blue', size=8)
plot.line(Origin_df['date'], Origin_df['deceased'], line_width=2, line_color='red', legend_label='Dethed')
plot.circle(Origin_df['date'], Origin_df['deceased'], fill_color="red",line_color='red', size=8)

plot.legend.location = "top_left"
plot.label_text_font_size: "36pt"
plot.legend.border_line_color = "navy"

show(plot)