2017-07-22 6 views
0

Ich habe diese Daten, die ich versuche, benutzerdefinierte Farben zu verwendenFarben in ggplot% Grafik

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) 

ich ggplot verwenden, um ein völlig in Ordnung Diagramm zu bekommen, aber ich habe mich gefragt, wie ich es bearbeiten würde meine Firma verwenden Standardfarben

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 

ich ein Vektor genannt Farben haben:

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

und ich versuchte es mit diesem grafisch darzustellen:

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") 

und einen unerwarteten Fehler erhalten. Kann jemand helfen?

Antwort

2

Es gibt mindestens zwei Möglichkeiten, das zu tun:

Gerade + scale_fill_manual(values = colors) hinzufügen:

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

Alternativ Sie eine spezielle Spalte mit der definierten Farbe zu Ihrem Datenrahmen hinzufügen können:

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

Vielen Dank! das hat funktioniert – Walker

Verwandte Themen