2012-09-13 96 views
43

我想將樣本大小值與繪圖上的點相關聯。我可以使用geom_text來定位靠近點的數字,但是這很麻煩。將它們沿着劇情的外邊緣排列起來會更清晰。ggplot2 - 在繪圖外註釋

舉例來說,我有:

df=data.frame(y=c("cat1","cat2","cat3"),x=c(12,10,14),n=c(5,15,20)) 

ggplot(df,aes(x=x,y=y,label=n))+geom_point()+geom_text(size=8,hjust=-0.5) 

將會產生這樣的情節: enter image description here

我寧願更多的東西是這樣的: enter image description here

我知道我可以創建第二個情節並使用grid.arrange(a la this post),但確定textGrobs與y軸排列的間距是很繁瑣的。有沒有更簡單的方法來做到這一點?謝謝!

+1

這可能與二級軸線做我認爲它正在開發中。但如果你想嘗試一下,請點擊此鏈接https://groups.google.com/forum/?fromgroups=#!topic/ggplot2/_3Pm-JEoCqE –

+0

嗯有趣...我想知道哈德利是否要去執行這個。但是,我收到一些奇怪的錯誤,試圖加載'devtools':'call:if(!version_match){error:argument is length zero'。 – jslefche

+0

我只能說devtools適合我。如果您無法解決問題,您應該嘗試發佈問題。 –

回答

42

您不需要繪製第二個圖。您可以使用annotation_custom來定位繪圖區域內部或外部的任何位置。 grobs的定位就數據座標而言。假設「5」,「10」,「15」與「cat1」,「cat2」,「cat3」對齊,textGrobs的垂直位置將被處理 - 三個textGrobs的y座標由三個數據點的y座標。默認情況下,ggplot2剪輯繪圖區域,但剪輯可以被覆蓋。需要擴大相關保證金以爲grob騰出空間。下面的(使用GGPLOT2 0.9.2)提供了一種類似於你的第二個情節一個情節:

library (ggplot2) 
library(grid) 

df=data.frame(y=c("cat1","cat2","cat3"),x=c(12,10,14),n=c(5,15,20)) 

p <- ggplot(df, aes(x,y)) + geom_point() +   # Base plot 
    theme(plot.margin = unit(c(1,3,1,1), "lines")) # Make room for the grob 

for (i in 1:length(df$n)) { 
p <- p + annotation_custom(
     grob = textGrob(label = df$n[i], hjust = 0, gp = gpar(cex = 1.5)), 
     ymin = df$y[i],  # Vertical position of the textGrob 
     ymax = df$y[i], 
     xmin = 14.3,   # Note: The grobs are positioned outside the plot area 
     xmax = 14.3) 
}  

# Code to override clipping 
gt <- ggplot_gtable(ggplot_build(p)) 
gt$layout$clip[gt$layout$name == "panel"] <- "off" 
grid.draw(gt) 

enter image description here

+8

是不是更容易有一個geom_text層在x = Inf ,hjust> = 1,並關閉剪輯? – baptiste

+0

非常棒,謝謝@ Sandy-Muspratt! – jslefche

+11

@jslefche,您應該注意@baptiste提供的解決方案要簡單得多。 'p = p + geom_text(aes(label = n,x = Inf,y = y),hjust = -1)'。然後關閉剪輯。雖然對齊可以略微關閉。 –

2

Simplier解決方案基於grid

require(grid) 

df = data.frame(y = c("cat1", "cat2", "cat3"), x = c(12, 10, 14), n = c(5, 15, 20)) 

p <- ggplot(df, aes(x, y)) + geom_point() + # Base plot 
theme(plot.margin = unit(c(1, 3, 1, 1), "lines")) 

p 

grid.text("20", x = unit(0.91, "npc"), y = unit(0.80, "npc")) 
grid.text("15", x = unit(0.91, "npc"), y = unit(0.56, "npc")) 
grid.text("5", x = unit(0.91, "npc"), y = unit(0.31, "npc"))