R ggplot2: Labeling a horizontal line without associating the label with a series

后端 未结 2 1302
北海茫月
北海茫月 2021-01-07 05:59

I\'d like to label a horizontal line on a ggplot with multiple series, without associating the line with a series. R ggplot2: Labelling a horizontal line on the y a

相关标签:
2条回答
  • 2021-01-07 06:29

    Is this what you had in mind?

    library(ggplot2)
    df <- data.frame(y=1:10, x=1:10, col=c("a", "b"))  # Added col
    h <- 7.1
    ggplot(df, aes(x=x,y=y)) + 
      geom_point(aes(color=col)) +
      geom_hline(yintercept=h) +
      geom_text(data=data.frame(x=0,y=h), aes(x, y), label=h, vjust=-1)
    

    First, you can make the color mapping local to the points layer. Second, you do not have to put all the aesthetics into calls to aes(...) - only those you want mapped to columns of the dataset. Three, you can have layer-specific datasets using data=... in the calls to a specific geom_*.

    0 讨论(0)
  • 2021-01-07 06:33

    You can use annotate instead:

    plot2 + annotate(geom="text", label=h, x=1, y=h, vjust=-1)
    

    Edit: Removed drawback that x is required, since that's also true of geom_text.

    0 讨论(0)
提交回复
热议问题