【问题标题】:Coordinates for formula based plotting of factors in boxplot, stripchart在箱线图、条形图中基于公式绘制因子的坐标
【发布时间】:2014-04-17 15:28:32
【问题描述】:

我正在使用箱线图和条形图绘制基于几个分类变量(因子、x 变量)的连续数据(y 变量)。 为此,默认绘图函数提供了一个方便的基于公式的界面,我可以在其中输入数据: 响应 ~ 因子 1 + 因子 2 + ... 并获得因子 1、因子 2 等的组合作为 x 轴坐标。

但是,我正在努力找出这些原始坐标值对我的数据来说是什么,因为我想在我的图中注释一些值。

例子:

data(iris)
iris[,"DummyFactor"] <- as.factor(c("First", "Second"))
boxplot(Sepal.Length ~ Species + DummyFactor, data = iris)
stripchart(Sepal.Length ~ Species + DummyFactor, data = iris, vertical=T, add=T, pch=16)

# y-axis values:
ys <- iris[,"Sepal.Length"]
# x-axis:
# How to obtain the x-axis values on my current plot?

通过实验我发现这个例子中的 x 值为:

xs <- apply(model.matrix(~ -1 + Species + DummyFactor, data = iris), MARGIN=1, FUN=function(x) sum(c(1,2,3,3)[as.logical(x)]))
# Annotate a few examples, e.g. 7th, 100th and 120th observation
points(x=xs[c(7,100,120)], y=ys[c(7,100,120)], pch=16, col="red", cex=2)
iris[c(7,100,120),]
#> iris[c(7,100,120),]
#    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species DummyFactor
#7            4.6         3.4          1.4         0.3     setosa       First
#100          5.7         2.8          4.1         1.3 versicolor      Second
#120          6.0         2.2          5.0         1.5  virginica      Second

...这可行,但似乎不是解决此问题的正确方法。似乎箱线图和条形图的公式实现对用户是隐藏的。

在一般情况下是否有一种简单的方法来获取这些坐标?

【问题讨论】:

  • x 轴坐标是您绘制的框数。所以试试这个points(x=c(1,5,6), y=ys[c(7,100,120)], pch=16, col="red", cex=2)

标签: r graphics formula boxplot stripchart


【解决方案1】:

参见?boxplot 中的at 参数:
“给出箱线图绘制位置的数字向量,[...];默认为 1:n,其中 n 是箱数。”

您可以从例如获取盒子的数量。 boxplot 对象中的 names 插槽(参见 ?boxplot 中的“值”:

bp <- boxplot(Sepal.Length ~ Species + DummyFactor, data = iris)
bp
bp$names

这些框是按顺序排列的,因此绘图公式(物种)中第一个因子的水平变化最快,然后是第二个(虚拟因子)。获取箱数:

length(bp$names)

创建一个默认 x (at) 坐标的向量:

at <- seq_along(bp$names)

相同的值可以通过以下方式获得:

at <- with(iris, seq_along(levels(interaction(Species, DummyFactor))))

从 Species 和 DummyFactor 之间的交互中创建一个因子。这将用于子集“at”:

intr <- with(iris, interaction(Species, DummyFactor))

将x坐标添加到数据框:

iris$at <- at[intr]

加分:

points(Sepal.Length ~ at, data = iris[c(7, 100, 120), ], pch = 16, col = "red", cex = 2)

【讨论】:

  • 很好,不知道“交互”。不知何故错过了回报。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
相关资源
最近更新 更多