📜  Python – 使用 covid19 India API 进行数据可视化(1)

📅  最后修改于: 2023-12-03 14:46:08.848000             🧑  作者: Mango

Python – 使用 covid19 India API 进行数据可视化

介绍

本文将介绍如何使用Python和covid19 India API进行数据可视化。COVID-19是流行病学中的一个非常重要的问题,因此,我们需要实现COVID-19数据的可视化,以更好地了解病毒的影响和趋势。

covid19 India API是一个公共API,它提供了有关印度COVID-19的最新统计信息,以及新闻和公告。我们将通过API获取数据并使用matplolib进行图形化可视化。

API

covid19 India API的官方链接:https://api.covid19india.org/

接口数据获取

要获取API的数据,我们需要安装requests模块,该模块允许我们从URL获得数据。在这里,我们将使用requests模块从API获取最新的印度COVID-19统计数据。

import requests
url = 'https://api.covid19india.org/data.json'
response = requests.get(url)
data = response.json()
数据加工和可视化

现在我们已经从API获取了数据,接下来我们将对数据进行处理,并使用matplotlib创建图形。

感染病例和死亡率可视化

我们将使用matplotlib创建一个饼状图,表示COVID-19的感染病例和死亡率百分比。

import matplotlib.pyplot as plt
total_cases = data['statewise'][0]['confirmed']
total_deaths = data['statewise'][0]['deaths']
total_recovered = data['statewise'][0]['recovered']
sizes = [total_cases, total_deaths, total_recovered]
labels = ['Confirmed Cases', 'Deaths', 'Recovered']
colors = ['#ff9999','#66b3ff','#99ff99']
fig1, ax1 = plt.subplots()
ax1.pie(sizes, colors = colors, labels=labels, autopct='%1.1f%%', startangle=90)
ax1.axis('equal')
plt.title('COVID-19 Stats in India')
plt.tight_layout()
plt.show()
按州/联邦领土绘制地图

我们将使用basemap和geopandas这两个Python库来创建按州/联邦领土汇总的地图。

!pip install geopandas
!pip install pyshp
!pip install shapely
!pip install basemap
import geopandas as gpd
import pandas as pd
from mpl_toolkits.basemap import Basemap

# Load shape file
map_data = gpd.read_file('https://raw.githubusercontent.com/geohacker/india/master/state/india_state.geojson')

# Convert data to required projection
map_data = map_data.to_crs(epsg=3857)

# Center the map to India
lat = map_data.centroid.y.mean()
lon = map_data.centroid.x.mean()

# Define the figure size and dpi
fig, ax = plt.subplots(figsize=(10, 10), dpi=300)

# Define the Basemap style
m = Basemap(ax=ax, llcrnrlon=68,llcrnrlat=5,urcrnrlon=98,urcrnrlat=38, projection='cyl', lat_0=lat, lon_0=lon)

# Add country borders
m.drawcountries(linewidth=1.5, linestyle='solid', color='black', zorder=50)

# Add states/provinces borders
m.drawstates(linewidth=0.5, linestyle='solid', color='gray', zorder=35)

# Add districts borders
m.drawmapboundary(linewidth=1.5, linestyle='solid', color='black', zorder=60)

# Get the names of the states/provinces
names = list(map_data['name'])
colors = ['darkgoldenrod', 'goldenrod', 'khaki', 'olive', 'darkolivegreen', 'olivedrab', 'yellowgreen', 'limegreen', 'forestgreen', 'green', 'darkgreen']

# Define the colors for each state/province
colordict = dict(zip(names, colors))

# Add data to the plot
for name, group in map_data.groupby('name'):
    shapes = [shape for shape in group['geometry']]
    c = colordict[name]
    for shape in shapes:
        x, y = shape.exterior.coords.xy
        x, y = m(list(x), list(y))
        m.fill(x, y, c)

# Show plot
plt.show()
结论

使用Python和covid19 India API,我们可以通过图形化可视化COVID-19印度统计数据,进一步提高对病毒的认识。