13

以下是我处理的示例。

require(lattice)
data(barley)
xyplot(yield ~ year | site, data = barley)

在此处输入图像描述

我想为不同的小条设置不同的条带颜色,字体颜色也与背景颜色不同优化。例如:

strip background colors = c("black", "green4", "blue", "red", "purple", "yellow")
font color = c("white", "yellow", "white", "white", "green", "red")

提供了第一个的粗略草图: 在此处输入图像描述 我怎样才能做到这一点?

4

2 回答 2

16

这是一个干净且易于定制的解决方案。

myStripStyle(),传入strip=参数的函数xyplot()使用计数器变量which.panel来选择颜色以及factor.levels当前正在绘制的面板的值。

如果你想玩弄这些设置,只需browser()在定义中的某个地方放一个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])
}    
xyplot(yield ~ year | site, data = barley, strip=myStripStyle)

在此处输入图像描述

于 2011-12-16T17:15:59.327 回答
10

引用函数范围之外的变量可能不明智。

您可以使用par.strip.text将其他参数传递给 strip 函数。par.strip.text可以在绘图级别定义,通常用于设置文本显示属性,但是作为列表,您可以使用它将变量带入 strip 函数。

bgColors <- c("black", "green4", "blue", "red", "purple", "yellow")
txtColors <- c("white", "yellow", "white", "white", "green", "red")

# Create a function to be passes to "strip=" argument of xyplot
myStripStyle <- function(which.panel, factor.levels, par.strip.text,
                     custBgCol=par.strip.text$custBgCol,
                     custTxtCol=par.strip.text$custTxtCol,...)     {
    panel.rect(0, 0, 1, 1,
            col = custBgCol[which.panel],
            border = 1)
    panel.text(x = 0.5, y = 0.5,
            font=2,
            lab = factor.levels[which.panel],
            col = custTxtCol[which.panel])
}
xyplot(yield ~ year | site, data = barley,
        par.strip.text=list(custBgCol=bgColors,
                            custTxtCol=txtColors),
        strip=myStripStyle)
于 2012-02-22T11:42:54.913 回答