【问题标题】:How can I overlay multiple stat_contour plots on the same graph using ggplot2?如何使用 ggplot2 在同一图表上叠加多个 stat_contour 图?
【发布时间】:2013-08-14 19:44:34
【问题描述】:

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

我已经阅读了覆盖不同几何图形的解决方案,但为此我特别想使用 stat_contour。

两个数据集的 X 和 Y 变量相同。一些可使用的示例数据:

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

v1 <- melt(volcano)
v2 <- v1
v2$value <- v2$value*1.5

所以单独绘制每一个是有效的:

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

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

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

感谢您的帮助!

【问题讨论】:

  • 您应该能够将多个geom_contours 添加到一个情节中,但您将无法使用不同的比例尺,每个情节中每个美学只允许使用 1 个比例尺。因此,您可能必须想出一个不同的解决方案来区分您的两个数据集。

标签: r ggplot2


【解决方案1】:

这里有几个选项用于在 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))
  • 绘图 1:用aes(colour=category) 绘制不同纯色的两层
  • 绘图 2:使用 Alpha 透明度显示 ..level..。模拟具有两个独立的颜色渐变。
  • 绘图 3:绘制具有相同梯度的两个图层。使用aes(group=category) 保持图层不同
  • 绘图 4:使用单色渐变,但使用线型区分图层。

【讨论】:

  • 谢谢。这似乎是最接近我想象的可视化的解决方案。感谢您也介绍了“gridExtra”包,我会检查一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-06
  • 2019-06-06
  • 1970-01-01
  • 1970-01-01
  • 2016-09-20
  • 1970-01-01
相关资源
最近更新 更多