巧用python中的plotly模块做可视化图表

今天给大家带来一个小福利,运用python里面plotly模块做可视化图表。

源数据如下图所示

巧用python中的plotly模块做可视化图表

import json,folium,requests
import mimetypes
import http.client
import pandas as pd
from folium.plugins import HeatMap
from pandas.io.json import json_normalize
import pycountry

df=pd.read_excel('D:\stockdata\疫情数据.xlsx')
df_confirm=df.groupby('国家/地区').agg('sum')
date_list=list(df_confirm.columns)

def get_country_code(name):
try:
return pycountry.countries.lookup(name).alpha_3
except:
return None

df_confirm['国家/地区']=df_confirm.index
df_confirm['iso_alpha_3']=df_confirm['国家/地区'].apply(get_country_code)
df_long=pd.melt(df_confirm,id_vars=['国家/地区','iso_alpha_3'],value_vars=date_list)

df_long=df_long.rename(columns={'variable':'日期','value':'人数'})
df_long.head()

处理后数据

巧用python中的plotly模块做可视化图表

国家就获得了相应的alpha3代码,也就是获得了地图上的每个country地形框架

import plotly.express as px
#行政地图
fig = px.choropleth(df_long,
# Input Dataframe
locations="iso_alpha_3",
# identify country code column
color="人数",
# identify representing col umn
hover_name="国家/地区",
# identify hover name
animation_frame="日期",
# identify date column
projection="natural earth",
#projection= "orthographic",# select projection
color_continuous_scale = 'Peach',
#color_continuous_scale = 'jet', # select prefer color sce
range_color = [0,10000] # select range of dataset
)

fig.layout.updatemenus[0].buttons[0].args[1]['frame']['duration'] = 100
fig.layout.updatemenus[0].buttons[0].args[1]['transition']['duration']=50
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

fig.write_html('pic.html') #存为网页

巧用python中的plotly模块做可视化图表

完美,大功告成!

改变配色

巧用python中的plotly模块做可视化图表

那么还可以在地形图上制作圆圈图,用圆圈表示数据的大小

fig = px.scatter_geo(df_long,locations="iso_alpha_3",
color="人数",# identify representing column
hover_name= "国家/地区",
size ="人数",
size_max= 50, # identify hover name
animation_frame="日期",# identify date column
projection="robinson",
#projection= "orthographic",# select projection
color_continuous_scale = 'Peach', # select prefer color scale
range_color=[0,10000]
)

fig.layout.updatemenus[0].buttons[0].args[1]['frame']['duration'] = 30
fig.layout.updatemenus[0].buttons[0].args[1]['transition'][ 'duration'] =5
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

巧用python中的plotly模块做可视化图表