2011-06-23 84 views
1

所以設置是這樣的:添加網格單元對象

dat <- data.frame(a = c("longnameonthelefthandside"), b = c(sample(10))) 
p <- ggplot(dat, aes(b,a)) + geom_point() + xlab("label") 

我可以通過調整x軸標籤一個unit對象hjust

p + opts(axis.title.x=theme_text(size=12,hjust=unit(0.3,"npc"))) 

但還有一些關於添加單元對象(可能,根據?單位)我沒有把握:

u1 <- unit(0.5,"npc") 
u2 <- unit(0.25,"npc") 
p + opts(axis.title.x=theme_text(size=12,hjust=u1+u2)) 

產生foll由於錯誤:

Error in grid.Call("L_textBounds", as.graphicsAnnot(x$label), x$x, x$y, : 
Polygon edge not found 
In addition: Warning message: 
In validDetails.text(x) : NAs introduced by coercion 

至於進一步情況下,我試圖通過巴蒂斯特here

+0

+1不錯的問題。我不知道你可以對ggplot中對象的位置進行這種控制。 – Andrie

回答

2

爲hjust大概單元隱式轉換爲數字的方式來繪製。 所以,試試這個:

grid.lines(c(0.5, 0.5)) 
grid.text("orzorzorz", y=0.4, hjust=unit(0.25, "npc")) 
grid.text("orzorzorz", y=0.5, hjust=unit(0.25, "mm")) 
grid.text("orzorzorz", y=0.6, hjust=unit(0.25, "cm")) 
grid.text("orzorzorz", y=0.7, hjust=0.25) 

,爲什麼u1+u2引起的錯誤是:

> c(u1+u2) 
$fname 
[1] "+" 

$arg1 
[1] 0.5npc 

$arg2 
[1] 0.25npc 

這絕對不能轉換成數字。

所以,convertUnit是一個解決方法,但簡單地說,hjust = c(u1)+c(u2)就足夠了。

+0

是的,hjust需要一個數字,而不是一個單位。 – hadley

2

巴蒂斯特的代碼包括到convertUnit調用拼湊出一個略帶神祕的解決方法。一旦你把這個回你的代碼,它會產生一個情節:

p + opts(
    axis.title.x=theme_text(size=12,hjust=convertUnit(u1+u2, "npc", value=TRUE)) 
) 
+0

+1必須選擇一個,與@ koshke一起解釋錯誤的來源。 – joran

+0

公平的電話。 @kohske給出了更多細節,並且比我更好地解釋了它。 – Andrie