Annotating text on individual facet in ggplot2

前端 未结 6 828
野的像风
野的像风 2020-11-22 09:39

I want to annotate some text on last facet of the plot with the following code:

library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <-          


        
6条回答
  •  盖世英雄少女心
    2020-11-22 10:37

    Expanding slightly on joran's excellent answer, to clarify how the label dataframe works.

    You can think of "mpg" and "wt" as the x and y coordinates, respectively (I find it easier to keep track of the original variable names than renaming them, as in Kamil's also-excellent answer). You need one row per label, and the "cyl" column shows which facet each row is associated with.

    ann_text<-data.frame(mpg=c(25,15),wt=c(3,5),cyl=c(6,8),label=c("Label 1","Label 2"))
    
    ann_text
    >  mpg wt cyl  label
    >  25  3   6   Label 1
    >  15  5   8   Label 2
    
    p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
    p <- p + facet_grid(. ~ factor(cyl))
    p + geom_text(data = ann_text,label=ann_text$label)
    

提交回复
热议问题