如何将多个箱形图添加到同一轴集

时间:2019-05-22 00:27:41

标签: r lattice bwplot

我试图在同一组轴上绘制4组数据作为箱形图。 我已经能够使用print()函数将它们绘制在单独的图上,但无法弄清楚如何将它们全部绘制在一起,最好使用基本包装或晶格

下面是我正在尝试的一些代码,但它不断出现错误:

Error in x[floor(d)] + x[ceiling(d)] :
non-numeric argument to binary operator

这里是我目前正在尝试的代码:

Summer <- SeasonalMax$Summer
Autumn <- SeasonalMax$Autumn
Winter <- SeasonalMax$Winter
Spring <- SeasonalMax$Spring

boxplot(Summer, Autumn, Winter, Spring,
    main = "Multiple boxplots for comparision",
    at = c(1,2,3,4),
    names = c("Summer", "Autumn", "Winter", "Spring"),
    las = 2,
    col = c("red","orange", "blue", "pink"))

2 个答案:

答案 0 :(得分:0)

首先将数据融合为长格式

# Dummy dataset
Dat <- data.frame(Spring = runif(10,0,1),
           Summer = runif(10,0,1),
           Autumn = runif(10,0,1),
           Winter = runif(10,0,1))

然后使用reshape2软件包将数据融为长格式

library(reshape2)
melt(Dat)

或提迪尔包裹

library(tidyr)
gather(Dat,key="Season",value="Value")

然后在绘制箱线图时,使用公式参数,如下所示 [我将继续tidyr,因为我命名了列]

Dat2 <- gather(Dat,key="Season",value="Value")
with(Dat2,boxplot(Value~Season))

以及所有您添加的内容

with(Dat2,boxplot(Value~Season,
     main = "Multiple boxplots for comparision",
     at = c(1,2,4,5),
     names = c("Summer", "Autumn", "Winter", "Spring"),
     las = 2,
     col = c("red","orange", "blue", "pink")))

答案 1 :(得分:0)

您可以使用ggplot2data.table,我认为这很容易,代码如下:

library(data.table)
library(ggplot2)
dat <- data.table(Spring = c(runif(9,0,1),2),
                  Summer = runif(10,0,1),
                  Autumn = runif(10,0,1),
                  Winter = runif(10,0,1))
dat1 = melt(dat)

ggplot(data=dat1,aes(x=variable,y=value)) +geom_boxplot(outlier.colour = "red")
ggplot(data=dat1,aes(x=variable,y=value,colour=variable)) +geom_boxplot() 

boxplot by group