ggplot2 - 在剧情之外注释

时间:2012-09-13 15:38:55

标签: r annotations 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)

产生这个情节: enter image description here

我更喜欢这样的东西: enter image description here

我知道我可以创建第二个图并使用grid.arrange(la this post)但是确定textGrobs与y轴对齐的间距会很繁琐。有更简单的方法吗?谢谢!

3 个答案:

答案 0 :(得分:53)

您无需绘制第二个图。您可以使用annotation_custom将绘图定位在绘图区域内部或外部的任何位置。凹槽的定位是根据数据坐标。假设“5”,“10”,“15”与“cat1”,“cat2”,“cat3”对齐,textGrobs的垂直位置被处理 - 你的三个textGrobs的y坐标由三个数据点的y坐标。默认情况下,ggplot2会将grobs剪辑到绘图区域,但可以覆盖裁剪。需要扩大相关的保证金,以便为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

答案 1 :(得分:28)

使用ggplot2 3.0.0现在很简单,因为现在可以通过调用coord_cartesian(clip = 'off')来禁用绘图中的裁剪,如下例所示。

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

    # Create the plot
    ggplot(df,aes(x=x,y=y,label=n)) +
      geom_point()+
      geom_text(x = 14.25, # Set the position of the text to always be at '14.25'
                hjust = 0,
                size = 8) +
      coord_cartesian(xlim = c(10, 14), # This focuses the x-axis on the range of interest
                      clip = 'off') +   # This keeps the labels from disappearing
      theme(plot.margin = unit(c(1,3,1,1), "lines")) # This widens the right margin

enter image description here

答案 2 :(得分:4)

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