10

There are two data frames - df1 & df2 from which I need to create line plot using ggplot2 and display on the same graph.

df1

 x   y 
2   30
4   25
6   20
8   15

df2

 x   y 
2   12
4   16
6   20
8   24

for plotting the first df,

p1 <- ggplot( df1, aes(x = df1[,1] , y = log(df1[,2]) ) )
p1 <- p1 + geom_line(aes(y = log(df1[,2])))
p1

how do we get a same plot overlay on same graph for data frame df2

0

1 Answer 1

29

If you redefine data, that will change where that geom layer is sourcing from. ggplot will always look to the initializing call for the aesthetic mappings and try to inherit from there, so you don't need to redfine aes() unless you want to change/add a mapping.

Also no need to use the df[,2] syntax, ggplot is already looking inside df1 as soon as you set data = df1.

df1 <- data.frame(x = seq(2, 8, by = 2),
                  y = seq(30, 15, by = -5))
df2 <- data.frame(x = seq(2, 8, by = 2),
                  y = seq(12, 24, by = 4))

ggplot(df1, aes(x, log(y))) + 
   geom_line() +
   geom_line(data = df2, color = "red") # re-define data and overwrite top layer inheritance

enter image description here

2
  • In the second geom_line(), can we use mapping=aes(...)? When I do that I'm getting this error for some reason: "Error in geom_point(): ! mapping must be created by aes() Run rlang::last_trace() to see where the error occurred."
    – Rasputin
    Commented Aug 19, 2023 at 1:10
  • 1
    you could do + geom_list(data = df2, aes(y = y2)) if df2$y2 exists (it doesn't in this example data). Maybe the error you get is about the column not existing in your data=
    – Nate
    Commented Aug 21, 2023 at 11:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.