Skip to content

Instantly share code, notes, and snippets.

@tofti
Last active April 7, 2020 17:01
Show Gist options
  • Save tofti/813927fea3d286f4ce24ba94fac67f4a to your computer and use it in GitHub Desktop.
Save tofti/813927fea3d286f4ce24ba94fac67f4a to your computer and use it in GitHub Desktop.
covid data plots
import requests
import matplotlib.pyplot as plt
import time
def main():
response = requests.get('https://covidtracking.com/api/states/daily')
data = response.json()
fig, subplots = plt.subplots(2, 2)
figure_row = 0
number_of_early_days_to_eliminate = 3
for state in ['NY', 'NJ']:
data_for_state = list(filter(lambda d: d['state'] == state, data))
data_for_state = data_for_state[:-number_of_early_days_to_eliminate]
data_for_state.reverse()
dates = list(map(lambda d: str(d['date']), data_for_state))
positive_cases = list(map(lambda d: d['positive'], data_for_state))
percent_changes_on_day = calculate_pct_change_on_day(positive_cases)
state_infected_rate_plot = subplots[figure_row][1]
state_infected_rate_plot.bar(dates[:-1], percent_changes_on_day)
state_infected_rate_plot.set_xlabel('Date')
state_infected_rate_plot.set_title(
'%s infection %% change from prior day\nlatest=%0.2f' % (state, percent_changes_on_day[-1]))
state_infected_rate_plot.set_aspect('auto')
state_infected_plot = subplots[figure_row][0]
state_infected_plot.bar(dates, positive_cases)
state_infected_plot.set_xlabel('Date')
state_infected_plot.set_title('%s infected (latest=%s)' % (state, positive_cases[-1]))
state_infected_plot.set_aspect('auto')
figure_row = figure_row + 1
for ax in fig.axes:
plt.sca(ax)
plt.xticks(rotation=90)
fig.tight_layout()
fig.suptitle('data from https://covidtracking.com\niain toft (https://github.com/tofti)', fontsize=14)
fig.show()
fig.set_size_inches(12, 10)
fig.savefig(str(int(round(time.time() * 1000))) + ".png")
def calculate_pct_change_on_day(data):
percent_changes_on_day = []
for i in range(len(data) - 1, 0, -1):
percent_change_on_day = 100.0 * (data[i] - data[i - 1]) / data[i - 1]
percent_changes_on_day.insert(0, percent_change_on_day)
return percent_changes_on_day
if __name__ == "__main__":
# execute only if run as a script
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment