更改与R /晶格中的多个面板关联的条带的背景和文本

时间:2011-12-16 15:21:12

标签: r plot lattice

以下是我的工作示例。

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

enter image description here

我想为不同的sprips设置不同的条带颜色,并且字体颜色也与背景颜色不同。例如:

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

提供第一个粗略草图: enter image description here 我怎样才能做到这一点?

2 个答案:

答案 0 :(得分: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)

enter image description here

答案 1 :(得分:10)

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

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

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)