使用箱线图添加线图

Adding line plot with boxplot

样本数据

set.seed(123)
par(mfrow = c(1,2))

dat <- data.frame(years = rep(1980:2014, each = 8), x = sample(1000:2000, 35*8 ,replace = T))
boxplot(dat$x ~ dat$year, ylim = c(500, 4000)) 

我有另一个数据集,它在某些选定年份具有单一值

ref.dat <- data.frame(years = c(1991:1995, 2001:2008), x = sample(1000:2000, 13, replace = T))
plot(ref.dat$years, ref.dat$x, type = "b")

如何在箱线图上添加线图

使用 ggplot2 你可以这样做:

ggplot(dat, aes(x = years, y = x)) + 
  geom_boxplot(data = dat,  aes(group = years)) + 
  geom_line(data = ref.dat, colour = "red") + 
  geom_point(data = ref.dat, colour = "red", shape = 1) +
  coord_cartesian(ylim = c(500, 4000)) + 
  theme_bw()

这里的技巧是找出箱线图上的 x 轴。您有 35 个框,它们绘制在 x 坐标 1、2、3、...、35 处 - 即年份 - 1979。这样,您可以像往常一样添加带有 lines 的行。

set.seed(123)
dat <- data.frame(years = rep(1980:2014, each = 8), 
    x = sample(1000:2000, 35*8 ,replace = T))
boxplot(dat$x ~ dat$year, ylim = c(500, 2500)) 

ref.dat <- data.frame(years = c(1991:1995, 2001:2008), 
    x = sample(1000:2000, 13, replace = T))
lines(ref.dat$years-1979, ref.dat$x, type = "b", pch=20)

点有点难看,所以我把点样式改成了20。另外,我在y轴上使用了一个较小的范围来减少空白space。