2017-07-22 111 views
0

我有這個數據,我試圖使用自定義顏色顏色ggplot%圖

School <- c('School1','School1','School1','School1','School1','School1','School1','School1','School2','School2','School2','School2','School3','School3','School3','School3') 
Condition <- c('2','1','4','3','2','1','4','3','2','4','2','4','2','1','2','1') 
Count <- c(136,465,2,45,652,123,205,9,392,157,201,111,298,888,254,709) 
Year <- c('2009','2009','2009','2009','2010','2010','2010','2010','2009','2009','2010','2010','2009','2009','2010','2010') 
acronym <- c('S1','S1','S1','S1','S1','S1','S1','S1','S2','S2','S2','S2','S3','S3','S3','S3') 
df <- data.frame(School, Condition, Count, Year, acronym) 

我用ggplot得到一個完美的罰款圖形,但我不知道我怎麼會編輯它使用我公司的標準顏色

test <- ggplot(df, aes(x=Year, y=Count, fill=Condition)) + 
    geom_bar(stat="identity", position = "fill") + scale_y_continuous(labels = percent_format()) + facet_grid(~acronym) + 
    theme_bw() + labs(title="Chart Title") 
test 

我有一個矢量稱爲顏色:

colors 
[1] "#101820" "#AF272F" "#EAAA00" "#D0D0CE" 

,我試圖與該曲線圖是:

test <- ggplot(df, aes(x=Year, y=Count, fill=Condition, color = colors 
)) + 
    geom_bar(stat="identity", position = "fill") + scale_y_continuous(labels = percent_format()) + facet_grid(~acronym) + 
    theme_bw() + labs(title="Chart Title") 

,並得到了一個意外的錯誤。有人可以協助嗎?

回答

2

至少有兩種可能做到這一點:

只需添加+ scale_fill_manual(values = colors)

ggplot(df, aes(x=Year, y=Count, fill=Condition)) + 
    geom_bar(stat="identity", position = "fill") + 
    scale_y_continuous(labels = percent_format()) + 
    facet_grid(~acronym) + 
    theme_bw() + 
    labs(title="Chart Title") + 
    scale_fill_manual(values = colors) # added 

enter image description here

或者,您可以用定義的顏色到您的數據框中添加一個特殊列:

colMap <- setNames(colors, unique(df$Condition)) 
df$color <- colMap[df$Condition] 

ggplot(df, aes(x=Year, y=Count, fill=I(color))) + # added fill=I(color) 
    geom_bar(stat="identity", position = "fill") + 
    scale_y_continuous(labels = percent_format()) + 
    facet_grid(~acronym) + 
    theme_bw() 
+0

謝謝!這工作 – Walker