Created
August 18, 2017 11:58
-
-
Save peterdalle/c995be3d2e30e57f6134dcb3ddcd7b61 to your computer and use it in GitHub Desktop.
Extrapolera SD:s valresultat och lägg in passande animerad gif...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
library(magick) | |
# --- Extrapolera --- | |
setwd("~/GU/code/rcode") | |
df <- na.exclude(polls.sd) # polls.sd kommer från Polls.r | |
# Skapa modell. | |
df$pred <- predict(lm(SD ~ poly(PublDate, 1), data=df)) | |
# Skapa plot. | |
gg <- ggplot(df, aes(x = PublDate, y=SD)) + | |
geom_line() + | |
scale_y_continuous(limits=c(0, 110)) + | |
scale_x_date(date_labels = "%Y", date_breaks = "2 years") + | |
geom_hline(aes(yintercept=0)) + | |
labs(title="Stöd för Sverigedemokraterna", subtitle="Extrapolerat från nuvarande opinionsundersökningar", x="År", y="Procent") | |
# Plotta modell med data. | |
gg + geom_line(aes(y = pred), color="red") + theme_minimal() | |
# Extrapolera utifrån modell. | |
pred <- data.frame(PublDate = seq.Date(as.Date("2017-06-01"), as.Date("2040-10-01"), "months")) | |
pred$SD <- predict(lm(SD ~ poly(PublDate, 1), data=df), newdata=pred) | |
gg.ext <- gg + | |
geom_line(color="red", data=pred) + | |
scale_y_continuous(labels=scales::comma, limits=c(0, 100), breaks=seq(0, 100, 20)) + | |
theme_minimal() + | |
theme(axis.text.x = element_text(angle=0)) | |
gg.ext | |
# --- Lägg ihop bilder --- | |
# Spara först plot. | |
gg.ext + ggsave(filename = paste0("extrapolering.png"), width=9, height=6, dpi=100) | |
# Läs in plot. | |
plot <- image_read("extrapolering.png") | |
gif_raw <- image_read("https://media.giphy.com/media/26ufdipQqU2lhNA4g/giphy.gif") | |
# Skala om gif. | |
gif <- gif_raw # %>% image_scale("125") | |
# Slå ihop gif animation med plot. | |
frames <- lapply(gif, function(frame) { | |
image_composite(plot, frame, offset = "+600+300") | |
}) | |
animation <- image_animate(image_join(frames)) | |
# Spara. | |
image_write(animation, "extrapolering.gif") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment