Mr.*_*cos 5 r data-visualization ggplot2 boxplot
如果这更多的是 SO 而不是 CV,我深表歉意。
我试图将第二个箱线图包含到现有箱线图中,该箱线图按绘制值的平均值排序。当我包含第二个 data.frame 中的箱线图(代表其他图的控制样本)时,原始图失去了顺序。
下面是一个例子:
x1 <- data.frame("V1" = runif(100, 0, 100), "siteno" = "X1") #mean = 50.3
x2 <- data.frame("V1" = runif(100, 200, 450), "siteno" = "X2") #mean = 322.4
x3 <- data.frame("V1" = runif(100, 50, 150), "siteno" = "X3") #mean = 97.8
xData <- rbind(x1,x2,x3)
xData$siteno <- with(xData, reorder(siteno, V1, mean))
zData <- data.frame("V1" = runif(300, 0, 450), "siteno" = "Z1") #mean = 224.2
#orders xData correctly
ggplot(xData, aes(x = siteno , y = V1)) +
stat_summary(fun.y=mean, colour="red", geom="point") +
geom_boxplot (aes(fill=siteno), alpha=.5, width=1, position = position_dodge(width = 1), outlier.colour = "dark gray", outlier.size = 1)
Run Code Online (Sandbox Code Playgroud)
这会生成下面的图,其中 x 变量按平均值正确排序:

如果我尝试使用下面的代码添加控制数据,则 x 变量的顺序会丢失:
x1 <- data.frame("V1" = runif(100, 0, 100), "siteno" = "X1") #mean = 50.3
x2 <- data.frame("V1" = runif(100, 200, 450), "siteno" = "X2") #mean = 322.4
x3 <- data.frame("V1" = runif(100, 50, 150), "siteno" = "X3") #mean = 97.8
xData <- rbind(x1,x2,x3)
xData$siteno <- with(xData, reorder(siteno, V1, mean))
zData <- data.frame("V1" = runif(300, 0, 450), "siteno" = "Z1") #mean = 224.2
#orders xData correctly
ggplot(xData, aes(x = siteno , y = V1)) +
stat_summary(fun.y=mean, colour="red", geom="point") +
geom_boxplot (aes(fill=siteno), alpha=.5, width=1, position = position_dodge(width = 1), outlier.colour = "dark gray", outlier.size = 1) +
geom_boxplot(data=zData, aes(x = siteno , y = V1))
Run Code Online (Sandbox Code Playgroud)
这会生成以下图,其中 x 变量没有排序:
我的图表的要点是显示按平均值排序的测试值,然后将控制值箱线图放在右侧以供视觉参考。我想可能有一个结合 xData 和 zData 数据帧的解决方案;如果有一些建议我愿意尝试。感谢您的时间。
当您使用两个数据框将数据合并到一个图中时,原始级别(和顺序)会丢失,并且会使用合并两个数据框中的数据的新级别。您不会获得填充值的这种行为,因为您没有为第二个数据框提供填充参数。但对于离散 x 尺度,两个数据帧都被组合起来,新的级别是X1、X2、X3和Z1。
无需从您可以使用的所有值创建一个数据框scale_x_discrete(),然后在参数中limits=使用函数levels()来获取级别的原始顺序siteno并将其与Z1参考级别相结合。
ggplot(xData, aes(x = siteno , y = V1)) +
stat_summary(fun.y=mean, colour="red", geom="point") +
geom_boxplot (aes(fill=siteno), alpha=.5, outlier.colour = "dark gray",
outlier.size = 1) +
geom_boxplot(data=zData, aes(x = siteno , y = V1))+
scale_x_discrete(limits=c(levels(xData$siteno),"Z1"))
Run Code Online (Sandbox Code Playgroud)
