2011-12-16 10 views
13

Sau đây là ví dụ tôi làm việc.thay đổi nền và văn bản của các dải được liên kết với nhiều bảng trong R/mạng

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

enter image description here

Tôi muốn đặt màu sắc khác nhau cho dải sprips khác nhau và font color cũng khác nhau được tối ưu hóa với màu backgroud. Ví dụ:

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

phác thảo sơ bộ đầu tiên được cung cấp: enter image description here Làm thế nào tôi có thể đạt được điều này?

Trả lời

15

Đây là giải pháp sạch và dễ tùy chỉnh.

myStripStyle(), chức năng đó là thông qua vào strip= đối số của xyplot() sử dụng bộ đếm biến which.panel để chọn màu sắc và cũng là giá trị của factor.levels cho bảng điều khiển mà hiện đang được âm mưu.

Nếu bạn muốn chơi xung quanh với các cài đặt, chỉ cần đặt browser() ở đâu đó bên trong định nghĩa của myStripStyle() và có ở đó!

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

Nó có thể không được khôn ngoan để tham khảo các biến bên ngoài phạm vi của hàm.

Bạn có thể sử dụng par.strip.text để chuyển đối số bổ sung cho hàm dải. par.strip.text có thể được xác định ở cấp độ cốt truyện và thường được sử dụng để thiết lập thuộc tính hiển thị văn bản, nhưng nuôi một danh sách bạn có thể sử dụng nó để đưa các biến của bạn vào hàm dải.

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)