簡體   English   中英

如何將多個箱形圖添加到同一軸集

[英]how to add multiple boxplots to same axis set

我正在嘗試在同一組軸上繪制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"))

首先將數據融合為長格式

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

您可以使用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() 

分組圖

暫無
暫無

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

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