使用线条和多因素连接 ggplot 箱线图

Sta*_*sra 3 plot r data-visualization ggplot2 boxplot

我正在尝试将 ggplot2 箱线图与 geom_lines 连接起来以了解多个因素。到目前为止,我已经能够完成用线条连接所有箱线图,请参阅附图。但我希望通过相应的因素连接唯一的箱线图。

在此输入图像描述

例如,对于我的变量 FL,我只想连接这两个箱线图,而不将它们与其余变量连接。同样,对于变量 RW,将这两个性别箱线图连接起来,而不连接其余的其他箱线图。

library("MASS")  
data(crabs)  
melt_crabs <- melt(crabs,id.var=c("sp","sex","index"))   
ggplot(melt_crabs, aes(x = variable, y = value)) +   geom_line(aes(group = index), size = 0.05, alpha = 0.7) +   geom_boxplot(aes(fill = sp), alpha = 0.5) + facet_grid(sex~.)
Run Code Online (Sandbox Code Playgroud)

有谁知道如何实现这一目标?我希望我能以最清楚的方式解释自己。

非常感谢和良好的祝愿,

Sti*_*ibu 6

我不知道如何准确连接您制作的图中的点。但我可以向您展示如何做类似的事情。

困难在于属于一对箱线图的所有点共享相同的 x 坐标(即 的值相同variable)。因此我使用了interaction(sex, variable)x 坐标,这样每个箱线图都有自己的 x 值。然而,这意味着成对的箱线图不太明显。另一方面,连接线在另一个方向上起作用。

为了绘制线条,它们按 分组interaction(index, variable),这意味着当数据点共享相同的 和 值时,数据点已index连接variable

废话不多说,代码如下:

ggplot(melt_crabs, aes(x = interaction(sex, variable), y = value)) +
    geom_boxplot(aes(fill = sex), alpha = 0.5) +
    geom_line(aes(group = interaction(index, variable)),
              alpha = 0.5, colour = "darkgrey") +
    facet_grid(sp~.) +
    scale_x_discrete(labels = rep(levels(melt_crabs$variable), each = 2))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Mik*_* H. 5

@Stibu 的答案绝对是获得所需输出的最快、最干净的方法。根据他的答案,因为对于给定的变量,图不再彼此相邻,您可能希望将每个图放在自己单独的图中。只需对facet_grid@Stibu 代码中的调用进行微小调整即可轻松实现此目的:

ggplot(melt_crabs, aes(x = interaction(sex, variable), y = value)) +
  geom_boxplot(aes(fill = sex), alpha = 0.5) +
  geom_line(aes(group = interaction(index, variable)),
            alpha = 0.5, colour = "darkgrey") +
  facet_grid(sp~variable,scales="free_x") +
  scale_x_discrete(labels = "")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果你想把顶部的条带移到底部,我也做了一些挖掘,这并不困难。改编自以下代码:How to display strip labels Below theplot whileinging?

我们得到:

p<-ggplot(melt_crabs, aes(x = interaction(sex, variable), y = value)) +
  geom_boxplot(aes(fill = sex), alpha = 0.5) +
  geom_line(aes(group = interaction(index, variable)),
            alpha = 0.5, colour = "darkgrey") +
  facet_grid(sp~variable,scales="free_x") +
  scale_x_discrete(labels = "")

# Convert the plot to a grob
gt <- ggplotGrob(p)

# Get the positions of the panels in the layout: t = top, l = left, ...
panels <-c(subset(gt$layout, name == "panel", select = t:r))

# Get the strip grob & x-axis label grob
stripGrob = gtable_filter(gt, "strip-top")

#Replace x-axis ticks with strip
gt = gtable_add_grob(gt, stripGrob, t = max(panels$b)+1, l = min(panels$l), r = max(panels$r))

# remove the old strip
gt = gt[-(min(panels$t)-1), ]

grid.newpage()
grid.draw(gt)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述