2016-08-10 160 views
0

我知道这个问题已被asked before,但我不能得到接受的工作的答案。这是我的数据集:ggplot中一致的颜色映射

library(ggplot2) 
library(scales)  
full_data<-NULL 
full_data$race<-c(1,2,3,4,1,2,3,4,3,4,3,4,4) 
full_data$race<-as.factor(full_data$race) 
full_data$Year<-sample(2000:2005,13,replace=TRUE) 
full_data$number<-sample(5:10,13,replace=TRUE) 
full_data$program<-c(rep(1,6),rep(2,7)) 
full_data<-as.data.frame(full_data) 
program1<-subset(full_data, full_data$program==1) 
program2<-subset(full_data, full_data$program==2) 
identical(levels(program1$race),levels(program2$race)) 

我确信为race的水平在每个数据集是相同的,但是当我做了两个巴图,甚至从对方的回答指定的矢量,色彩酒吧之间的不同地块。

MyPalette <- c("1" = "#5DD0B9", "2" = "#E1E7E9", "3" = "#1f78b4", 
      "4" = "#a6cee3") 

p1_chart<-ggplot(data=program1, aes(x=program1$Year, y=program1$number, fill=program1$race)) + 
    geom_bar(stat="identity", position=position_dodge())+ 
    scale_colour_manual(values = MyPalette) 
p1_chart 

p2_chart<-ggplot(data=program2, aes(x=program2$Year, y=program2$number, fill=program2$race)) + 
geom_bar(stat="identity", position=position_dodge())+ 
    scale_colour_manual(values = MyPalette) 
p2_chart 

我真的很感激任何想法!

+0

你想要'scale_fill_manual' – Nate

回答

0

只是为了显示你在colour_scale实际上是着色,使用MyPalette为fill_scale:

library(RColorBrewer) 

p1_chart<- ggplot(data=program1, aes(x=Year, y=number, fill=race, colour = race)) + 
    geom_bar(stat="identity", position=position_dodge())+ 
    scale_fill_manual(values = MyPalette) + 
    scale_color_brewer(palette = "Dark2") + 
    theme_bw() 
p1_chart 

p2_chart<-ggplot(data=program2, aes(x=Year, y=number, fill=race, colour = race)) + 
    geom_bar(stat="identity", position=position_dodge())+ 
    scale_fill_manual(values = MyPalette) + 
    scale_color_brewer(palette = "Dark2") + 
    theme_bw() 
p2_chart 

enter image description here

enter image description here

旁注:你真的不希望在ggplot调用中使用df $引用,因为您已经设置了data = df。