简体   繁体   English

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

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

I'm trying to plot 4 groups of data as boxplots on the same set of axis. 我正在尝试在同一组轴上绘制4组数据作为箱形图。 I've been able to use the print() function to plot them on separate plots, but can't figure out how to plot them all together, preferably using the base package or lattice 我已经能够使用print()函数将它们绘制在单独的图上,但无法弄清楚如何将它们全部绘制在一起,最好使用基本包装或晶格

below is some code I am trying, but it keeps coming up with error: 下面是我正在尝试的一些代码,但它不断出现错误:

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

Heres the code I'm currently trying: 这是我目前正在尝试的代码:

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

First melt the data into long format 首先将数据融合为长格式

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

Then melt the data into long format with either : reshape2 package 然后使用以下任一方法将数据融为长格式:reshape2包

library(reshape2)
melt(Dat)

or tidyr package 或提迪包

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

Then when you plot the boxplot , use the formula argument as follows [I will continue with tidyr because I named the columns] 然后,当您绘制箱线图时,请按如下所示使用公式参数[由于命名列,我将继续使用tidyr]

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

And with all your additions 以及所有您添加的内容

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

You can use ggplot2 and data.table , I think it is easier, here is the code: 您可以使用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 分组图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM