""" Plot detailed figures for each country """ import matplotlib.pyplot as pp from mpl_toolkits.axisartist.parasite_axes import HostAxes, ParasiteAxes import numpy as np import time as time_module import pickle import logging logging.getLogger().setLevel(logging.CRITICAL) import os import datetime import locale locale.setlocale(locale.LC_ALL, "de_DE.utf8") def plot(data, countries, pop, metadata, **kwargs): figsize = (10,5) for loc in data: if loc == "International": continue if loc == "World": continue path = "img/"+f"{loc}".replace(" ", "_").replace("'", "").replace("/", "") if not os.path.isdir(path): os.mkdir(path) # is this country vaccinating? is_vaccinating = True if data[loc]['total_vaccinations'][-1] > 0 else False if is_vaccinating: first_vac_report = np.argwhere(np.isnan(data[loc]['total_vaccinations']))[-1][0] + 1 vac_text = f"Impfstart{data[loc]['time'][first_vac_report]}" try: vac_rate = data[loc]['total_vaccinations'][-1]/metadata[loc]['population']*100 vac_text+= f"Impfrate{vac_rate:1.3f} %" except: pass try: immune_rate = (data[loc]['total_vaccinations'][-1] + data[loc]['total_cases'][-1])/metadata[loc]['population']*100 vac_text += f"Immunrate{immune_rate:1.3f} %" vac_text += f"Geimpfte{data[loc]['total_vaccinations'][-1]} %" except: pass try: vaccines = metadata[loc]['vaccines'] if 'vaccines' in metadata[loc] else "unknown" vac_text += f"Impfstoffe{vaccines}" except: pass total_cases = data[loc]['total_cases'][-1] total_deaths = data[loc]['total_deaths'][-1] today = datetime.datetime.now().strftime("%d.%m.%Y") if True: #not os.path.isfile(path+"/index.html") or False: # TODO enable html file generation with open(path+"/index.html", "w") as f: f.write(f""" CoVid19 in {loc}

Details zu {loc}

Zurück

Letztes Update: {datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d")}

Landesspezifische Kennzahlen

(Stand: {today}) {vac_text if is_vaccinating else ''}
ISO Code{metadata[loc]["iso_code"]}
Continent{metadata[loc]["continent"]}
Country name{metadata[loc]["location"]}
Population{metadata[loc]["population"]}
Population density{metadata[loc]["population_density"]}
Median age{metadata[loc]["median_age"]}
% older than 65{metadata[loc]["aged_65_older"]}
% older than 70{metadata[loc]["aged_70_older"]}
GDP per capita{metadata[loc]["gdp_per_capita"]}
Extreme poverty{metadata[loc]["extreme_poverty"]}
Cardiovascular death rate{metadata[loc]["cardiovasc_death_rate"]}
Diabetes prevalence{metadata[loc]["diabetes_prevalence"]}
female smokers (%){metadata[loc]["female_smokers"]}
male smokers (%){metadata[loc]["male_smokers"]}
Handwashing facilities{metadata[loc]["handwashing_facilities"]}
hospital beds per thousand inhabitants{metadata[loc]["hospital_beds_per_thousand"]}
life expectancy{metadata[loc]["life_expectancy"]}
human development index{metadata[loc]["human_development_index"]}
Absolute bestätigte Infektionsfälle{total_cases}
Absolute bestätigte Todesfälle{total_deaths}
Übersicht
Krankenhaussituation
Testsituation
Testing dataset: Hasell, J., Mathieu, E., Beltekian, D. et al. A cross-country database of COVID-19 testing. Sci Data 7, 345 (2020). DOI:10.1038/s41597-020-00688-8
Impfsituation


Zurück
Ein Infoservice von dukun.de; Anregungen gern per Mail; Proudly made with Python, Matplotlib, Numpy
""") # extract data time = data[loc]['time'] new_cases = data[loc]['new_cases'] new_deaths = data[loc]['new_deaths'] new_vaccinations = data[loc]['new_vaccinations'] total_cases = data[loc]['total_cases'] total_deaths = data[loc]['total_deaths'] total_vaccinations = data[loc]['total_vaccinations'] stringency_index = data[loc]['stringency_index'] reproduction_rate = data[loc]['reproduction_rate'] icu_patients = data[loc]['icu_patients'] hosp_patients = data[loc]['hosp_patients'] weekly_icu_admissions = data[loc]['weekly_icu_admissions'] weekly_hosp_admissions = data[loc]['weekly_hosp_admissions'] new_tests = data[loc]['new_tests'] total_tests = data[loc]['total_tests'] positive_rate = data[loc]['positive_rate'] tests_per_case = data[loc]['tests_per_case'] tests_units = data[loc]['tests_units'] people_fully_vaccinated = data[loc]['people_fully_vaccinated'] # plots ############### hospital occupation if True: fig, ax1 = pp.subplots(num=loc+"_hospitalization", figsize=figsize) ax2 = ax1.twinx() icu_map = ~np.isnan(weekly_icu_admissions) hosp_map = ~np.isnan(weekly_hosp_admissions) if not np.isnan(icu_patients).all() : ax2.plot(time, icu_patients, color="blue", label="ICU patients") if not np.isnan(hosp_patients).all() : ax2.plot(time, hosp_patients, color="green", label="Hospitalized patients") if not np.isnan(weekly_icu_admissions).all() : ax1.plot(np.array(time)[icu_map], np.array(weekly_icu_admissions)[icu_map], color="blue", linestyle="--", label="weekly ICU admissions") if not np.isnan(weekly_hosp_admissions).all() : ax1.plot(np.array(time)[hosp_map], np.array(weekly_hosp_admissions)[hosp_map], color="green", linestyle="--", label="weekly hospital admissions") axbounds = ax2.axis() if metadata[loc]["hospital_beds_per_thousand"] == "" or metadata[loc]["population"] == "": pass else: hospital_beds = float(metadata[loc]["hospital_beds_per_thousand"]) * float(metadata[loc]["population"]) / 1000 ax2.plot([axbounds[0], axbounds[1]], [hospital_beds]*2, color="k", label=f"total hospital beds: {hospital_beds:1.0f}") ax2.axis(axbounds) ax1.set_ylabel("admissions") ax2.set_ylabel("patients") fig.legend(frameon=False, loc="upper left", bbox_to_anchor=(0,1), bbox_transform=ax1.transAxes) ax1.set_title(f"Hospital situation in {loc}") pp.text(0.002,0.005, f"plot generated {time_module.strftime('%Y-%m-%d %H:%M')}, CC-by-sa-nc, origin: dukun.de/corona, datasource: ourworldindata.org/coronavirus-source-data", color="dimgrey", fontsize=8, transform=fig.transFigure) pp.savefig(path+"/hospitals.png") pp.close(fig) ############## test situation if True: fig, ax1 = pp.subplots(num=loc+"_tests", figsize=figsize) ax2 = ax1.twinx() if set(tests_units) == {''}: testunit = "unknown" elif len(set(tests_units).difference({''})) == 1: testunit = set(tests_units).difference({''}) .pop() else: testunit = "changing" print(loc, set(tests_units)) if np.isnan(new_tests).all() and not np.isnan(total_tests).all(): ttest_map = ~np.isnan(total_tests) total_tests = np.array(total_tests) new_tests = (total_tests[ttest_map][1:] - total_tests[ttest_map][:-1])/7. try: ax1.plot(np.array(time)[ttest_map][1:], new_tests, color="blue", linestyle="-", linewidth=2, label="new tests") except: pass elif not np.isnan(new_tests).all() : ntest_map = ~np.isnan(new_tests) try: ax1.plot(np.array(time)[ntest_map], np.array(new_tests)[ntest_map]/7, color="grey", linestyle="--", label="new tests") except: pass try: ax1.plot(np.array(time)[ntest_map][3:-3], np.convolve(np.array(new_tests)[ntest_map], np.ones((7,))/7, mode="valid")/7, color="blue", linewidth=2, label="new tests 7day mean") except: pass if not np.isnan(positive_rate).all(): prate_map = ~np.isnan(positive_rate) try: ax2.plot(np.array(time)[prate_map], np.array(positive_rate)[prate_map]*100, color="black", linestyle="-", linewidth=2, label="positive rate (%)") except: pass ax1.set_ylabel(f"tests (unit: {testunit})") ax2.set_ylabel("positive rate") fig.legend(frameon=False, loc="upper left", bbox_to_anchor=(0,1), bbox_transform=ax1.transAxes) ax1.set_title(f"Test situation in {loc}") pp.text(0.002,0.005, f"plot generated {time_module.strftime('%Y-%m-%d %H:%M')}, CC-by-sa-nc, origin: dukun.de/corona, datasource: ourworldindata.org/coronavirus-source-data", color="dimgrey", fontsize=8, transform=fig.transFigure) pp.savefig(path+"/tests.png") pp.close(fig) ########### vaccine situation if True: fig, ax1 = pp.subplots(num=loc+"_vac", figsize=figsize) ax2 = ax1.twinx() if not np.isnan(new_vaccinations).all(): ax1.plot(np.array(time), new_vaccinations, color="grey", linestyle="--", linewidth=1, label="new vaccinations") if not np.isnan(total_vaccinations).all(): ax2.plot(np.array(time), total_vaccinations, color="blue", linestyle="-", linewidth=1, label="total vaccinations") if not np.isnan(people_fully_vaccinated).all(): ax2.plot(np.array(time), people_fully_vaccinated, color="green", linestyle="-", linewidth=1, label="people fully vaccinated") immune_mask = ~np.isnan(total_vaccinations) & ~np.isnan(total_cases) assert len(total_vaccinations) == len(total_cases) total_immune = np.array(total_vaccinations) + np.array(total_cases) ax2.plot(np.array(time)[immune_mask], total_immune[immune_mask], color="green", linestyle="-", linewidth=1, label="total immune") ax1.set_ylabel(f"new vaccinations") ax2.set_ylabel("total vaccinations") fig.legend(frameon=False, loc="upper left", bbox_to_anchor=(0,1), bbox_transform=ax1.transAxes) title = f"Vaccination situation in {loc}" try: title += f", Vaccines: {metadata[loc]['vaccines']}" except: pass try: title += f", Immune rate: {immune_rate:1.2f}%" except: if loc == "Germany": print(f", Immune rate: {immune_rate:1.2f}%") exit() pass ax1.set_title(title) pp.text(0.002,0.005, f"plot generated {time_module.strftime('%Y-%m-%d %H:%M')}, CC-by-sa-nc, origin: dukun.de/corona, datasource: ourworldindata.org/coronavirus-source-data", color="dimgrey", fontsize=8, transform=fig.transFigure) pp.savefig(path+"/vaccinations.png") pp.close(fig) if __name__ == "__main__": import pickle with open("data.dump", "rb") as f: data, metadata = pickle.load(f) plot(data, [], {}, metadata=metadata)