0

Is there a way to ensure that the legend for the size aesthetic in ggplot always starts and finishes at the minimum and maximum values?

For instance, the minimum value in the call below:

p<-ggplot(mpg, aes(displ, hwy, size = hwy)) + geom_point()

(first example here) should be 12. But the smallest circle size it shows corresponds to a value of 20.

I tried adding:

p+scale_size_manual(values=c(min(mpg$hwy),median(mpg$hwy), max(mpg$hwy)), labels = c(as.character(min(mpg$hwy)),as.character(median(mpg$hwy)), as.character(max(mpg$hwy))))

but it throws an error (even though I think the labels and values are in the appropriate format). I also tried:

scale_size_continuous(range = c(min(mpg$hwy), max(mpg$hwy))

as recommended here, but it makes symbols which are WAY too big.

Any clues? thanks!

agpo
  • 3
  • 2

2 Answers2

1

You can try:

p<-ggplot(mpg, aes(displ, hwy, size = factor(hwy))) + geom_point()

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84
1

You could set breaks based on the minimum and maximum values of hwy; the number of breaks would be up to you to decide. The reason you do not get the minimum and maximum values, necessarily from ggplot is that it automates the process.



library(ggplot2)


ggplot(mpg, aes(displ, hwy, size = hwy)) + 
  geom_point()+
  scale_size_continuous(breaks = seq(range(mpg$hwy)[1], range(mpg$hwy)[2], length.out = 5))

Created on 2020-07-10 by the reprex package (v0.3.0)

Peter
  • 11,500
  • 5
  • 21
  • 31