为了账号安全,请及时绑定邮箱和手机立即绑定

gggplot 2-在图外注释

gggplot 2-在图外注释

尚方宝剑之说 2019-07-02 17:25:36
gggplot 2-在图外注释我想把样本大小值和图上的点联系起来。我可以用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)产生这个情节:我更喜欢这样的东西:我知道我可以创建第二个情节grid.arrange(A)a la这个职位)但是,确定textGrobs与y轴之间的间距是很繁琐的。有更简单的方法吗?谢谢!
查看完整描述

3 回答

?
LEATH

TA贡献1936条经验 获得超6个赞

你不需要再画一个情节。你可以用annotation_custom将Grobs定位在绘图区域内或之外的任何位置。Grobs的定位是根据数据坐标进行的。假设“5”、“10”、“15”与“cat 1”、“cat 2”、“cat 3”对齐,TextGrobs的垂直定位将由三个数据点的y坐标给出。默认情况下,ggplot2剪辑格罗布到绘图区域,但裁剪可以被覆盖。需要扩大有关的差额,以便为格罗布会议腾出空间。下面(使用ggplot 2 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 grobfor (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 clippinggt <- ggplot_gtable(ggplot_build(p))gt$layout$clip[gt$layout$name == "panel"] <- "off"grid.draw(gt)


查看完整回答
反对 回复 2019-07-02
?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

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


查看完整回答
反对 回复 2019-07-02
  • 3 回答
  • 0 关注
  • 1485 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信