gggplot 2-在图外注释

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)

产生这个情节:enter image description here

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

我知道我可以创建第二个情节grid.arrange(A)a la这个职位)但是,确定textGrobs与y轴之间的间距是很繁琐的。有更简单的方法吗?谢谢!


尚方宝剑之说
浏览 1489回答 3
3回答

LEATH

你不需要再画一个情节。你可以用annotation_custom将Grobs定位在绘图区域内或之外的任何位置。Grobs的定位是根据数据坐标进行的。假设“5”、“10”、“15”与“cat 1”、“cat 2”、“cat 3”对齐,TextGrobs的垂直定位将由三个数据点的y坐标给出。默认情况下,ggplot2剪辑格罗布到绘图区域,但裁剪可以被覆盖。需要扩大有关的差额,以便为格罗布会议腾出空间。下面(使用ggplot 2 0.9.2)给出了与第二幅图类似的图:library&nbsp;(ggplot2)library(grid)df=data.frame(y=c("cat1","cat2","cat3"),x=c(12,10,14),n=c(5,15,20))p&nbsp;<-&nbsp;ggplot(df,&nbsp;aes(x,y))&nbsp;+&nbsp;geom_point()&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Base&nbsp;plot &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;theme(plot.margin&nbsp;=&nbsp;unit(c(1,3,1,1),&nbsp;"lines"))&nbsp;&nbsp;&nbsp;#&nbsp;Make&nbsp;room&nbsp;for&nbsp;the&nbsp;grobfor&nbsp;(i&nbsp;in&nbsp;1:length(df$n))&nbsp;&nbsp;{p&nbsp;<-&nbsp;p&nbsp;+&nbsp;annotation_custom( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;grob&nbsp;=&nbsp;textGrob(label&nbsp;=&nbsp;df$n[i],&nbsp;hjust&nbsp;=&nbsp;0,&nbsp;gp&nbsp;=&nbsp;gpar(cex&nbsp;=&nbsp;1.5)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ymin&nbsp;=&nbsp;df$y[i],&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Vertical&nbsp;position&nbsp;of&nbsp;the&nbsp;textGrob &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ymax&nbsp;=&nbsp;df$y[i], &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;xmin&nbsp;=&nbsp;14.3,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Note:&nbsp;The&nbsp;grobs&nbsp;are&nbsp;positioned&nbsp;outside&nbsp;the&nbsp;plot&nbsp;area &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;xmax&nbsp;=&nbsp;14.3) &nbsp;}&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Code&nbsp;to&nbsp;override&nbsp;clippinggt&nbsp;<-&nbsp;ggplot_gtable(ggplot_build(p))gt$layout$clip[gt$layout$name&nbsp;==&nbsp;"panel"]&nbsp;<-&nbsp;"off"grid.draw(gt)

白猪掌柜的

基于gridrequire(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 plottheme(plot.margin = unit(c(1, 3, 1, 1), "lines"))pgrid.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"))
打开App,查看更多内容
随时随地看视频慕课网APP