GGPLOT2 - 诠释剧情之外 [英] ggplot2 - annotate outside of plot

查看:186
本文介绍了GGPLOT2 - 诠释剧情之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想样本大小值与一个情节点连接。我可以使用 geom_text 来点附近的数字的位置,但这是凌乱。这将是更清洁排队它们沿着剧情的外边缘。

I would like to associate sample size values with points on a plot. I can use geom_text to position the numbers near the points, but this is messy. It would be much cleaner to line them up along the outside edge of the plot.

比如说,我有:

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)

这会产生这个阴谋:

Which produces this plot:

我想preFER更多的东西是这样的:

I would prefer something more like this:

我知道我可以创建第二个情节,并使用 grid.arrange (一拉<一个href=\"http://stackoverflow.com/questions/10525957/how-to-draw-lines-outside-of-plot-area-in-ggplot2\">this张贴),但它会是乏味确定textGrobs的间距与y轴对齐。是否有更简单的方法来做到这一点?谢谢!

I know I can create a second plot and use grid.arrange (a la this post) but it would be tedious to determine the spacing of the textGrobs to line up with the y-axis. Is there an easier way to do this? Thanks!

推荐答案

您不需要进行绘制第二个情节。您可以使用 annotation_custom 来位置内或绘图区以外的任何地方grobs。该grobs的定位是在数据坐标表示。假设5,10,15与CAT1,CAT2,CAT3时,textGrobs的垂直定位是照顾对齐 - 你的三个textGrobs的y坐标由给出的三个数据点的y坐标。默认情况下, GGPLOT2 剪辑grobs到绘图区,但裁剪可以被覆盖。相关的保证金需要扩大,以腾出空间给GROB。以下(使用GGPLOT2 0.9.2)给出了类似的关于你的第二情节一个情节:

You don't need to be drawing a second plot. You can use annotation_custom to position grobs anywhere inside or outside the plotting area. The positioning of the grobs is in terms of the data coordinates. Assuming that "5", "10", "15" align with "cat1", "cat2", "cat3", the vertical positioning of the textGrobs is taken care of - the y-coordinates of your three textGrobs are given by the y-coordinates of the three data points. By default, ggplot2 clips grobs to the plotting area but the clipping can be overridden. The relevant margin needs to be widened to make room for the grob. The following (using ggplot2 0.9.2) gives a plot similar to your second plot:

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)

这篇关于GGPLOT2 - 诠释剧情之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆