#> # A tibble: 6 × 4
#> country year urban rural
#> <chr> <chr> <dbl> <dbl>
#> 1 United Arab Emirates 1991 78.9 21.1
#> 2 Armenia 2003 64.1 35.9
#> 3 Gambia 2022 63.9 36.1
#> 4 Qatar 1967 87.6 12.4
#> 5 Montenegro 1970 26.9 73.1
#> 6 Democratic Republic of the Congo 2009 39.5 60.5
Prepare DataFrame for plot
Code
df_p <- df_merge |>filter( country %in% countries ) |>pivot_longer(cols =c(urban, rural),names_to ="pop",values_to ="pct" ) |>mutate(year =as.integer(year)) # year must be integer for animated plotting(gganimate)# arrange(desc(year))df_p |>sample_n(6)
#> # A tibble: 6 × 4
#> country year pop pct
#> <chr> <int> <chr> <dbl>
#> 1 Uzbekistan 1968 urban 36.1
#> 2 Tajikistan 2007 rural 73.5
#> 3 Turkmenistan 2015 urban 50.3
#> 4 Tajikistan 1975 rural 64.5
#> 5 Tajikistan 2023 urban 28.2
#> 6 Kyrgyzstan 2019 urban 36.6
Lineplot facetted by countries
Code
# Create plot facetted by countriesdf_p |>filter(country !="Russian Federation") |>ggplot(aes(x = year, y = pct, color = pop)) +geom_line() +geom_point() +transition_reveal(year) +scale_y_continuous(limits =c(0,100),breaks =seq(0, 100, 20),labels =function(x) paste0(x, "%"), ) +scale_x_continuous(limits =c(1950, 2025), breaks =seq(1950, 2025, 15)) +facet_wrap(~country) -> p_facetcountry# facet_wrap(~country, labeller = labeller(country = new_labels)) -> p_facetcountry# format plotp_facetcountry <- p_facetcountry +labs(title ="Percentage of rural and urban population by selected countries",caption ="Source: United Nations, Department of Economic and Social Affairs",x ="Years, 1950 - 2025",y ="Percentage of Population") +theme(plot.title =element_text(color ="dodgerblue4", size =12, face ="bold", hjust =0.5),plot.caption =element_text(color ="dodgerblue", size =8, face ="italic"),plot.background =element_rect(fill ="aliceblue"), legend.title =element_blank(),legend.background =element_blank(),legend.position ="top")p_facetcountry# to save#gganimate::animate(p_facetcountry, renderer = gifski_renderer(), height=500, width=700)