rggplot2legendgeom-point

how to have a legend for size of geom_points() and also set the size of the dots themselves?


I am trying to plot a sort of bubble plot but i am unable to set the size of the dots and have a legend explaining how the sizing works.

These are two examples which combined give me the expected output. The first one allows me to set the size of the dots. The second one prints the legend. I need to have both: sized dots and a legend explaining the size. But if i have one, i am unable to get the other, too. Would be great to be able to set the title for the "size legend", too.

Any clue?

library("ggplot2")

x <- sample(2000, 1000, replace=T)
y <- sample(2000, 1000, replace=T)
category <- sample(c("one", "two"), 2000, replace = TRUE)
size <- sample(2000, 1000, replace=T)/50

df <- data.frame(x, y, category, size)

# first example with sized dots
dev.new()

ggplot(df, aes(x=x, y=y, fill=category))+
   geom_point(shape=21, color="black", size=df$size)+
   guides(fill=guide_legend(override.aes=list(size=40)))

# second example with the legend
dev.new()

ggplot(df, aes(x=x, y=y, fill=category, size=size))+
   geom_point(shape=21, color="black")+
   guides(fill=guide_legend(override.aes=list(size=40)))

If there is a duplicate question, please link it and mark this one. Thanks!


Solution

  • ggplot(df, aes(x=x, y=y, fill=category, size=size))+
      geom_point(shape=21, color="black") +
      guides(fill=guide_legend(override.aes=list(size=8), title = "New category"))
    

    enter image description here