geom_text writing all data on all facets

风格不统一 提交于 2019-12-22 04:43:27

问题


I used ggplot with facet_grid and I'd like to indicate on each facet the number of observations in each facet. I follow examples provided on many sites but when I get it to write anything, it writes all four observation numbers on top of each other on all four plots.

Here the geom_text layer command: geom_text(data=ldata, aes(x=xpos, y=ypos, label=lab, size=1), group=NULL, hjust=0, parse=FALSE)

and ldata is a data frame listing the coordinates (xpos, ypos) on each plot and the number of observations (lab). It's printing the numbers in the right position on the plot, but all four are written on top of each other on all four plots. I can not figure out what I'm doing wrong.

ldata:

xpos ypos lab

1 10 1.35 378

2 10 1.35 2

3 10 1.35 50

4 10 1.35 26


回答1:


You almost have it. It is just that you need one more column in your ldata data frame which is what you will give to facet_grid. (I changed the Ypos to Inf)

Notice the role of the splitter column in ldata below, and how it is used in facet_grid

xpos <- c(10,10,10) 
ypos <- c(Inf,Inf,Inf)
lab <- c(378,2,50)
splitter <- c(1:3)
ldata <- data.frame(xpos, ypos, lab, splitter)


ggplot(mtcars) + geom_bar(aes(x=cyl)) + facet_grid(~splitter) + 
  geom_text(data=ldata, aes(x=xpos, y=ypos, 
                            label=lab, size=1), 
            vjust=2, parse=FALSE)

Which produces:



来源:https://stackoverflow.com/questions/20428902/geom-text-writing-all-data-on-all-facets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!