2016-08-11 48 views
2

在R中使用格,我使用因子選項繪製了xyplot。現在我想爲每個繪圖添加一個水平的abline,但是在另一個數據框之外。我怎樣才能在他們的記者小組中得到這些線路?將不同數據的abline添加到xyplot面板

EDIT - example: 

MyData <- data.frame(
    v1 = 1:50, 
    v2 = rnorm(50,20,5), 
    v3 = c(rep("one", 10), rep("two", 10), rep("three", 10), rep("four", 10), rep("five", 10))) 


require(latticeExtra) 

xyplot(
    v1 ~ v2 | v3, 
    data = MyData, 
    layout = c(5, 1), 
    scales = list(
    x = list(relation="free"), 
    y = list(relation="same") 
) 
) 

# Now the horizontal lines I want to draw 
lineData <- c(30,30,20,20,40) 
# each for one column, from left to right; another option would be 
lineData <- data.frame(
    v3 = c("one","two","three","four","five"), 
    height = c(30,30,20,20,40) 
) 

# I know this will not work for each correspondent panel, separately... 
abline(h = lineData) 
+2

你應該提供一個[重複的例子(HTTP:/ /stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)與樣本輸入數據和您當前正在使用的代碼進行繪圖。儘可能簡單地清楚顯示你卡在哪裏。 – MrFlick

+0

我們仍然缺少'MyData'和一些將'lineData'中的值連接到'v3'的值 – MrFlick

+0

我添加了示例數據。連接'lineData'的方式就是我所需要的。他們可以與'MyData'共享變量'v3' – Arne

回答

1

下面是我會做到這一點,以確保值匹配

lineData <- data.frame(
    v3 = c("one","two","three","four","five"), 
    height = c(30,30,20,20,40) 
) 

xyplot(
    v1 ~ v2 | v3, 
    data = MyData, 
    layout = c(5, 1), 
    scales = list(
    x = list(relation="free"), 
    y = list(relation="same") 
), 
    panel = function(x, ...) { 
     level <- dimnames(trellis.last.object())[["v3"]][packet.number()] 
     panel.xyplot(x, ...); 
     panel.abline(h = lineData$height[lineData$v3==level]) 
    } 
) 

這將產生

enter image description here

+0

謝謝!是否可以在函數中添加一個'panel.text()'? – Arne

+0

你爲什麼不試試? – MrFlick

1

我認爲你必須使用自定義面板功能。

library(lattice) 

MyData <- data.frame(
    v1 = 1:50, 
    v2 = rnorm(50,20,5), 
    v3 = c(rep("one", 10), rep("two", 10), rep("three", 10), rep("four", 10), rep("five", 10))) 

lineData <- c(30,30,20,20,40) 
# define custom panel plot function 
customPanel = function(x, y, lineData) { 
    panel.xyplot(x, y) 
    panel.abline(h = lineData[panel.number()]) # instead of using a global variable 
} 

xyplot(
    v1 ~ v2 | v3, 
    data = MyData, 
    layout = c(5, 1), 
    scales = list(
    x = list(relation="free"), 
    y = list(relation="same") 
), 
    panel = customPanel, 
    lineData = lineData) 
+1

而不是一個全局變量,你可以使用'lineData [panel.number()]',但是你需要確保這些值的調節因子的級別。 – MrFlick

+0

謝謝,不知道。 – Vandenman