rnso
rnso

Reputation: 24535

Adjusting legend and colors in ggplot2

I am using following data:

testdf = structure(list(var1 = c(14.9, 15.5, 16.5, 16.6, 15.1, 13.8, 13.2, 
27.6, 22.3, 29.1, 18.4, 14.8, 15.7, 14.3, 15.5, 15.8, 17.6, 14.9, 
16.9, 20.8, 13.9, 20.1, 16.9, 24.7, 15.2, 15.9, 15.8, 17.1, 15.9, 
17.3, 17.5, 14.7, 21, 12, 18.6, 16.1, 16.1, 15.8, 15.9, 13.9, 
13.6, 13.6, 14.2, 13.9, 14.1, 13.9, 13.7, 13.6, 13.9, 13.2), 
    age = c(7L, 7L, 8L, 10L, 7L, 11L, 9L, 14L, 12L, 15L, 10L, 
    12L, 12L, 9L, 9L, 10L, 15L, 10L, 12L, 14L, 15L, 13L, 15L, 
    13L, 11L, 9L, 14L, 12L, 12L, 15L, 13L, 12L, 15L, 7L, 14L, 
    8L, 10L, 8L, 9L, 9L, 8L, 10L, 9L, 9L, 11L, 10L, 10L, 9L, 
    9L, 9L)), .Names = c("var1", "age"), row.names = c(NA, 50L
), class = "data.frame")

I can have a histogram with following code:

ggplot(testdf)+geom_histogram(aes(var1,group=age,color=age,fill=age))

But how can I get ages 7,8,9,10,11,12,13,14,15 in legend and different colours for all these age groups, eg rainbow(9)

I tried following codes but they work only partially:

ggplot(testdf)+geom_histogram(aes(var1,group=age,color=age,fill=age))+scale_colour_continuous(breaks=c(7:15),color=rainbow(9))

ggplot(testdf)+geom_histogram(aes(var1,group=age,color=age,fill=age, legend=F))+scale_colour_continuous(breaks=c(7:15))

Upvotes: 1

Views: 295

Answers (1)

Jaap
Jaap

Reputation: 83215

As @nrussel said, you have to convert age to a factor variable. You can do that within ggplot2. Moreover, you don't really need the group and colour parameters in this case.

With:

ggplot(testdf)+
  geom_histogram(aes(var1, fill=as.factor(age)))

you should get the following result: enter image description here

Upvotes: 2

Related Questions