0

在此处输入图像描述我有一个包含 3 列(y1、y2、x)的数据框(df1)。我设法在 y1, x 和 y2, x 之间绘制了一个箱线图。我有另一个数据框(df2),其中包含两列 A,x。我想绘制一个折线图(A,x)并将其添加到箱线图中。请注意,两个数据框中的变量 x 是轴访问,但是,它具有不同的值。我试图根据因子(x)组合和重塑两个数据框和绘图......我在一张图中得到了 3 个箱线图。我需要在一个图中将 df2 绘制为线,将 df1 绘制为箱线图。

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

有什么建议么?

4

1 回答 1

2

在第二个数据集中,每个 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 )) 
于 2013-03-20T13:20:38.377 回答