如何使用ggplot2在同一图表上叠加多个stat_contour图?

Chr*_*emp 6 r ggplot2

是否可以使用来自不同数据帧的数据覆盖ggplot2中的多个stat_contour图?

我已经阅读了覆盖不同geoms的解决方案,但为此我特别想使用stat_contour.

两个数据集的X和Y变量相同.一些样本数据可用于:

# some sample data
require(ggplot2)
require(reshape2)

v1 <- melt(volcano)
v2 <- v1
v2$value <- v2$value*1.5
Run Code Online (Sandbox Code Playgroud)

所以单独绘制每个人的作品:

ggplot(v1, aes(x = Var1, y = Var2, z = value)) +
+   stat_contour(aes(color = ..level..)) + scale_colour_gradient(low = "white", high="#ff6666")

ggplot(v2, aes(x = Var1, y = Var2, z = value)) +
+   stat_contour(aes(color = ..level..)) + scale_colour_gradient(low = "white", high="#A1CD3A")
Run Code Online (Sandbox Code Playgroud)

有没有办法在同一图表上叠加这些密度图?

我已经尝试创建一个因子变量并为每个集合分配不同的值,然后将它们堆叠起来,但是我得到一个错误,因为它们对于每个X和Y都有多个值(此处为Var 1和Var2).

感谢您的帮助!

bde*_*est 8

以下是在ggplot2中覆盖两个轮廓数据集的几个选项.一个重要的警告(正如@Drew Steen所指出的)是你不能colour在同一个情节中有两个不同的尺度.

# Add category column to data.frames, then combine.
v1$category = "A"
v2$category = "B"
v3 = rbind(v1, v2)

p1 = ggplot(v3, aes(x=Var1, y=Var2, z=value, colour=category)) +
     stat_contour(binwidth=10) +
     theme(panel.background=element_rect(fill="grey90")) +
     theme(panel.grid=element_blank()) +
     labs(title="Plot 1")

p2 = ggplot(v3, aes(x=Var1, y=Var2, z=value, colour=category)) +
     stat_contour(aes(alpha=..level..), binwidth=10) +
     theme(panel.background=element_rect(fill="white")) +
     theme(panel.grid=element_blank()) +
     labs(title="Plot 2")

p3 = ggplot(v3, aes(x=Var1, y=Var2, z=value, group=category)) +
     stat_contour(aes(color=..level..), binwidth=10) +
     scale_colour_gradient(low="white", high="#A1CD3A") +
     theme(panel.background=element_rect(fill="grey50")) +
     theme(panel.grid=element_blank()) +
     labs(title="Plot 3")

p4 = ggplot(v3, aes(x=Var1, y=Var2, z=value, linetype=category)) +
     stat_contour(aes(color=..level..), binwidth=10) +
     scale_colour_gradient(low="white", high="#A1CD3A") +
     theme(panel.background=element_rect(fill="grey50")) +
     theme(panel.grid=element_blank()) +
     labs(title="Plot 4")

library(gridExtra)
ggsave(filename="plots.png", height=8, width=10,
       plot=arrangeGrob(p1, p2, p3, p4, nrow=2, ncol=2))
Run Code Online (Sandbox Code Playgroud)
  • 图1:用不同的纯色绘制两个图层 aes(colour=category)
  • 图2:..level..使用Alpha透明度显示.模拟具有两个单独的颜色梯度.
  • 图3:用相同的梯度绘制两个图层.保持层与众不同aes(group=category)
  • 图4:使用单色渐变,但使用线型区分图层.

在此输入图像描述