ggplot结合来自不同data.frames的两张图

我想把两个不同的data.frames的ggplots合并成一个plot。 下面你会find代码。 我想结合情节1和2或情节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() 

这一定很容易做到,但不知何故,我无法得到它的工作。 谢谢你的时间。

Baptiste说,你需要在geom级别指定数据参数。 或

 #df1 is the default dataset for all geoms (plot1 <- ggplot(df1, aes(v, p)) + geom_point() + geom_step(data = df2) ) 

要么

 #No default; data explicitly specified for each geom (plot2 <- ggplot(NULL, aes(v, p)) + geom_point(data = df1) + geom_step(data = df2) ) 

我唯一的工作解决scheme是在geom_line中定义数据对象,而不是基础对象ggplot。

喜欢这个:

 ggplot() + geom_line(data=Data1, aes(x=A, y=B), color='green') + geom_line(data=Data2, aes(x=C, y=D), color='red') 

代替

 ggplot(data=Data1, aes(x=A, y=B), color='green') + geom_line() + geom_line(data=Data2, aes(x=C, y=D), color='red') 

更多信息在这里

你可以把这个技巧只使用qplot。 使用内部variables$mapping 。 你甚至可以添加color =到你的地块,所以这也将被放在地图上,然后你的地块与图例和颜色自动结合。

 cpu_metric2 <- qplot(y=Y2,x=X1) cpu_metric1 <- qplot(y=Y1, x=X1, xlab="Time", ylab="%") combined_cpu_plot <- cpu_metric1 + geom_line() + geom_point(mapping=cpu_metric2$mapping)+ geom_line(mapping=cpu_metric2$mapping)