我有一个根据数据框中的SalesCategory
给出颜色的图。但是,其中一些SalesCategory
不再有效,我想将灰色分配给不活动的SaleCategory
。如何将一组颜色分配给活动类别,将另一组颜色分配给非活动类别?对于此示例,示例很简单,因为您可以轻松地将scale_fill_manual
用于所有情况,但此请求背后的数据会因为它具有的类别数量而无法使用。
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')
答案 0 :(得分:3)
这样的事情怎么样?
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)