gpt4 book ai didi

r - 在多面图中为单个面板添加几何图层

转载 作者:行者123 更新时间:2023-12-03 20:51:52 25 4
gpt4 key购买 nike

从以下链接获取提示Aligning two plots with ggplot2 ,我能够针对一个共同的 x 轴绘制 2 个“y”变量。我现在要做的是能够将 geom_point 图层添加到仅一个方面。该层使用与 d1 具有相同结构的不同数据集(d3)。当我添加图层时,它会在两个方面都使用。是否可以仅在上面对点进行分层。

library(ggplot2)

x <- seq(1992, 2002, by = 2)
d1 <- data.frame(x = x, y = rnorm(length(x)))
xy <- expand.grid(x = x, y = x)
d2 <- data.frame(x = xy$x, y = xy$y, z = jitter(xy$x + xy$y))
d3 <- data.frame(x = x, y = 3+rnorm(length(x)))

d1$panel <- "a"
d2$panel <- "b"
d1$z <- d1$x

d <- rbind(d1, d2)

p <- ggplot(data = d, mapping = aes(x = x, y = y))
p <- p + facet_grid(panel ~ ., scale = "free")
p <- p + layer(data = d1, geom = c( "line"), stat = "identity")
###*p <- p + layer(data = d3, geom = c( "point"))* - This is the layer I intend to add only to the top panel

p <- p + layer(data = d2, geom = "line", stat = "identity")
p

最佳答案

只需添加 panel列至 d3使用要添加点集的面板。在你的情况下:

d3$panel = "a"

p <- ggplot(data = d, mapping = aes(x = x, y = y))
p <- p + facet_grid(panel ~ ., scale = "free")
p <- p + layer(data = d1, geom = c( "line"), stat = "identity")
p <- p + layer(data = d3, geom = c( "point"))
p <- p + layer(data = d2, geom = "line", stat = "identity")
p

这会产生正确的输出:

enter image description here

如果对 facet_grid 的调用中提到的列不存在,ggplot2 假定它需要在所有方面打印。当您指定 panel , ggplot2 会考虑到它。

关于r - 在多面图中为单个面板添加几何图层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10673481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com