Coronavirus Trend In Spain

April 7, 2020 • edited April 22, 2020

After the video from Minute Earth about the coronavirus, I’ve decided to plot the same data but only for Spain by province. This gives a good view of which provinces are managing to stop the virus.

You have to watch the video to understand the following plots.

Not that your understand… enjoy it.

You can double click on a label to Isolate it or single click to hide.

Code could not finish, this are some reasons why this happen. - Plot name not defined. The first parameter of the shortcode is the name. - There is a syntax error. check browser console.
Code could not finish, this are some reasons why this happen. - Plot name not defined. The first parameter of the shortcode is the name. - There is a syntax error. check browser console.
Code could not finish, this are some reasons why this happen. - Plot name not defined. The first parameter of the shortcode is the name. - There is a syntax error. check browser console.

leave your comments bellow.

Click here to see the code:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import pandas as pd
import requests
import json

from datetime import timedelta,datetime, date
from io import StringIO


codigos = {'AN':'Andalucía',
'AR':'Aragón',
'AS':'Asturias',
'CN':'Canarias',
'CB':'Cantabria',
'CM':'Castilla-La Mancha',
'CL':'Castilla y León',
'CT':'Cataluña',
'EX':'Extremadura',
'GA':'Galicia',
'IB':'Islas Baleares',
'RI':'La Rioja',
'MD':'Comunidad de Madrid',
'MC':'Región de Murcia',
'NC':'Navarra',
'PV':'País Vasco',
'VC':'Comunidad Valenciana',
'CE':'Ceuta',
'ML':'Melilla'
}


population = pd.read_html("https://es.wikipedia.org/wiki/Anexo:Provincias_y_ciudades_aut%C3%B3nomas_de_Espa%C3%B1a")[0]
population.Población = population.Población.str.replace(".","").astype(int)
population = population.groupby("Comunidad autónoma").sum()["Población"].to_dict()

r = requests.get("https://covid19.isciii.es/resources/serie_historica_acumulados.csv")
text = r.text[0:r.text.index("NOTA")]
spain = pd.read_csv(StringIO(text)).dropna(subset=["CCAA"])
spain.columns =  [c.strip() for c in spain.columns]
spain["Provincia"] = spain["CCAA"].apply(lambda x: codigos[x])
spain["Poblacion"] = spain.Provincia.apply(lambda x: population[x])
spain["Nuevos_Casos"] = spain.groupby("Provincia")["CASOS"].diff()
spain["Casos_x_1000"] = 1000*spain.CASOS / spain.Poblacion
spain["Nuevos_Casos_x_1000"] =  1000* spain.Nuevos_Casos / spain.Poblacion
spain["Nuevos_Casos_Ultima_Semana"] = spain.groupby("Provincia")["Nuevos_Casos"].rolling(7).sum().reset_index(0,drop=True)
spainc = spain[spain.CASOS > 1000]

fig = {
    "data":[ {
        "y":spainc[(spainc["Provincia"]==cat)]["Nuevos_Casos_Ultima_Semana"].to_list(),
        "x":spainc[(spainc["Provincia"]==cat)]["CASOS"].to_list(),
        "text": spainc[(spainc["Provincia"]==cat)]["FECHA"].to_list(),
        "name": cat,
        "mode": "lines+markers"
    } for cat in sorted(spain["Provincia"].unique()) ],
    "layout":{
        "title":"Exito frenando el coronavirus por comunidad",
        "xaxis":{
            "title": "Casos Totales",
            "type":"log"
        },
        "yaxis":{
            "title": "Casos Nuevos Ultima Semana",
            "type":"log"
        }
    }

}
local = json.dumps(fig)


aggregated = spain.groupby(["FECHA"],as_index=False).sum()[["FECHA","CASOS","Nuevos_Casos","Nuevos_Casos_Ultima_Semana"]].sort_values("CASOS")
fig = {
    "data": [{
        "y":aggregated["Nuevos_Casos_Ultima_Semana"].to_list(),
        "x":aggregated["CASOS"].to_list(),
        "name": "casos totales",
        "mode": "lines+markers"
    }],
    "layout":{
        "title":"Exito frenando el coronavirus total",
        "xaxis":{
            "title": "Casos Totales",
            "type":"log"
        },
        "yaxis":{
            "title": "Casos Nuevos Ultima Semana",
            "type":"log"
        }
    }

}
total = json.dumps(fig)


from scipy.optimize import curve_fit
import numpy as np
from numpy import linspace

aggregated["UNIX"] = pd.to_datetime(aggregated["FECHA"],dayfirst=True)

def gauss(x, A,mu,sigma):
    return A*np.exp(-(x-mu)**2/(2.*sigma**2))

p0 = [50000, 40, 5]

popt, pcov = curve_fit(gauss,
                       aggregated.index.to_series(),
                       aggregated['Nuevos_Casos_Ultima_Semana'],
                       p0,
                       method='dogbox')
x = np.linspace(1, 90, 90)
y = gauss(x, *popt)
xdate = pd.Series(x).apply(lambda x: aggregated.UNIX.min() + timedelta(days=x) )
prediction = pd.DataFrame(data={"y":pd.Series(y),"UNIX":xdate})
prediction = prediction[prediction.y > 1]

fig = {
    "data":[ {
        "y":aggregated["Nuevos_Casos_Ultima_Semana"],
        "x":aggregated.UNIX,
        "name": "Nuevos Casos Ultima Semana",
        "mode": "lines+markers"
    },{
        "y":prediction.y,
        "x":prediction.UNIX,
        "name": "prediccion",
        "mode": "lines"
    }  ],
    "layout":{
        "yaxis":{
        }
    }
}
prediction = json.dumps(fig)

template = """
<div class="figure">
<div class="figure-plot" id="local_corona">
	Code could not finish, this are some reasons why this happen.
	- Plot name not defined. The first parameter of the shortcode is the name.
	- There is a syntax error. check browser console.
</div>
<script>
  function draw(){
	test = document.getElementById("local_corona");
	if (test == null){
		console.log("The plot name is not defined")
		return
	}

	fig = null
	
fig = %s


	if (!fig) {
		test.innerText = "ERROR: fig variable is not defined"
		return
	}
	test.innerText = null
	Plotly.plot(test ,fig);
  }
  draw()
</script>
</div>

<div class="figure">
<div class="figure-plot" id="total_corona">
	Code could not finish, this are some reasons why this happen.
	- Plot name not defined. The first parameter of the shortcode is the name.
	- There is a syntax error. check browser console.
</div>
<script>
  function draw(){
	test = document.getElementById("total_corona");
	if (test == null){
		console.log("The plot name is not defined")
		return
	}

	fig = null
	
fig = %s


	if (!fig) {
		test.innerText = "ERROR: fig variable is not defined"
		return
	}
	test.innerText = null
	Plotly.plot(test ,fig);
  }
  draw()
</script>
</div>

<div class="figure">
<div class="figure-plot" id="prediction_corona">
	Code could not finish, this are some reasons why this happen.
	- Plot name not defined. The first parameter of the shortcode is the name.
	- There is a syntax error. check browser console.
</div>
<script>
  function draw(){
	test = document.getElementById("prediction_corona");
	if (test == null){
		console.log("The plot name is not defined")
		return
	}

	fig = null
	
fig = %s


	if (!fig) {
		test.innerText = "ERROR: fig variable is not defined"
		return
	}
	test.innerText = null
	Plotly.plot(test ,fig);
  }
  draw()
</script>
</div>
"""

print(template % (local, total, prediction))

Refer to Add Plots With Hugo Shortcodes if you do not understand the previus template.

References

blogcoronavirus

The Clap Button

2020-03-30 Weekend Learnings