Search code examples
rggplot2legendgeom-point

how to change size of symbol in ggplot2 when size, shape, and color are set through geom_point?


The problem i am having is surely trivial, and yet i am unable to solve it. What i need is to have my own shape, colour, and size for the geom_point(). However, if i set it, the size of the symbols in the legend is not changing.

So, say i want to plot this:

library("ggplot2")

x <- rnorm(2000, 0, 1)
y <- rnorm(2000, 0, 1)
category <- sample(c("one", "two"), 2000, replace = TRUE)
size <- rnorm(2000, 0, 1)*10

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

dev.new()

ggplot(df, aes(x=x, y=y, color=category)) +
    geom_point(size = df$size) +
    guides(color = guide_legend(override.aes = list(size = 10)))

But then, if i want to change the aesthetic of my geom_point(), i am unable to set the size of the dots in the legend. In other words, this is not working anymore:

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

I feel like i should pass more parameters to guides but maybe not. What to do?

I can't find any answer for my question. If you do, please mark this as duplicate and link it. Thank you!

EDIT:

the expected output is represented by the second plot i provided (where i set the aesthetic for geom_point()) but then i need the dots in the legend as big as i want.

EDIT 2:

using sample instead of rnorm (as suggested in a comment) gives the same problem, it seems:

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)

dev.new()

ggplot(df, aes(x=x, y=y, color=category)) +
    geom_point(size = df$size) +
    guides(color = guide_legend(override.aes = list(size = 10)))

dev.new()

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

Solution

  • Maybe this helps?

    library(ggplot2)
    
    set.seed(213)
    x <- rnorm(2000, 0, 1)
    y <- rnorm(2000, 0, 1)
    category <- sample(c("one", "two"), 2000, replace = TRUE)
    size <- rnorm(2000, 0, 1)*10
    
    
    ggplot(df, aes(x = x, y=y, fill = category)) +
    geom_point(shape = 21, aes(size = size)) +
      guides(fill = guide_legend(override.aes = list(size = 5)),
             size  = "none")
    

    enter image description here