red-swan
red-swan

Reputation: 1269

How do assign different sets of colors to different groups of categories?

I have a plot that gives color based on the SalesCategory in the data frame. Some of these SalesCategorys, however, are no longer active and I would like to assign grey colors to the inactive SaleCategorys. How do I assign one set of colors to the active categories and annother set of colors to the inactive set? The sample is trivial for this example because you could easily use scale_fill_manual for all the cases, but the data behind this request would make that unfeasible because of the number of categories it has.

myFrame <- 
    data.frame(Year = c(2010L, 2010L, 2010L, 2010L, 2011L, 2011L, 2011L, 2011L, 2011L, 
                        2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2013L, 2013L, 2013L, 
                        2013L, 2013L, 2013L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L),
               SalesCategory = c("Bobsleds", "IceSkates", "RollerSkates", "HockeyPucks", "Bobsleds", 
                                 "IceSkates", "RollerSkates", "HockeyPucks", "RollerBlades", "Bobsleds", 
                                 "IceSkates", "RollerSkates", "HockeyPucks", "RollerBlades", "Helmets", 
                                 "Bobsleds", "IceSkates", "RollerSkates", "HockeyPucks", "RollerBlades", 
                                 "Helmets", "Bobsleds", "IceSkates", "RollerSkates", "HockeyPucks", 
                                 "RollerBlades", "Helmets"),
               PctOfSales = c(0.5, 0.3, 0.1, 0.1, 0.3, 0.3, 0.3, 0.05, 0.05, 0.1, 0.2, 0.4, 
                              0, 0.15, 0.15, 0, 0.05, 0.4, 0, 0.35, 0.2, 0, 0, 0.4, 0, 0.4, 
                              0.2),
               ActiveRevenueStream =c(FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, 
                                      FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, 
                                      TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE))

# this plot gives colors to all the categories indiscriminantly
ggplot(myFrame,(aes(Year,PctOfSales, fill = SalesCategory))) +
    geom_bar(stat = 'identity')

Upvotes: 2

Views: 56

Answers (1)

Mike H.
Mike H.

Reputation: 14370

How about something like this?

  library(RColorBrewer)
  uniq_inactive<-unique(myFrame[myFrame$ActiveRevenueStream==FALSE,"SalesCategory"])
  uniq_active<-unique(myFrame[myFrame$ActiveRevenueStream==TRUE,"SalesCategory"])

  my_active_cols <- brewer.pal(length(uniq_active),"Set1")
  names(my_active_cols)<- uniq_active

  my_inactive_cols <- gray.colors(length(uniq_inactive),start=0.5,end=0.7)
  names(my_inactive_cols) <- uniq_inactive

  my_cols <- c(my_active_cols,my_inactive_cols)

ggplot(myFrame,(aes(Year,PctOfSales, fill = SalesCategory))) +
  geom_bar(stat = 'identity') + scale_fill_manual(values=my_cols)

enter image description here

Upvotes: 3

Related Questions