Animated lollipop chart
library(ggplot2)
library(gganimate)
library(dplyr)
df <- readxl::read_excel("longit_data.xlsx")
str(df) # Index is how much interest there is in a Subject over seasons where Index = 100 for 1.1.2019
## tibble [15 x 3] (S3: tbl_df/tbl/data.frame)
## $ Quarter: POSIXct[1:15], format: "2019-01-01" "2019-01-01" ...
## $ Index : num [1:15] 100 100 100 95 103 95 20 106 105 50 ...
## $ Subject: chr [1:15] "Skiing" "Maths" "Cooking" "Skiing" ...
df$Quarter <- as.character(df$Quarter)
df_1 <- df %>%
filter(Quarter == "2020-01-01")
str(df_1)
## tibble [3 x 3] (S3: tbl_df/tbl/data.frame)
## $ Quarter: chr [1:3] "2020-01-01" "2020-01-01" "2020-01-01"
## $ Index : num [1:3] 105 112 105
## $ Subject: chr [1:3] "Skiing" "Maths" "Cooking"
ggplot(df_1,
aes(x = Subject, y = Index, label = Subject, color = Subject)) +
geom_point(stat = 'identity', size = 13) +
geom_segment(aes(
y = 100,
x = Subject,
yend = Index,
xend = Subject)
) +
geom_text(color = 'black', size = 3) +
coord_flip() +
theme(legend.position = 'none')
df$Quarter <- as.Date(df$Quarter) # numeric, POSIXct, Date, difftime, orhms
str(df)
## tibble [15 x 3] (S3: tbl_df/tbl/data.frame)
## $ Quarter: Date[1:15], format: "2019-01-01" "2019-01-01" ...
## $ Index : num [1:15] 100 100 100 95 103 95 20 106 105 50 ...
## $ Subject: chr [1:15] "Skiing" "Maths" "Cooking" "Skiing" ...
ggplot(df,
aes(x = Subject, y = Index, label = Subject, color = Subject)) +
geom_point(stat = 'identity', size = 16) +
geom_segment(aes(
y = 100,
x = Subject,
yend = Index,
xend = Subject)
) +
geom_text(color = 'black', size = 3) +
coord_flip() +
theme(legend.position = 'none') +
labs(title = 'Quarter: {frame_time}', x = 'Quarter', y = 'Index') +
transition_time(Quarter) +
ease_aes('linear')
#anim_save('subjects.gif')
Another example
library(gapminder) # Hans Rosling data
#+ static version
p <- ggplot(
gapminder,
aes(x = gdpPercap, y = lifeExp,
size = pop, color = country)
) +
geom_point(
alpha = 0.7,
show.legend = F
) +
scale_color_manual(
values = country_colors
) +
scale_size(range = c(2, 12)) +
scale_x_log10() +
facet_wrap(~continent) +
labs(
x = 'GDP per capita',
y = 'life expectancy'
) +
theme_bw()
p
anim <- p +
transition_time(year) + # animate over year, a continuous variable
labs(title = 'Year: {frame_time}') # from 'glue' package
anim # there is interpellation to ensure that animation runs smoothly!
gapminder_1 <- gapminder %>%
filter(country == "Poland" | country == "Finland")
p_1 <- ggplot(
gapminder_1,
aes(x = gdpPercap, y = lifeExp,
size = pop, color = country)
) +
geom_point(
alpha = 0.7,
show.legend = F
) +
scale_color_manual(
values = country_colors
) +
scale_size(range = c(2, 12)) +
scale_x_log10() +
labs(
x = 'GDP per capita',
y = 'life expectancy'
)
p_1 +
transition_time(year) +
shadow_mark()