在箱线图中观察子类别值

时间:2019-11-02 14:40:36

标签: r

对于R中的虹膜数据;

我想只选择一个或多个子类别来观察箱线图的值。

例如,当我运行以下命令时,它将显示所有三个子类别;

boxplot(iris$Sepal.Length ~ iris$Species)

但是当我要将其范围缩小到一个或两个类别时,我会失败

boxplot(iris$Sepal.Length ~ iris[levels(iris$Species) == "setosa"])

如何为我想要的单个子类别或多个类别执行此操作? 谢谢

1 个答案:

答案 0 :(得分:0)

我们可以使用with()。为了避免未选择物种的空图,我们使用as.numeric()允许boxplot()沿物种因子水平而不是其标签来区分物种。

op <- par(mfrow=c(1, 2))
with(iris[iris$Species %in% "setosa", ],
     boxplot(Sepal.Length ~ as.numeric(Species), xlab="Species"))
mtext("setosa", 1, 1)

with(iris[iris$Species %in% c("setosa", "virginica"), ],
     boxplot(Sepal.Length ~ as.numeric(Species), xlab="Species", xaxt="n"))
mtext(c("setosa", "virginica"), 1, 1, at=1:2)
par(op)

结果

enter image description here