R ggplot:将小提琴添加到线图

R ggplot:将小提琴添加到线图,r,ggplot2,data-visualization,R,Ggplot2,Data Visualization,我正在用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)) 这就给了我: 理想情况下,我想要一把小提琴,而不是误差条,以更好地反映分布 您需要在ge

我正在用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))
这就给了我:


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

您需要在
geom_小提琴
aes
内部使用
group=1

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

要在线条图旁边绘制小提琴,您可以使用
网格。从
网格额外
包中排列

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))
p1我想出来了:

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_小提琴()
中设置
aes(x=11,y=y)
不起作用,因为(a)x和y必须具有相同的长度,(b)您将得到十把小提琴

(a) 可以通过
rep()
“使用数字创建长度等于
y
的向量来避免,(b)通过设置
group=1
来避免(正如拖延症患者的回答所指出的)

结果图:


如果有更好的解决办法,我很想看看

有没有什么方法可以让我在x=11的位置展示这个小提琴,而不是跨越整个图形?理想情况下,我希望它显示在现在的线条和图例之间。这在我看来不会给出正确的小提琴情节。另请参见我的更新答案“不正确”是什么意思?如果x轴上的值较大,小提琴可能会显示为垂直线,但可以使用
geom_小提琴(…,width=x)
-但小提琴将包含
y
中的数据。这有什么不对的?这会导致小提琴的不同形状,但这不只是密度如何缩放的问题吗?使用的数据是相同的,对吗?但小提琴只代表
y
值的分布。尝试(在我的代码中)用4、5、6替换11。他们都是同一把小提琴。在你最初的回答中(小提琴在线条顶部横跨整个情节),唯一不同的是
宽度
参数(我认为)。
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))
ggplot(dat, aes(x, y, group=person)) + geom_line(aes(color=person)) + 
  geom_violin(aes(x=rep(11, nrow(dat)), y=y, group=1))