Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (5.3k points)
edited by

I want to combine two ggplots, from two different data.frames, into one plot. Below you will find the code. I want to combine plot 1&2 or plots 3&4.

df1 <- data.frame(p=c(10,8,7,3,2,6,7,8),

v=c(100,300,150,400,450,250,150,400))

df2 <- data.frame(p=c(10,8,6,4), v=c(150,250,350,400))

plot1 <- qplot(df1$v, df1$p)

plot2 <- qplot(df2$v, df2$p, geom="step")

plot3 <- ggplot(df1, aes(v, p)) + geom_point()

plot4 <- ggplot(df2, aes(v, p)) + geom_step()

This must be very easy to do, but somehow I can't get it to work. Thanks for your time.

1 Answer

0 votes
by
edited by

To create a plot by combining two plots from different data frames, you can pass the data frames at the geom level as follows:

df1 <- data.frame(p=c(10,8,7,3,2,6,7,8),

v=c(100,300,150,400,450,250,150,400))

df2 <- data.frame(p=c(10,8,6,4), v=c(150,250,350,400))

plot1 <- ggplot(df1, aes(v, p)) + 

  geom_point() +

  geom_step(data = df2)

OR

plot2 <- ggplot(NULL, aes(v, p)) + 

  geom_point(data = df1) +

  geom_step(data = df2)

image

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...