ggplot柱形图 - Brewer对象中颜色顺序无效

3

我正在尝试更改ggplot列图的颜色。经过谷歌搜索,我认为以下代码可以解决问题:

require(ggplot2)
require(RColorBrewer)
State <- c(rep("NSWTC",5), rep("TCV",5), rep("QTC",5), 
           rep("WATC",5), rep("SAFA",5), rep("Other",5))

Year  <- rep(c("11-12","12-13","13-14","14-15","15-16"),6)

##some random data
Funding.Programme <- abs(rnorm(30))

df <- data.frame(State, Year, Funding.Programme)

##this line makes the graph in the order you inputted it, rather than alphabetical
df$State <- factor(df$State, levels=unique(df$State))

##ugly coloured
bars <- ggplot(df) + 
            aes(x=Year ,y=Funding.Programme, fill=Year) + 
            geom_bar(stat='identity') + 
            facet_grid(facets=~State) + 
            scale_y_continuous('Gross Issuance Requirements')

##nicely coloured
blues <- brewer.pal(5, "Blues")
blues <- rev(blues)
##the following two graphs have the same colours
bars <- ggplot(df) + 
            aes(x=Year ,y=Funding.Programme, fill=Year) + 
            geom_bar(stat='identity') + 
            facet_grid(facets=~State) + 
            scale_y_continuous('Gross Issuance Requirements') + 
            scale_fill_brewer(blues)
bars
bars <- ggplot(df) + 
            aes(x=Year ,y=Funding.Programme, fill=Year) + 
            geom_bar(stat='identity') + 
            facet_grid(facets=~State) + 
            scale_y_continuous('Gross Issuance Requirements') + 
            scale_fill_brewer(blues.rev)
bars

##and this does not adjust the default colours
bars <- ggplot(df)+ 
            aes(x=Year,y=Funding.Programme, fill=Year) + 
            geom_bar(stat='identity') + 
            facet_grid(facets=~State) + 
            scale_y_continuous('Gross Issuance Requirements') + 
            scale_colour_manual(values = blues.rev)
bars

但是最后一种方法并不起作用,而且产生的第二张和倒数第三张图表是相同的,尽管颜色顺序在对象中被反转。
1个回答

3
你需要使用scale_fill_manual(values = blues) 或者相反的 blues.rev(在你的示例代码中实际上没有创建它,我假设这是一个 typo)。
只有当你按名称选择其中一个默认调色板时,才应该使用scale_*_brewer。否则,对于这种情况,请使用scale_*_manual
最后一条不起作用是因为你使用的是颜色而不是填充。
最后,回车和制表符:热爱他们,珍爱他们,使用他们!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接