Python - Data visualization using covid19 India API - GeeksforGeeks

06 Aug, 2021
API (Application Programming Interface) is a computing interface that interacts between multiple software. 
JSON (JavaScript Object Notation) is a lightweight format for storing and transporting data. It is used to send data from server to web.
Required modules: 
matplotlib
requests
pandas
json
Commands to install modules:
pip install matplotlib
pip install requests
pip install pandas
Steps:
Importing all required modules.Calling API and getting JSON data.Getting the State Wise District Data.Visualization of data.
Importing all required modules.
Calling API and getting JSON data.
Getting the State Wise District Data.
Visualization of data.
The below URL redirects you to API https://api.covid19india.org/state_district_wise.json
Importing all required modules
Python3
#importing modulesimport jsonimport requestsimport pandas as pdimport matplotlib.pyplot as plt
 
 
Function for getting JSON data from API and Visualization of Data
 
Python3
#storing the url in the form of stringurl="https://api.covid19india.org/state_district_wise.json" #function to get data from apidef casesData():    #getting the json data by calling api    data = ((requests.get(url)).json())    states = []
 
 
Getting State Names available in JSON Data
 
Python3
# getting statewise datafor state in states:        f = (data[state]['districtData'])# states data available in JSON Data'''0 State Unassigned1 Andaman and Nicobar Islands2 Andhra Pradesh3 Arunachal Pradesh4 Assam5 Bihar6 Chandigarh7 Chhattisgarh8 Delhi9 Dadra and Nagar Haveli and Daman and Diu10 Goa11 Gujarat12 Himachal Pradesh13 Haryana14 Jharkhand15 Jammu and Kashmir16 Karnataka17 Kerala18 Ladakh19 Lakshadweep20 Maharashtra21 Meghalaya22 Manipur23 Madhya Pradesh24 Mizoram25 Nagaland26 Odisha27 Punjab28 Puducherry29 Rajasthan30 Sikkim31 Telangana32 Tamil Nadu33 Tripura34 Uttar Pradesh35 Uttarakhand36 West Bengal'''
Getting the state-wise Data
Python3
# getting statewise datafor state in states:    f = (data[state]['districtData'])    tc = []    dis = []    act, con, dea, rec = 0, 0, 0, 0     # getting districtwise data    for key in (data[state]['districtData']).items():        district = key[0]        dis.append(district)        active = data[state]['districtData'][district]['active']        confirmed = data[state]['districtData'][district]['confirmed']        deaths = data[state]['districtData'][district]['deceased']        recovered = data[state]['districtData'][district]['recovered']        if district == 'Unknown':            active, confirmed, deaths, recovered = 0, 0, 0, 0        tc.append([active, confirmed, deaths, recovered])        act = act + active        con = con + confirmed        dea = dea + deaths        rec = rec + recovered    tc.append([act, con, dea, rec])    dis.append('Total')    parameters = ['Active', 'Confirmed', 'Deaths', 'Recovered']
Creating DataFrame Using pandas
Python3
# creating a dataframedf = pd.DataFrame(tc, dis, parameters)print('COVID - 19', state, 'District Wise Data')print(df)
Data Visualization Using Matplotlib
Python3
# plotting of dataplt.bar(dis, df['Active'], width=0.5, align='center')fig = plt.gcf()fig.set_size_inches(18.5, 10.5)plt.xticks(rotation=75)plt.show()print('*'*100)
Final casesData() function code
Python3
# function to get data from apidef casesData():    # getting the json data by calling api    data = ((requests.get(url)).json())    states = []     # getting states    for key in data.items():        states.append(key[0])     # getting statewise data    for state in states:        f = (data[state]['districtData'])        tc = []        dis = []        act, con, dea, rec = 0, 0, 0, 0         # getting districtwise data        for key in (data[state]['districtData']).items():            district = key[0]            dis.append(district)            active = data[state]['districtData'][district]['active']            confirmed = data[state]['districtData'][district]['confirmed']            deaths = data[state]['districtData'][district]['deceased']            recovered = data[state]['districtData'][district]['recovered']            if district == 'Unknown':                active, confirmed, deaths, recovered = 0, 0, 0, 0            tc.append([active, confirmed, deaths, recovered])            act = act + active            con = con + confirmed            dea = dea + deaths            rec = rec + recovered        tc.append([act, con, dea, rec])        dis.append('Total')        parameters = ['Active', 'Confirmed', 'Deaths', 'Recovered']         # creating a dataframe        df = pd.DataFrame(tc, dis, parameters)        print('COVID - 19', state, 'District Wise Data')        print(df)         # plotting of data        plt.bar(dis, df['Active'], width=0.5, align='center')        fig = plt.gcf()        fig.set_size_inches(18.5, 10.5)        plt.xticks(rotation = 75)        plt.show()        print('*' * 100)
Python3
# importing modulesimport jsonimport requestsimport pandas as pdimport matplotlib.pyplot as plt # storing the url in the form of stringurl = "https://api.covid19india.org/state_district_wise.json" # function to get data from api  def casesData():    # getting the json data by calling api    data = ((requests.get(url)).json())    states = []     # getting states    for key in data.items():        states.append(key[0])     # getting statewise data    for state in states:        f = (data[state]['districtData'])        tc = []        dis = []        act, con, dea, rec = 0, 0, 0, 0         # getting districtwise data        for key in (data[state]['districtData']).items():            district = key[0]            dis.append(district)            active    = data[state]['districtData'][district]['active']            confirmed = data[state]['districtData'][district]['confirmed']            deaths    = data[state]['districtData'][district]['deceased']            recovered = data[state]['districtData'][district]['recovered']            if district == 'Unknown':                active, confirmed, deaths, recovered = 0, 0, 0, 0            tc.append([active, confirmed, deaths, recovered])            act = act + active            con = con + confirmed            dea = dea + deaths            rec = rec + recovered        tc.append([act, con, dea, rec])        dis.append('Total')        parameters = ['Active', 'Confirmed', 'Deaths', 'Recovered']         # creating a dataframe        df = pd.DataFrame(tc, dis, parameters)        print('COVID - 19', state, 'District Wise Data')        print(df)         # plotting of data        plt.bar(dis, df['Active'], width = 0.5, align = 'center')        fig = plt.gcf()        fig.set_size_inches(18.5, 10.5)        plt.xticks(rotation = 75)        plt.show()        print('*' * 100)  # states data available through API'''0 State Unassigned1 Andaman and Nicobar Islands2 Andhra Pradesh3 Arunachal Pradesh4 Assam5 Bihar6 Chandigarh7 Chhattisgarh8 Delhi9 Dadra and Nagar Haveli and Daman and Diu10 Goa11 Gujarat12 Himachal Pradesh13 Haryana14 Jharkhand15 Jammu and Kashmir16 Karnataka17 Kerala18 Ladakh19 Lakshadweep20 Maharashtra21 Meghalaya22 Manipur23 Madhya Pradesh24 Mizoram25 Nagaland26 Odisha27 Punjab28 Puducherry29 Rajasthan30 Sikkim31 Telangana32 Tamil Nadu33 Tripura34 Uttar Pradesh35 Uttarakhand36 West Bengal''' #Driver CodecasesData()
Output:
gabaa406
JSON
Python-matplotlib
Technical Scripter 2020
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary