I am trying to create a for loop function to make multiple ggplot line graphs, where only the x variable changes. However, the resulting plots show the variable name as title, and in the hover labels in the ggplotly, 'x' is shown instead of the variable name. I would like to use the variable labels that are already build in in the dataset, instead of the variable names. Can anyone help me with changing the function in such a way that the variable labels are used in the ggplotly instead of the variable names (column names of the df) and the variable label instead of just a 'x' in the hover label?
Below the code:
library(ggplot2)
library(cbsodataR)
library(plotly)
library(sjlabelled)
library(expss)
library(tidyr)
library(tidyverse)
library(sf)
library(dplyr)
library(stringr)
##Get data from dutch public data for one specific area
bevolking <- cbs_get_data("70072NED",
RegioS = "GM0736")
#Create other values for variable $Perioden
bevolking$Perioden <- 1995:2020
#Only show data as from 2011
bevolking <- bevolking %>%
filter(bevolking$Perioden>=2011)
#Select variables from dataset
bevolking <- bevolking %>%
select(c("Perioden", "Mannen_2", "Vrouwen_3"))
#Create for loop function
plots <- list()
for(nm in names(bevolking)) {
plots[[nm]] <- ggplot(bevolking, aes_string(y = nm, x = bevolking$Perioden)) +
geom_line(color = "#10A593", size = 1) +
theme_bw() +
theme(panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"),
axis.title.y=element_blank(),
axis.ticks.y=element_blank(),
axis.ticks.x=element_blank(),
axis.line.y=element_blank()) +
geom_point() +
labs(title = (paste(nm)))+
scale_x_continuous("Perioden",
labels = as.character(bevolking$Perioden),
breaks = bevolking$Perioden)
}
#Display one plot as a plotly from the above function
ggplotly(plots[["Mannen_2"]])