I have some csv files and I need to produce the same plot from each one of them. I have read the csv files in R as dataframes and put them together in a list, and each element of the list is named after the original file.
Question
How do I title the plots based on each csv file's name? I am new to both ggplot and regex functions.
This is what I have tried; first I create some toy dataframes to "mimic" the original data and put them in a list:
library(tidyverse)
# Create four dataframes
df1_09 <- data.frame(
first_column = c(1, 2, 3, 4),
second_column = c(5, 6, 7, 8)
)
df1_10 <- data.frame(
first_column = c(4, 2, 3, 1),
second_column = c(8, 6, 7, 5)
)
df2_09 <- data.frame(
first_column = c(9, 10, 11, 12),
second_column = c(13, 14, 15, 16)
)
df2_10 <- data.frame(
first_column = c(12, 10, 11, 9),
second_column = c(16, 14, 15, 13)
)
list_of_df <- list(df1_09, df1_10, df2_09, df2_10)
Now I create the function that I will use to plot the dataframes. I would like the name of the dataframe as main title. So I have tried:
# Create plot function
plot_data <- function(data) {
ggplot(data) +
geom_point(aes(x = data[, 1], y = data[, 2])) +
xlim(0, 12) +
ylim(5, 16) +
ggtitle(paste(names(data))) +
xlab("x axis") +
ylab("y axis") +
theme_bw()
}
myplots <- list()
myplots <- lapply(list_of_df, plot_data)
The code works, but if I check the list's structure I get the weirdest output ever (I just pasted a small part of the output below)
str(myplots)
#> List of 4
#> $ df1_09:List of 9
#> ..$ data :'data.frame': 4 obs. of 2 variables:
#> .. ..$ first_column : num [1:4] 1 2 3 4
#> .. ..$ second_column: num [1:4] 5 6 7 8
#> ..$ layers :List of 1
#> .. ..$ :Classes 'LayerInstance', 'Layer', 'ggproto', 'gg' <ggproto object: Class LayerInstance, Layer, gg>
#> aes_params: list
#> compute_aesthetics: function
#> compute_geom_1: function
#> compute_geom_2: function
#> compute_position: function
#> compute_statistic: function
#> data: waiver
#> draw_geom: function
#> finish_statistics: function
In addition, if I check the first plot I can see it has picked the column name, not the dataframe's name:
myplots[[1]]

Created on 2021-04-19 by the reprex package (v0.3.0)
