Specify position of geom_text by keywords like “top”, “bottom”, “left”, “right”, “center”

后端 未结 5 1385
名媛妹妹
名媛妹妹 2020-12-31 23:37

I wish to position text in a ggplot without specifying x and y positions, but instead using keywords, like e.g. in graphics::leg

5条回答
  •  失恋的感觉
    2021-01-01 00:04

    The solution using infinity is good and is definitely the easiest option.

    However, if you want more control over the position of your labels (for example, if you want them centered, or if you want more space between the axis line and annotation), you can use some math with min() and max() of your plot titles to create centered titles at top, bottom, right, or left. The code below is a bit lengthy, but will still place labels correctly if the values in your plot change. Also, to copy to other plots, you won't need to manually calculate values, just change the names of the x and y variables.

    sp <- ggplot(mpg, aes(hwy, cty)) +
      geom_point() +
      theme_classic() +
      annotate("text", label = "top", 
               x = 0.5*(min(mpg$hwy) + max(mpg$hwy)), y = max(mpg$cty), vjust = 1) +
      annotate("text", label = "bottom", 
               x = 0.5*(min(mpg$hwy) + max(mpg$hwy)), y = min(mpg$cty), vjust = 0) +
      annotate("text", label = "right", 
               x =  max(mpg$hwy), y = 0.5*(min(mpg$cty) + max(mpg$cty)), hjust = 1) +
      annotate("text", label = "left", 
                x =  min(mpg$hwy), y = 0.5*(min(mpg$cty) + max(mpg$cty)), hjust = 0)
    
    sp   
    

提交回复
热议问题