【问题标题】:how to add multiple boxplots to same axis set如何将多个箱线图添加到同一轴集
【发布时间】:2019-10-08 09:53:37
【问题描述】:

我正在尝试将 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"))

【问题讨论】:

  • 您的代码按预期对我有用:imgur.com/nArWQIi。也许我误解了你的问题?

标签: r lattice bwplot


【解决方案1】:

先将数据融合成长格式

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

或 tidyr 包

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

【讨论】:

  • 当我使用gather() 函数时,我收到消息“警告消息:度量变量的属性不相同;它们将被丢弃' ...然后如果我忽略它,我的输出箱线图不正确,知道为什么吗?
  • 当您使用我在此答案中建议的示例 data.frame 时会发生这种情况,还是使用您自己的数据?如果是您自己的数据,请发布它的样本。这很可能是由于数据框中的其他变量。如果您不想在收集过程中包含另一个变量,请执行以下操作:gather(Dat,key="Season",value="Value",-unwantedVariable1, -unwantedvariable2)。您可以根据需要添加任意数量的-variable 参数
【解决方案2】:

你可以使用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

【讨论】:

    猜你喜欢
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 2021-08-30
    • 1970-01-01
    • 2020-10-19
    • 2016-01-14
    • 1970-01-01
    相关资源
    最近更新 更多