Add a horizontal line to plot and legend in ggplot2

后端 未结 2 1047
甜味超标
甜味超标 2020-12-01 05:06

This code creates a nice plot but I would like to add a horizontal black line at y=50 AND have the legend show a black line with the text \"cutoff\" in the legend, but leave

2条回答
  •  孤城傲影
    2020-12-01 05:53

    (1) Try this:

    cutoff <- data.frame( x = c(-Inf, Inf), y = 50, cutoff = factor(50) )
    ggplot(the.data, aes( year, value ) ) + 
            geom_point(aes( colour = source )) + 
            geom_smooth(aes( group = 1 )) + 
            geom_line(aes( x, y, linetype = cutoff ), cutoff)
    

    screenshot

    (2) Regarding your comment, if you don't want the cutoff listed as a separate legend it would be easier to just label the cutoff line right on the plot:

    ggplot(the.data, aes( year, value ) ) + 
        geom_point(aes( colour = source )) + 
        geom_smooth(aes( group = 1 )) + 
        geom_hline(yintercept = 50) + 
        annotate("text", min(the.data$year), 50, vjust = -1, label = "Cutoff")
    

    screenshot

    Update

    This seems even better and generalizes to mulitple lines as shown:

    line.data <- data.frame(yintercept = c(50, 60), Lines = c("lower", "upper"))
    ggplot(the.data, aes( year, value ) ) + 
            geom_point(aes( colour = source )) + 
            geom_smooth(aes( group = 1 )) + 
            geom_hline(aes(yintercept = yintercept, linetype = Lines), line.data)
    

提交回复
热议问题