R 使用箱线图添加线图
样本数据R 使用箱线图添加线图,r,line,scatter-plot,boxplot,R,Line,Scatter Plot,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:1
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年。这样,您就可以像往常一样添加带有行的行
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轴上使用了较小的范围以减少空白。我得到了以下错误:ggplot2不知道如何处理未验证类的数据,我犯了一个错误,请重试。