在R中使用晶格,我使用因子选项绘制了一个xyplot。现在我想为每个绘图添加一个水平abline,但不是另一个数据帧。我怎样才能在相应的专家小组中获得这些内容?
EDIT - example:
MyData <- data.frame(
v1 = 1:50,
v2 = rnorm(50,20,5),
v3 = c(rep("one", 10), rep("two", 10), rep("three", 10), rep("four", 10), rep("five", 10)))
require(latticeExtra)
xyplot(
v1 ~ v2 | v3,
data = MyData,
layout = c(5, 1),
scales = list(
x = list(relation="free"),
y = list(relation="same")
)
)
# Now the horizontal lines I want to draw
lineData <- c(30,30,20,20,40)
# each for one column, from left to right; another option would be
lineData <- data.frame(
v3 = c("one","two","three","four","five"),
height = c(30,30,20,20,40)
)
# I know this will not work for each correspondent panel, separately...
abline(h = lineData)
答案 0 :(得分:2)
以下是我如何确保值匹配
lineData <- data.frame(
v3 = c("one","two","three","four","five"),
height = c(30,30,20,20,40)
)
xyplot(
v1 ~ v2 | v3,
data = MyData,
layout = c(5, 1),
scales = list(
x = list(relation="free"),
y = list(relation="same")
),
panel = function(x, ...) {
level <- dimnames(trellis.last.object())[["v3"]][packet.number()]
panel.xyplot(x, ...);
panel.abline(h = lineData$height[lineData$v3==level])
}
)
这会产生
答案 1 :(得分:1)
我认为你必须使用自定义面板功能。
library(lattice)
MyData <- data.frame(
v1 = 1:50,
v2 = rnorm(50,20,5),
v3 = c(rep("one", 10), rep("two", 10), rep("three", 10), rep("four", 10), rep("five", 10)))
lineData <- c(30,30,20,20,40)
# define custom panel plot function
customPanel = function(x, y, lineData) {
panel.xyplot(x, y)
panel.abline(h = lineData[panel.number()]) # instead of using a global variable
}
xyplot(
v1 ~ v2 | v3,
data = MyData,
layout = c(5, 1),
scales = list(
x = list(relation="free"),
y = list(relation="same")
),
panel = customPanel,
lineData = lineData)