首页 文章

ggplot:将小提琴添加到折线图中

提问于
浏览
1

我在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))

哪个产生:

enter image description here

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)

哪个给了我这个:

enter image description here

理想情况下,我想要一把小提琴而不是误差条来更好地反映分布 .

2 回答

  • 1

    我想到了:

    ggplot(dat, aes(x, y, group=person)) + geom_line(aes(color=person)) + 
      geom_violin(aes(x=rep(11, nrow(dat)), y=y, group=1))
    

    注意事项:在 geom_violin() 中设置 aes(x=11, y=y) 不起作用,因为(a)x和y必须具有相同的长度,(b)你将获得10把小提琴 .

    (a)可以通过 rep() 来创建一个等长到 y 的向量来避免,并且(b)通过设置 group = 1 来避免(如Procrastinatus Maximus的答案所指出的那样) .

    由此产生的情节:

    enter image description here

    如果有更好的解决方案,我很乐意看到它!

  • 2

    您需要在 aes geom_violin 内使用 group = 1

    ggplot(dat, aes(x, y)) + 
      geom_line(aes(color = person)) + 
      geom_violin(aes(group = 1), fill = NA, size = 1.5) +
      theme_minimal()
    

    这给了:

    enter image description here

    要在线图旁边绘制小提琴,您可以使用 gridExtra 包中的 grid.arrange

    p1 <- ggplot(dat, aes(x, y)) + 
      geom_line(aes(color = person)) + 
      theme_minimal(base_size = 14)
    p2 <- ggplot(dat, aes(x, y)) + 
      geom_violin(fill = NA) + 
      theme_minimal(base_size = 14) + 
      theme(axis.title = element_text(color = NA),
            axis.text = element_text(color = NA))
    
    library(gridExtra)
    grid.arrange(p1, p2, ncol=2, widths = c(4,1))
    

    这使:

    enter image description here

    然而,线条和小提琴图现在由图例分开 . 附:

    library(gtable)
    leg <- gtable_filter(ggplot_gtable(ggplot_build(p1)), "guide-box") 
    
    grid.arrange(p1 + guides(color = FALSE), p2, leg, ncol=3, widths = c(4,1,1))
    

    您可以将图例再次放置在绘图的最右侧:

    enter image description here

相关问题