如何在ggplot2中扩展调色板

时间:2014-01-05 20:26:54

标签: r ggplot2

大家好我在ggplot2中制作一个图形,但我希望为它添加不同的颜色。一种方法是使用RColorBrewer包中的调色板。我使用了这个包中的调色板,但我得到了这个。我使用的代码是下一个:

library(ggplot2)
library(reshape2)
library(scales)
library(RColorBrewer)
#Graphic
png(filename = "Atotal.png", width = 1050, height = 900)
Atotal=ggplot(Melt.Atotal, aes(x = Var2, y = value, fill = Mes)) +
  geom_bar(stat = "identity") + scale_y_continuous(labels = comma) + scale_fill_brewer(palette="Set3") +
  annotate("text", x = ncol(AtotalM) - 1.3, y = finalValA1 + 4000000, 
           label = finalValA1f, size = 5) + theme(axis.text.x=element_text(angle=90,colour="grey20",face="bold"),axis.text.y=element_text(colour="grey20",face="bold",hjust=1,vjust=0.8),axis.title.x=element_text(colour="grey20",face="bold"),axis.title.y=element_text(colour="grey20",face="bold"))+xlab('Mes')+ylab('Total')+ ggtitle("Consumo Automotriz (A)")+theme(plot.title = element_text(lineheight=3, face="bold", color="black",family="F",size=24))
print(Atotal)
dev.off()

在此代码中使用scale_fill_brewer(palette="Set3")的结果是下一个:

enter image description here

并非所有Mes的值都在考虑之中。我的数据为Melt.Atotal,它有3个变量MesVar2Value。构建Melt.Atotal的代码是下一个(我添加基本矩阵的dput()版本):

Melt.Atotal <- melt(AtotalMt)
Melt.Atotal<-transform(Melt.Atotal, Var1 = factor(Var1, colnames(AtotalMt)),
                       Var2 = factor(Var2, rownames(AtotalMt)))
names(Melt.Atotal)[1] <- "Mes"

dput()的{​​{1}}版本是下一个:

AtotalMt

感谢您的帮助。

1 个答案:

答案 0 :(得分:13)

Set3有12种不同的颜色(见?RColorBrewer)。如果你想要更多,你需要插值:

library(grid) # for unit()
cols <- colorRampPalette(brewer.pal(12, "Set3"))
myPal <- cols(length(unique(Melt.Atotal$Mes)))
Atotal <- ggplot(Melt.Atotal, aes(x = Var2, y = value, fill = Mes)) +
  geom_bar(stat = "identity") + 
  scale_fill_manual(values = myPal) +
  theme(axis.text.x=element_text(angle=90), 
        legend.text=element_text(size=8),
        legend.key.height=unit(.1, "cm"))
Atotal

enter image description here