How to add a line to a continuous color legend but not the plot?

后端 未结 1 808
余生分开走
余生分开走 2021-01-01 04:39

Is there a way to add a line just to a continuous gradient legend? I was unable to find any examples of this using ggplot2.

For example, how could I add a r

相关标签:
1条回答
  • 2021-01-01 05:33

    Not sure how to add a custom line on gradient legend, but I do know how to add a custom tick label with custom color:

    library(ggplot2)
    ggplot(df, aes(x, y, color = y)) + 
      geom_point() +
      scale_colour_gradient(breaks = c(-2, 0, 1.7, 2),
                            labels = c(-2, 0, "1.7 (important)", 2)) +
      guides(color = guide_colorbar(barheight = 10,
                                    label.theme = element_text(colour = c("black", "black", 
                                                                          "red", "black"), 
                                                               angle = 0,
                                                               size = 12)))
    

    Notice that the "1.7" label overlaps the "2" label. You can either do something like the following:

    ggplot(df, aes(x, y, color = y)) + 
      geom_point() +
      scale_colour_gradient(breaks = c(-2, 0, 1.7, 2),
                            labels = c(-2, 0, "<-- 1.7 (important)", 2)) +
      guides(color = guide_colorbar(barheight = 10,
                                    label.theme = element_text(colour = c("black", "black", 
                                                                          "red", "black"), 
                                                               angle = 0,
                                                               size = 12)))
    

    or adjust the horizontal position of the "1.7" label:

    ggplot(df, aes(x, y, color = y)) + 
      geom_point() +
      scale_colour_gradient(breaks = c(-2, 0, 1.7, 2),
                            labels = c(-2, 0, "1.7 (important)", 2)) +
      guides(color = guide_colorbar(barheight = 10,
                                    label.hjust = c(0, 0, 0.1, 0),
                                    label.theme = element_text(colour = c("black", "black", 
                                                                          "red", "black"), 
                                                               angle = 0,
                                                               size = 12)))
    

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