user3206440 user3206440 - 1 month ago 6
R Question

Overlaying two plots using ggplot2 in R

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

Answer

You simply need to redefine the data.frame you are sourcing from. ggplot will always look to the initializing call for aesthetics and try to inherit from there. Also no need to use the df[,2] syntax, ggplot is looking inside df1$... as soon as you set data = ...

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")

enter image description here