【问题标题】:Adding line plot with boxplot使用箱线图添加线图
【发布时间】:2018-07-02 12:41:13
【问题描述】:

样本数据

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")

如何在箱线图顶部添加线图

【问题讨论】:

    标签: r line scatter-plot boxplot


    【解决方案1】:

    使用 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()
    

    【讨论】:

    • 我收到此错误Error: ggplot2 doesn't know how to deal with data of class uneval
    • 确实,我犯了一个错误,请再试一次。
    【解决方案2】:

    这里的诀窍是找出箱线图上的 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 轴上使用了更小的范围以留下更少的空白。

    【讨论】: