2011-12-16 4 views
13

次の例は私が取り組む例です。 R /格子内の複数のパネルに関連付けられたストリップの背景とテキストを変更します

enter image description here

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

は、私は別のspripsに異なるストリップの色を入れたいとフォントの色は、その背景色で最適化も異なっています。例:最初の1の

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

ラフスケッチに提供されています enter image description here は、どのように私はこれを達成することができますか?

答えて

15

ここでは、クリーンで簡単にカスタマイズ可能なソリューションを紹介します。

myStripStyle()xyplot()strip=引数に渡される関数は、色と、現在プロットされていますパネルのfactor.levelsの値を選択するために、カウンタ変数which.panelを使用しています。

この設定で遊んでみたい場合は、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

9

関数のスコープの外の変数を参照するのが賢明ではないかもしれません。

par.strip.textを使用して、ストリップ関数に追加の引数を渡すことができます。 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) 
関連する問題