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
ggplot2
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)
白猪掌柜的
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"))
- 3 回答
- 0 关注
- 1566 浏览
添加回答
举报
0/150
提交
取消