2012-09-13 98 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"))