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

jon*_*jon 13 plot r lattice

以下是我的工作示例.

require(lattice)
data(barley)
xyplot(yield ~ year | site, data = barley)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我想为不同的sprips添加不同的条带颜色,并且字体颜色也与背景颜色不同.例如:

strip background colors = c("black", "green4", "blue", "red", "purple", "yellow")
font color = c("white", "yellow", "white", "white", "green", "red")
Run Code Online (Sandbox Code Playgroud)

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

Jos*_*ien 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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


小智 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)
Run Code Online (Sandbox Code Playgroud)