I have a dataframe in R and I want to write a helper function to enable me to easily show multiple lines on top of each other.
I want to call the method with a list of boolean values indicating which columns of the data frame to visualize. For several reasons, I would like to name them in order, ie "Element1", "Element2" etc.
I would have liked to be able to just do this in a loop, ie, for each boolean in the list, if it is TRUE, do the following:
- add the line to the plot with the appropriate name
- append the name to the list of names
Since this is a relatively long string (and ideally I would like to do all of this automatically in as little code as possible) I would like to use a variable in which I store that string and update it every time I need a new line. However, every time this string is updated, the line is updated too. This means that any time I change a variable which I used to set the line's characteristics, the line is changed accordingly.
So when I add a line with the name in a string variable, and I update this variable every time I add a new line, there will only be one line in the plot in the end because they all ended up having the same name. Same thing if I try referencing columns with an integer i which I increment every loop - when i is incremented, the column that the line displays is changed accordingly.
How can I do this in the most aesthetically and functionally appropriate way?
overlay.graphs <- function(df, prog = c(TRUE, TRUE, TRUE)) {
i <- 1
names <- "Val"
n <- nrow(df)
gg <- ggplot2::ggplot(data = df, ggplot2::aes(x = "Date")) +
ggplot2::geom_line(ggplot2::aes(y = Price, color = "Val"))
for (bool in prog) {
if (bool) {
temp <- paste("Prog", i)
gg <- gg + ggplot2::geom_line(ggplot2::aes(y = df[, temp], color = temp))
names <- c(names, temp)
}
i <- i + 1
}
gg + ggplot2::scale_color_manual(name = "Legend", breaks = names, values = c("steelblue", "firebrick", "sienna", "seagreen"))
}
I would expect ggplot2 to draw a line for each call to geom_line, however, since any time the variable which was used to set attributes for the line is changed, the line is also updated, this does not seem to work.
How would you go about this?