ggplot如何将来自不同数据框的两个图形组合在一起?

95

我想将来自两个不同数据框的两个ggplot组合成一个图。以下是代码。我想要组合第一个和第二个图,或者第三个和第四个图。

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

这应该很容易做到,但不知为何我无法使其起作用。谢谢您的时间。


9
使用ggplot()语法,您可以为每个独立的图层指定要使用的数据,例如geom_step(data=df2) - baptiste
3个回答

89

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

33
最外层的括号是一种技巧,可以让绘图与其赋值在同一行中打印出来。你也可以将这个技巧用于其他变量上。(my_variable <- 1:5)my_variable <- 1:5; my_variable 的更简洁版本。 - Richie Cotton

78

对我而言唯一有效的解决方案是在 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')

更多信息请点击这里


3

您可以使用这个技巧来只使用qplot。使用内部变量$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)

如何使用这种方法来使用两种颜色? - Wagner Jorge
1
@WagnerJorge 尝试阅读 qplot 文档,并在初始化 cpu_metric2 时添加颜色,例如 qplot(y=..., x=..., colour=...),然后在 geom_line(mapping..., colour=...) 中添加颜色。 - Alexander.Iljushkin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接