Ggplot 结合来自不同 data.frame 的两个绘图

我想将来自两个不同数据帧的两个 ggplot 合并到一个绘图中。下面您将找到代码。我想结合情节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()

这一定很容易做到,但不知为何我不能让它工作。谢谢你的时间。

194853 次浏览

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

You can take this trick to use only qplot. Use inner variable $mapping. You can even add colour= to your plots so this will be putted in mapping too, and then your plots combined with legend and colors automatically.

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)

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