Search code examples
rggplot2sizelegendstroke

Add legend for stroke points ggplot2


I want to add a legend for the thickness of stroke in the graph. Do you have any idea how can i do that ? I can add a legend for the size but i can not for the stroke.

sizes <- expand.grid(size = (0:3) * 2, stroke = (0:3) * 2)
ggplot(sizes, aes(size, stroke, size = size, stroke = stroke)) +
  geom_abline(slope = -1, intercept = 6, colour = "white", size = 6) + 
  geom_point(shape = 21, fill = "red") + 
  scale_size(range=c(2,12), breaks=c(0,01,02),
             labels=c(">=0",">=0.1",">=0.2"), guide="legend")

ggplot output


Solution

  • I don't think that there is a scale function that works out of the box for strokes, but you could ofcourse build your own.

    sizes <- expand.grid(size = (0:3) * 2, stroke = (0:3) * 2)
    ggplot(sizes, aes(size, stroke, size = size, stroke = stroke)) +
      geom_abline(slope = -1, intercept = 6, colour = "white", size = 6) + 
      geom_point(shape = 21, fill = "red") + 
      scale_size(range=c(2,12), breaks=c(0,01,02),
                 labels=c(">=0",">=0.1",">=0.2"), guide="legend") +
      continuous_scale("stroke", "stroke", 
                       palette = function(x){scales::rescale(x, c(0, 6))},
                       breaks = c(0, 2, 4, 6))
    

    enter image description here

    EDIT:

    I just found out about scales::rescale_pal, which is probably more elegant that making an ad hoc anonymous function for the continuous scale.

    continuous_scale("stroke", "stroke", 
                     palette = scales::rescale_pal(c(0, 6)),
                     breaks = c(0, 2, 4, 6))