2016-08-10 68 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。