Skip to content

Instantly share code, notes, and snippets.

@eliardocosta
Last active June 19, 2022 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliardocosta/f27b04b41bf70d4c5fc9e38340b873f0 to your computer and use it in GitHub Desktop.
Save eliardocosta/f27b04b41bf70d4c5fc9e38340b873f0 to your computer and use it in GitHub Desktop.
Animação conceito de média móvel. Veja o link https://twitter.com/EliardoGCosta/status/1385725754877616130?s=20
# Adaptacao da funcao 'mwar.ani' do pacote 'animation' do R para
# ilustrar o conceito de media movel para k observacoes consecutivas
mm.ani = function(x, k = 7, mat = matrix(1:2, 2),
widths = rep(1, ncol(mat)),
heights = rep(1, nrow(mat)), lty.rect = 2, ...) {
nmax = ani.options('nmax')
n = length(x)
if (k > n)
stop('A largura da janela k deve ser menor que o tamanho de x!')
idx = matrix(1:k, nrow = k, ncol = n - k + 1) +
matrix(rep(0:(n - k), each = k), nrow = k, ncol = n - k + 1)
phi = se = numeric(ncol(idx))
j = 1
for (i in 1:ncol(idx)) {
if (j > nmax)
break
phi[i] = mean(x[idx[, i]])
j = j + 1
}
layout(mat, widths, heights)
j = 1
minx = maxx = NULL
for (i in 1:ncol(idx)) {
if (j > nmax) break
dev.hold()
plot(x, xlab = 'Dia', ylab = 'Núméro de Mortes', type = "l",
lwd = 1.5)
minx = min(x[idx[, i]])
maxx = max(x[idx[, i]])
rect(i, minx, (i + k - 1), maxx, lty = lty.rect, border = i,
lwd = 1.5)
plot(x, xlim = c(1, n), type = 'n', ylab = 'Média Móvel',
xlab = 'Dia')
points(1:i + k/2 - 0.5, phi[1:i], col = 1:i, pch = 19)
ani.pause()
j = j + 1
}
invisible(list(phi = phi))
}
# exemplo
library(animation)
num.mor <- c(0, 1, 0, 1, 2, 0, 2, 0, 1, 3, 3, 0, 2, 0, 1, 3, 1, 2,
0, 1, 1, 2, 4, 4, 4, 2, 4, 0, 5, 5, 6, 2, 8, 4, 1, 7,
5, 6, 8, 5, 7, 7, 8, 14, 8, 12, 10, 8, 9, 8, 12, 10,
9, 9, 7, 9, 14, 9, 10, 13, 7, 6, 15, 9, 10, 4, 9, 7,
8, 3, 6, 0)
mm.ani(num.mor)
# salvando a animacao (Linux)
saveVideo({
par(mar = c(3, 3, 1, 0.5), mgp = c(2, 0.5, 0), tcl = -0.3,
cex.axis = 1, cex.lab = 1, cex.main = 1)
ani.options(interval = 0.25, nmax = length(x))
mm.ani(num.mor)
}, video.name = "media_movel.mp4",
other.opts = "-pix_fmt yuv420p -b 300k")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment