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.
Example: Drawing ggplot2 Plot Based on Two Different Data Frames. This section shows how to use the ggplot2 package to draw a plot based on two different data sets. For this, we have to set the data argument within the ggplot function to NULL.
To join two data frames (datasets) vertically, use the rbind function. The two data frames must have the same variables, but they do not have to be in the same order. If data frameA has variables that data frameB does not, then either: Delete the extra variables in data frameA or.
Combine multiple ggplots using ggarrange() the line plot (lp) will live in the first row and spans over two columns. the box plot (bxp) and the dot plot (dp) will be first arranged and will live in the second row with two different columns.
As Baptiste said, you need to specify the data argument at the geom level. Either
#df1 is the default dataset for all geoms (plot1 <- ggplot(df1, aes(v, p)) + geom_point() + geom_step(data = df2) )
or
#No default; data explicitly specified for each geom (plot2 <- ggplot(NULL, aes(v, p)) + geom_point(data = df1) + geom_step(data = df2) )
The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.
Like this:
ggplot() + geom_line(data=Data1, aes(x=A, y=B), color='green') + geom_line(data=Data2, aes(x=C, y=D), color='red')
instead of
ggplot(data=Data1, aes(x=A, y=B), color='green') + geom_line() + geom_line(data=Data2, aes(x=C, y=D), color='red')
More info here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With