Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the colour palette in histogram

I am trying to change the colours of my histogram, but not sure how to do it, that's my code:

qplot(user, count, data=count_group, geom="histogram", fill=group,
            xlab = "users", ylab="count", 
            main="Users")+
    opts(axis.text.x=theme_text(angle=90, hjust=0, size=7))

here is the histogram I get, but the default colours are too bright,

enter image description here

I would like to use colours like this

I tried to add the line, but it didnt work.

  scale_fill_brewer(palette = palette)
like image 762
Mallvina Avatar asked Dec 17 '22 03:12

Mallvina


1 Answers

If you want to use the Brewer Set1 with that many groups, you could do something like this:

library(ggplot2)

count_group <- data.frame(user=factor(rep(1:50, 2)), 
                          count=sample(100, 100, replace=T), 
                          group=factor(rep(LETTERS[1:20], 5)))

library(RColorBrewer)
cols <- colorRampPalette(brewer.pal(9, "Set1"))
ngroups <- length(unique(count_group$group))
qplot(user, count, data=count_group, geom="histogram", fill=group,
      xlab = "users", ylab="count") +
      opts(axis.text.x=theme_text(angle=90, hjust=0, size=7)) +
      scale_fill_manual(values = cols(ngroups))

Brewer Set 1 with many groups in ggplot


EDIT

You can create and use multiple colorRampPalettes, e.g. to assign blues to groups A to J and reds to groups K to T:

blues <- colorRampPalette(c('dark blue', 'light blue'))
reds <- colorRampPalette(c('pink', 'dark red'))

qplot(user, count, data=count_group, geom="histogram", fill=group,
      xlab = "users", ylab="count") +
        opts(axis.text.x=theme_text(angle=90, hjust=0, size=7)) +
        scale_fill_manual(values = c(blues(10), reds(10)))
# blues(10) and reds(10) because you want blues for the first ten
#  groups, and reds thereafter. Each of these functions are equivalent
#  to providing vectors containing ten hex colors representing a gradient
#  of blues and a gradient of reds.

ggplot with blues and reds

like image 116
jbaums Avatar answered Jan 30 '23 22:01

jbaums