我在ggplot中画了一个折线图 . 每行对应一个人及其随时间的发展 . 一个简化的,可重现的例子:
dat <- data.frame(x=rep(1:10, 10), y=rnorm(100), person=rep(LETTERS[1:10], each=10))
ggplot(dat, aes(x, y, group=person)) + geom_line(aes(color=person))
哪个产生:
I'd like to add a violin at x = 11 to show the overall distribution of the values depicted on the y-axis.
如果我在ggplot调用中添加 + geom_violin()
,则会在x的每个值处绘制一个小提琴(这是有意义的) . 但我想要的是加上我用 ggplot(dat, aes(x, y)) + geom_violin()
获得的小提琴 .
如何将这两个 geom_
组合在一个图中以全面概述我的数据?
编辑:我得到它与 geom_errorbar
工作,但不能得到类似于小提琴的东西:
ggplot(dat, aes(x, y, group=person)) + geom_line(aes(color=person)) +
geom_errorbar(aes(x=11, ymax=mean(dat$y)+sd(dat$y), ymin=mean(dat$y)-sd(dat$y))) +
geom_point(aes(x=11, y=mean(dat$y)), size=4)
哪个给了我这个:
理想情况下,我想要一把小提琴而不是误差条来更好地反映分布 .
2 回答
我想到了:
注意事项:在
geom_violin()
中设置aes(x=11, y=y)
不起作用,因为(a)x和y必须具有相同的长度,(b)你将获得10把小提琴 .(a)可以通过
rep()
来创建一个等长到y
的向量来避免,并且(b)通过设置group = 1
来避免(如Procrastinatus Maximus的答案所指出的那样) .由此产生的情节:
如果有更好的解决方案,我很乐意看到它!
您需要在
aes
geom_violin
内使用group = 1
:这给了:
要在线图旁边绘制小提琴,您可以使用
gridExtra
包中的grid.arrange
:这使:
然而,线条和小提琴图现在由图例分开 . 附:
您可以将图例再次放置在绘图的最右侧: