【问题标题】:change background and text of strips associated to multiple panels in R / lattice更改与 R / lattice 中的多个面板关联的条带的背景和文本
【发布时间】:2011-12-16 15:21:12
【问题描述】:

以下是我处理的示例。

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")

提供了第一个的粗略草图: 我怎样才能做到这一点?

【问题讨论】:

    标签: r plot lattice


    【解决方案1】:

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

    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)
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-06
        • 2015-03-27
        • 1970-01-01
        • 1970-01-01
        • 2017-11-30
        • 2011-04-27
        • 1970-01-01
        • 2015-09-06
        相关资源
        最近更新 更多