用dlply函数改变R /晶格中条带的背景

时间:2015-02-26 09:47:41

标签: r plyr lattice

我需要将xyplot与dlply结合使用,以绘制几页。按照下面的示例,x的每个值都有一个页面,条件是y:

set.seed(1)
df <- as.data.frame(cbind(
    x = c("AV","DZ"),   
    y=rep(c(letters[1:4]),5), 
    stringsAsFactors = F))
df$z <- rnorm(20)
df$q <- rnorm(20)
plotter <- function(dataframe) { xyplot(q ~ z | y, data=dataframe)}
charts <- dlply(df, .(x), plotter)
charts

现在,如果我想更改条形背景的颜色(有用地解释here),我是否应该从列表中选择颜色的值?我应该使用矢量列表吗?数据框? x&amp;的组合y值?两个嵌套的plyr函数? 让我们假设四种面板颜色应该如下:

"blue"  "red"   "blue"  "green"

您如何建议修改后面的col函数(在链接中提出)中的myStripStyle参数?

bgColors <- c("black", "green4", "blue", "red", "purple", "yellow")
txtColors <- c("white", "yellow", "white", "white", "green", "red")
# Create a function to be passed to "strip=" argument of xyplot
myStripStyle <- function(which.panel, factor.levels, ...) {
panel.rect(0, 0, 1, 1,
col = bgColors[which.panel],
border = 1)
panel.text(x = 0.5, y = 0.5,
font=2,
lab = factor.levels[which.panel],
col = txtColors[which.panel])
}

老实说,我认为这个问题本来可以在其他地方得到解答,但我找不到任何可以帮助我改变的plyr函数和lattice图形的混合这样的参数。

1 个答案:

答案 0 :(得分:1)

这是一个黑客,有lattice经验的人应该真正添加一个正确的答案。但这会做你想要的,所以在这里。您可以在全局环境中指定allLevels。然后,使用全局变量which.panelmyStripStyle内重新计算allLevels

allLevels <- levels(df$y)
# Create a function to be passed to "strip=" argument of xyplot
myStripStyle <- function(which.panel, factor.levels,  ...) {
  # recalculate which.panel based on allLevels
  which.panel <- match(factor.levels, allLevels)[which.panel]
  panel.rect(0, 0, 1, 1,
             col = bgColors[which.panel],
             border = 1)
  panel.text(x = 0.5, y = 0.5,
             font=2,
             lab = allLevels[which.panel],
             col = txtColors[which.panel])
}
plotter <- function(dataframe) { xyplot(q ~ z | y, data=dataframe, strip=myStripStyle)}
# 
dlply(df, .(x), plotter)