在 ggplot2 中添加趋势线/箱线图(按组) [英] Adding trend lines/boxplots (by group) in ggplot2

查看:483
本文介绍了在 ggplot2 中添加趋势线/箱线图(按组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 40 名受试者,分为两组,超过 15 周,有一些测量变量 (Y).

I have 40 subjects, of two groups, over 15 weeks, with some measured variable (Y).

我希望有一个情节,其中:x = 时间,y = T,线条按主题分类,颜色按组分类.

I wish to have a plot where: x = time, y = T, lines are by subjects and colours by groups.

我发现可以这样做:

TIME <- paste("week",5:20)
ID <- 1:40
GROUP <- sample(c("a","b"),length(ID), replace = T)
group.id <- data.frame(GROUP, ID)
a <- expand.grid(TIME, ID)
colnames(a) <-c("TIME", "ID")
group.id.time <- merge(a, group.id)
Y <- rnorm(dim(group.id.time)[1], mean = ifelse(group.id.time$GROUP =="a",1,3) )
DATA <- cbind(group.id.time, Y)
qplot(data = DATA,
        x=TIME, y=Y, 
        group=ID,       
        geom = c("line"),colour = GROUP) 

但现在我想在图中添加一些东西来显示两组之间的差异(例如,每个组的趋势线,带有一些 CI 阴影线) - 怎么做?

But now I wish to add to the plot something to show the difference between the two groups (for example, a trend line for each group, with some CI shadelines) - how can it be done?

我记得曾经看到 ggplot2 可以(轻松)使用 geom_smooth 做到这一点,但我缺少有关如何使其工作的一些信息.

I remember once seeing the ggplot2 can (easily) do this with geom_smooth, but I am missing something about how to make it work.

另外,我想知道是否让线条像每个组的箱线图一样(不同分位数和围栏等都有一条线).但我想回答第一个问题会帮助我解决第二个问题.

Also, I wondered at maybe having the lines be like a boxplot for each group (with a line for the different quantiles and fences and so on). But I imagine answering the first question would help me resolve the second.

谢谢.

推荐答案

p <- ggplot(data=DATA, aes(x=TIME, y=Y, group=ID)) +
            geom_line(aes(colour=GROUP)) +
            geom_smooth(aes(group=GROUP))

geom_smooth 图 http://img143.imageshack.us/img143/7678/geomsmooth.png

这篇关于在 ggplot2 中添加趋势线/箱线图(按组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆