簡體   English   中英

在ggplot2中添加不同結果的行到boxplot圖

[英]Add a line from different result to boxplot graph in ggplot2

在此輸入圖像描述 我有一個包含3列(y1,y2,x)的數據幀(df1)。 我設法在y1,x和y2,x之間繪制了一個箱線圖。 我有另一個數據幀(df2),其中包含兩列A,x。 我想繪制一個折線圖(A,x)並將其添加到箱線圖中。 請注意,兩個數據幀中的變量x都是軸訪問,但是它具有不同的值。 我嘗試根據因子(x)組合並重塑數據幀和繪圖...我在一個圖中有3個箱圖。 我需要在一個圖中將df2繪制為線,將df1繪制為boxplot。

df1 <- structure(list(Y1 = c(905L, 941L, 744L, 590L, 533L, 345L, 202L, 
369L, 200L, 80L, 200L, 80L, 50L, 30L, 60L, 20L, 30L, 30L), Y2 = c(774L, 
823L, 687L, 545L, 423L, 375L, 249L, 134L, 45L, 58L, 160L, 60L, 
20L, 40L, 20L, 26L, 19L, 27L), x = c(10L, 10L, 10L, 20L, 20L, 
20L, 40L, 40L, 40L, 50L, 50L, 50L, 70L, 70L, 70L, 90L, 90L, 90L
 )), .Names = c("Y1", "Y2", "x"), row.names = c(NA, -18L), class = "data.frame")

df2 <- structure(list(Y3Line = c(384L, 717L, 914L, 359L, 241L, 265L, 
240L, 174L, 114L, 165L, 184L, 96L, 59L, 60L, 127L, 54L, 31L, 
44L), x = c(36L, 36L, 36L, 56L, 56L, 56L, 65L, 65L, 65L, 75L, 
75L, 75L, 85L, 85L, 85L, 99L, 99L, 99L)), .Names = c("A", 
"x"), row.names = c(NA, -18L), class = "data.frame")

df_l <- melt(df1, id.vars = "x")

ggplot(df_l, aes(x = factor(x), y =value, fill=variable  )) +
geom_boxplot()+
#  here I'trying to add the line graph from df2
geom_line(data = df2, aes(x = x, y=A))

有什么建議么?

在第二個數據集中,每個x值有三個y值,是否要為每個x值繪制單獨的行或每個x值的平均值? 兩者都顯示如下。 訣竅是首先將兩個數據集中的x變量更改為包含兩個變量的所有級別的因子。

df1 <-structure(list(Y1 = c(905L, 941L, 744L, 590L, 533L, 345L, 202L, 
369L, 200L, 80L, 200L, 80L, 50L, 30L, 60L, 20L, 30L, 30L), Y2 = c(774L, 
823L, 687L, 545L, 423L, 375L, 249L, 134L, 45L, 58L, 160L, 60L, 
20L, 40L, 20L, 26L, 19L, 27L), x = c(10L, 10L, 10L, 20L, 20L, 
20L, 40L, 40L, 40L, 50L, 50L, 50L, 70L, 70L, 70L, 90L, 90L, 90L
)), .Names = c("Y1", "Y2", "x"), row.names = c(NA, -18L), class = "data.frame")

df2 <- structure(list(Y3Line = c(384L, 717L, 914L, 359L, 241L, 265L, 
240L, 174L, 114L, 165L, 184L, 96L, 59L, 60L, 127L, 54L, 31L, 
44L), x = c(36L, 36L, 36L, 56L, 56L, 56L, 65L, 65L, 65L, 75L, 
75L, 75L, 85L, 85L, 85L, 99L, 99L, 99L)), .Names = c("A", 
"x"), row.names = c(NA, -18L), class = "data.frame")

library(ggplot2)
library(reshape2)

df_l <- melt(df1, id.vars = "x")

allLevels <- levels(factor(c(df_l$x,df2$x)))
df_l$x <- factor(df_l$x,levels=(allLevels))
df2$x <- factor(df2$x,levels=(allLevels))

每x類別的行數:

ggplot(data=df_l,aes(x = x, y =value))+geom_line(data=df2,aes(x = factor(x), y =A))  + 
geom_boxplot(aes(fill=variable )) 

x類別的連接方式:

ggplot(data=df2,aes(x = factor(x), y =A)) + 
stat_summary(fun.y=mean, geom="line", aes(group=1))  + 
geom_boxplot(data=df_l,aes(x = x, y =value,fill=variable )) 

暫無
暫無

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

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