首页 文章

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

提问于
浏览
13

以下是我的工作示例 .

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 回答

  • 9

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

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

    如果你想玩这些设置,只需在 myStripStyle() 的定义内某处放一个 browser() 就可以了!

    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

  • 16

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

    您可以使用 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)
    

相关问题