是否可以在ggplot2中使用facet_grid()仅在其中一个子图上显示annotation_logtics()?

时间:2013-11-21 18:03:50

标签: r ggplot2

我使用以下代码在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会话中,它看起来像我期望的那样。非常感谢您提供有用的链接!

1 个答案:

答案 0 :(得分:3)

目前,函数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'))

enter image description here