簡體   English   中英

使用線和多因素連接ggplot箱圖

[英]Connect ggplot boxplots using lines and multiple factor

我正在嘗試將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~.)

有誰知道如何實現這一目標? 我希望我能以最清晰的方式向自己解釋。

非常感謝和最良好的祝願,

我不知道如何將點精確連接到您生成的圖中。 但我可以向您展示如何做類似的事情。

困難在於,屬於一箱形圖的所有點共享相同的x坐標(即, variable值相同)。 因此,我已將interaction(sex, variable)用作x坐標,以便每個箱線圖都有自己的x值。 但是,這意味着成對的箱形圖不太明顯。 另一方面,連接線沿另一個方向工作。

為了繪制線,將它們按interaction(index, variable)分組,這意味着當數據點共享相同的indexvariable值時,數據點已連接。

聊夠了,下面是代碼:

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

在此處輸入圖片說明

@Stibu的答案絕對是獲得所需輸出的最快,最干凈的方法。 建立他的答案,因為對於給定的變量,曲線不再相鄰,因此您可能希望將每個曲線放在各自的曲線中。 只需對@Stibu的代碼中的facet_grid調用進行較小的調整即可輕松實現:

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 = "")

在此處輸入圖片說明

另外,如果您想將頂部的條帶移動到底部,我也做了一些挖掘,這並不困難。 從以下代碼改編代碼: 刻面時如何在圖下方顯示條形標簽?

我們得到:

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)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM