在ggplot中向下移动facet标签

时间:2018-02-22 19:19:55

标签: r ggplot2 facet-wrap

如何移动小平面标签(A,B,C)以使它们位于左上角的框内?

enter image description here

示例数据集:

date <- as.factor(rep(c(1,2,3,4,5,6,7,8), 7))
chlconc <- runif(56, min = 0.1, max = 15.9)
colony <- as.factor(c(rep("A", 24), rep("B", 16), rep("C", 16)))
year <- as.factor(c(rep("2014", 8), rep("2016", 8), rep("2017", 8), rep("2016", 8), rep("2017", 8), rep("2014", 8), rep("2017", 8)))
graphvalues <- data.frame(year, date, colony, chlconc)

ggplot代码

library(ggplot2)
library(ggthemes)

pd <- position_dodge(0.1)

ggplot(graphvalues, aes(date, chlconc, group = year)) + 
  facet_wrap(~colony, ncol = 1, labeller = label_parsed) + 
  geom_line(aes(color = year), position = pd) +
  geom_point(aes(color = year), position = pd) +
  scale_y_continuous(limit=c(0, 16), breaks=c(0, 4, 8, 12, 16), labels=c(0, 4, 8, 12, 16)) +
  scale_color_discrete(name="Year") +
  geom_hline(yintercept=2, linetype="dashed") +
  theme(legend.text=element_text(size=14)) + 
  theme(axis.text=element_text(size=14)) + 
  theme(axis.title=element_text(size=18)) + 
  theme(legend.title=element_text(size=14)) +
  theme_few() + 
  theme(strip.text = element_text(hjust = 0, size = 14, face = "bold"))

1 个答案:

答案 0 :(得分:2)

Facet标签生活在情节区域之外,我不认为有办法让它们进入你的情节。但是,您可以在绘图区域内添加标签,方法是添加geom_text()图层作为标签,并设置geom_text()图层的x和y值,将其置于您的左上方图形。然后你也删除了facet标签。

ggplot(graphvalues, aes(date, chlconc, group = year)) + 
  facet_wrap(~colony, ncol = 1) + 
  geom_line(aes(color = year), position = pd) +
  geom_point(aes(color = year), position = pd) +
  scale_y_continuous(limit=c(0, 16), breaks=c(0, 4, 8, 12, 16), labels=c(0, 4, 8, 12, 16)) +
  scale_color_discrete(name="Year") +
  geom_hline(yintercept=2, linetype="dashed") +
  theme_classic() + 
  theme(strip.text = element_blank(), #remove strip text
    strip.background = element_blank()) + #remove strip rectangles
  geom_text(aes(label = colony, x = 0.75, y = 15.5)) #add titles using geom_text()

enter image description here