Example data
df_1 <- data.frame(a1 = abs(rnorm(50, 1, 1)),
b1 = rnorm(50, 1, 1))
df_2 <- data.frame(a1 = rnorm(50, 1, 10),
b1 = rnorm(50, 1, 1))
df_3 <- data.frame(a1 = rnorm(50, 1, 10),
b1 = rnorm(50, 1, 1))
df_all <- list (df_1, df_2, df_3)
I use ggplot like this and I get a satisfactory effect
ggplot() +
geom_line(data = df_all[[1]], aes(x = a1, y = b1), color = "blue", size = 0.05) +
geom_line(data = df_all[[2]], aes(x = a1, y = b1), color = "blue", size = 0.05) +
geom_line(data = df_all[[3]], aes(x = a1, y = b1), color = "blue", size = 0.05)
The number of data frames changes every day, so a better solution is needed. I thought of this solution (of course it is not correct)
lapply(df_all, ggplot()+
function(x) (geom_line(x, aes(x=a1, y=b1), color='blue'))
)
I don't want to convert the list to one frame
Fortunately, ggplot
can add lists of geoms:
ggplot() +
lapply(df_all, function(dat) geom_line(data=dat, aes(a1, b1), color="blue", size=0.05))
To demonstrate, I'll do this slightly differently by changing the colors:
ggplot() +
Map(df_all, c("blue","darkgreen","red"),
f = function(dat,col) geom_line(data=dat, aes(a1, b1), color=col))
(Slightly thicker and varying colors, for demo here.)
Though frankly, I think it's generally better to combine them and have a single frame, using ggplot's native aes
thetic mapping for colors (even if you eschew the legend).
ggplot() +
geom_line(aes(a1, b1, group = id, color = id),
data = dplyr::bind_rows(df_all, .id = "id")) +
scale_color_manual(
values = c("1"="blue", "2"="darkgreen", "3"="red")
)
I've taken the liberty of adding color=id
to the aesthetics, again just to show that the separate lines are there. (The group=id
needs to stay, though.)
The bind_rows
is not required if you aren't using dplyr
, we can also use data.table::rbindlist(.., idcol="id")
. Base R requires a little more work to get the ID column in there, though it's far from prohibitive.
The one thing that this method requires, though, is that the aesthetic variables are the same name, so a1
and b1
need to be the same in all of the frames. (If not, it might be easy enough to rename them as you combine them ...)