R - ggplot柱形图 - 布鲁尔对象中的颜色顺序不起作用



我正在尝试更改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

但是最后一种方法不起作用,并且生成的倒数第二个和第三个图表是相同的,尽管对象中的颜色顺序颠倒了。

你想要

scale_fill_manual(values = blues)或相反地使用blues.rev(你实际上并没有在你的示例代码中创建,我认为这是一个错字)。

仅当您按名称选择默认调色板之一时,才使用scale_*_brewer。否则,请使用scale_*_manual进行此类操作。

最后一个不起作用,因为您使用的是颜色而不是填充。

最后,回车和标签:爱它们,珍惜它们,使用它们!

最新更新