Question

Suppose I work with the mtcars data set. I would like to set the size of the points according to the weight (wt). If I do that as shown below, R/ggplot2 will give me a legend with 4 categories (2,3,4,5).

library(ggplot2)
mtc <- mtcars
p1 <- ggplot(mtc, aes(x = hp, y = mpg))
p1 <- p1 + geom_point(aes(size = wt))     
print(p1)

How can I change the scale/names/categories of the legend. I found information on how to do that if the "categories" would be factors, but I don't know how to do this with numeric values. I need to keep them numeric otherwise it doesn't work with the size of the dots anymore.

My real data set has about 100 values for wt (everything from 1-150) and I want to keep 5 values. (ggplot 2 gives me 2 -> 50 and 100)

1) How can I change the scale of that legend? In the mtc example for example I just want 2 points of size 2 and 5

2) I was thinking about making categories such as:

mtc$wtCat[which(mtc$wt<=2)]=1
mtc$wtCat[which(mtc$wt>2 & mtc$wt<=3)]=2
mtc$wtCat[which(mtc$wt>3)]=3

p1 <- ggplot(mtc, aes(x = hp, y = mpg))
p2 <- p1 + geom_point(aes(size = wtCat), stat="identity")     
print(p2)

and then just rename 1,2,3 in the legend into <=2, 2-3 and >3 but I didn't figure out how to do that as well.

Thank you so much.

Was it helpful?

Solution

You can use scale_size_continuous() and with argument breaks= set levels you want to see in legend and with argument labels= change how legend entries are labelled.

ggplot(mtcars,aes(hp,mpg,size=wt))+geom_point()+
  scale_size_continuous(breaks=c(2,5),labels=c("<=2",">2"))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top