ggplot2 – 在图的外部注释

我想将样本大小值与图上的点关联起来。 我可以使用geom_text来定位点附近的数字,但这是混乱的。 将它们沿着剧情的外边缘排列起来会更加清晰。

例如,我有:

 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) 

哪个产生这个情节: 在这里输入图像描述

我更喜欢这样的东西: 在这里输入图像描述

我知道我可以创build第二个绘图,并使用grid.arrange ( 这个post ),但确定textGrobs与y轴排列的间距是很繁琐的。 有没有更简单的方法来做到这一点? 谢谢!

你不需要画第二个阴谋。 您可以使用annotation_custom在绘图区域内部或外部的任何地方定位grob。 grobs的定位是根据数据坐标来确定的。 假设“5”,“10”,“15”与“cat1”,“cat2”,“cat3”alignment,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) 

在这里输入图像描述

基于grid简单解决scheme

 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"))