For Loop Within Custom Function to Create Ggplot Time Series Plots

for loop within custom function to create ggplot time series plots

The following works.

You were looping along all columns including column "DATE", which is supposed to be the x axis and the loop variable was integer so in the plot's aesthetic y = i was an integer, not a column name.

Note that I call windows() to open a new graphic window. Remove this if not needed.

Plot_Graph <- function(DF, na.rm = TRUE){
nm = names(DF)[-1]
for (i in nm) {
g <- ggplot(DF, aes(x = DATE, y = get(i))) +
geom_point()
windows()
print(g)
}
}

Plot_Graph(philly_df_new)

using a custom ggplot function in a loop of variables from a list

Unless for some reason you want to be able to pass unquoted parameters, I would change the function so it only admits strings and use the .data[[]] pronoun which is the recommended way in the last versions of dplyr and ggplot. Its purpose is obvious to read when compared with quotes and bangs !! (Although someone may argue the opposite).

library(ggplot2)

gg_hist <- function(data, x){
ggplot(data,
aes(x = .data[[x]] )) +
geom_histogram()
}

gg_hist(mtcars, "hp") # Note now I use "hp" and not hp

vars <- c("mpg","hp")

for (variable in vars) {
p <- gg_hist(mtcars, variable)
print(p)
}

The main source for this would be the dplyr official documentation. It is true that is not a gpplot2 source but most of what is explained there is applicable. Other source for ggplot2 especifically is this rconf2020 slides. Hope this helps.

For loop in ggplot for multiple time series viz

You could try following code using lapply instead of for loop.

# transforming timestamp in date object
df$timestamp <- as.Date(df$timestamp, format = "%d/%m/%Y")
# create function that is used in lapply
plotlines <- function(variables){
ggplot(df, aes(x = timestamp, y = variables)) +
geom_line()
}
# plot all plots with lapply
plots <- lapply(df[names(df) != "timestamp"], plotlines) # all colums except timestamp
plots

How to create several plots with different names at once (ggplot in a loop)

You can save the plots in a list. Here is a for loop to do that.

library(ggplot2)

variable_to_be_plotted<-c("a","b","c")
list_plots <- vector('list', length(variable_to_be_plotted))

for (i in seq_along(list_plots)) {
list_plots[[i]] <- ggplot(data = mydata,
aes(.data[[variable_to_be_plotted[i]]])) + geom_boxplot()
}

Individual plots can be accessed via list_plots[[1]], list_plots[[2]] etc.

how to add layers in ggplot using a for-loop

One approach would be to reshape your data frame from wide format to long format using function melt() from library reshape2. In new data frame you will have x1 values, variable that determine from which column data came, and value that contains all original y values.

Now you can plot all data with one ggplot() and geom_line() call and use variable to have for example separate color for each line.

 library(reshape2)
df.long<-melt(df,id.vars="x1")
head(df.long)
x1 variable value
1 1 y1 2.0
2 2 y1 5.4
3 3 y1 7.1
4 4 y1 4.6
5 5 y1 5.0
6 1 y2 0.4
ggplot(df.long,aes(x1,value,color=variable))+geom_line()

Sample Image

If you really want to use for() loop (not the best way) then you should use names(df)[-1] instead of seq(). This will make vector of column names (except first column). Then inside geom_line() use aes_string(y=i) to select column by their name.

plotAllLayers<-function(df){
p<-ggplot(data=df,aes(df[,1]))
for(i in names(df)[-1]){
p<-p+geom_line(aes_string(y=i))
}
return(p)
}

plotAllLayers(df)

Sample Image

How to write a function to loop through variables and plot using ggplot

One way would be to split data in every 3 columns and apply the code to each list.

library(gridExtra)
library(tidyverse)
library(rlang)

temp <- split.default(df, gl(ncol(myData)/3, 3)) %>%
map(~{
x <- syms(names(.))
ggplot(., aes(x = !!x[[1]], y = !!x[[2]])) + geom_raster(aes(fill = !!x[[3]]))
})
grid.arrange(grobs = temp)

Sample Image

data

Applied this on limited data of 2 rows.

myData <- structure(list(x1 = c(-0.8523122, -0.564995), x2 = c(-2.737223, 
-2.737223), yhat = c(-6.562228, -6.562228), x11 = c(-0.8523122,
-0.564995), x3 = c(-1.450288, -1.450288), yhat1 = c(0.464739,
0.464739), x12 = c(-0.8523122, -0.564995), x4 = c(-1.267759,
-1.267759), yhat2 = c(-4.624147, -4.624147), x21 = c(-2.737223,
-2.267001), x31 = c(-1.450288, -1.450288), yhat3 = c(-0.6858007,
-0.6858007)), class = "data.frame", row.names = c("1", "2"))

Multiple plots using for loop

Try using lapply :

library(ggplot2)
p.vec <- c("disp","mpg")

lapply(p.vec, function(x) {
p <- ggplot(data = mtcars, aes(x = mpg, y= .data[[x]])) +geom_jitter()
ggsave(sprintf('plot_%s.jpg', x))
})

Instead of .data[[x]] you can also use any of the option from this answer.



Related Topics



Leave a reply



Submit