Reputation: 489
I have this data that I'm trying to use custom colors
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)
I use ggplot to get a perfectly fine graph but I was wondering how I would edit it to use my company's standard colors
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
I have a vector called colors:
colors
[1] "#101820" "#AF272F" "#EAAA00" "#D0D0CE"
And I tried to graph it with this:
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")
And got an unexpected error. Can someone assist?
Upvotes: 1
Views: 101
Reputation: 6175
There are at least two possibilities to do that:
Just add + 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
Alternatively, you can add a special column with the defined color to your dataframe:
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()
Upvotes: 2