是否可以使用ggplot2中的facet_grid()让annotation_logtics()仅出现在一个子图上?

2024-02-27

我使用以下代码在 ggplot2 中使用facet_grid() 创建一个包含三个子图的图:

day <- c('5-Aug', '5-Aug','5-Aug','10-Aug','10-Aug','10-Aug','17-Aug','17-Aug','17-Aug')
station <- c(1:3,1:3,1:3)
Mean <- c(382, 1017, 1519, 698, 5398, 2458, 346, 5722, 6253)
StErr<- c(83, 100, 73, 284, 3417, 689, 53, 1796, 732)
df <- data.frame(day,station,Mean,StErr)

library(ggplot2)
library(scales)
ggplot(df, aes(x=station, y=Mean)) + 
geom_errorbar(aes(ymin=Mean-StErr, ymax=Mean+StErr), colour="black", width=.1) +
geom_point(size=2)+
xlab(NULL) +
ylab(expression(paste('Copepods,'~'#/m'^3))) + 
theme_bw() +
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()
) + 
scale_x_continuous(expand=c(.3,0), breaks=c(1:3), labels=c("In", "FL", "Off")) + 
annotation_logticks(sides = "l") + 
scale_y_log10(limit=c(100,10000)) +
theme(axis.text.x=element_text(size=12)) +
theme(axis.text.y=element_text(size=12)) +
facet_grid(.~day)

但是,我使用annotation_logticks() 创建的对数轴刻度出现在所有三个子图上。问题:有谁知道如何控制facet_grid()annotation_logticks()中出现的子图?

我将数据添加到代码中,并希望这是一种更容易接受和有用的包含示例数据的方式。我将此代码复制到新的 R 会话中,它似乎达到了我的预期。非常感谢您提供有用的链接!


目前功能annotation_logticks硬编码data创建的图层中的对象。

您可以创建自己的函数,允许您传递data.frame包含您想要添加注释的分面变量和级别

add_logticks  <- function (base = 10, sides = "bl", scaled = TRUE, 
   short = unit(0.1, "cm"), mid = unit(0.2, "cm"),  long = unit(0.3, "cm"), 
   colour = "black",  size = 0.5, linetype = 1, alpha = 1, color = NULL, 
   data =data.frame(x = NA),... )   {
  if (!is.null(color)) 
    colour <- color
  layer(geom = "logticks", geom_params = list(base = base, 
          sides = sides, raw = raw, scaled = scaled, short = short, 
          mid = mid, long = long, colour = colour, size = size, 
          linetype = linetype, alpha = alpha, ...), 
        stat = "identity", data =data , mapping = NULL, inherit.aes = FALSE, 
        show_guide = FALSE)
}
# The plot without logticks
overall <- ggplot(df, aes(x=station, y=Mean)) + 
  geom_errorbar(aes(ymin=Mean-StErr, ymax=Mean+StErr), colour="black", width=.1) +
  geom_point(size=2)+
  xlab(NULL) +
  ylab(expression(paste('Copepods,'~'#/m'^3))) + 
  theme_bw() +
  theme(
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank()
  ) + 
  scale_x_continuous(expand=c(.3,0), breaks=c(1:3), labels=c("In", "FL", "Off")) + 
  scale_y_log10(limit=c(100,10000)) +
  theme(axis.text.x=element_text(size=12)) +
  theme(axis.text.y=element_text(size=12)) +
  facet_grid(.~day)

overall + add_logticks(side = 'l', data = data.frame(x= NA, day = '5-Aug'))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以使用ggplot2中的facet_grid()让annotation_logtics()仅出现在一个子图上? 的相关文章

随机推荐