繁体   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