penguin
penguin

Reputation: 1377

How to change color of only one stack in ggplot stacked barplot?

I have a ggplot stacked barplot like below

enter image description here

I want to change the color combination of stacks only for dec , for example c("red", "green"). My desired output is

desired_plot

I tried

ggplot() +    
geom_bar(data = x1, aes(y = values, x = months, fill = variable), stat="identity") +   
scale_fill_manual(values = c("orange", "blue")) +       
geom_bar(data = x2, aes(y = values, x = months, fill = variable), stat="identity") +
scale_fill_manual(values = c("red", "green"))

It takes only the last scale_fill_manual values. If it was a regular barplot, changing fill in geom_bar works. I can't figure out how to do this for stacked plot without creating extra values for legend.

In my code, x1 contains values for jan to nov and x2 contains values for dec. Both are subsets of whole data.

Upvotes: 1

Views: 1719

Answers (1)

iod
iod

Reputation: 7592

It's hard to give the code without the dataset, but what you want to try to do is create a new type column (for the full data set) that will distinguish between the Dec column and the other ones, so you'll have four types: chickens, eggs, chickens-December, eggs-December. fill based on this new column, and you'll get new colours for the December bars.

You can then use

scale_fill_manual(breaks=c("chickens","eggs"),
                values=c("green", "orange", "red", "blue")) 

to only include those values you want in the legend (pardon my random colour choice - use better ones for your graph).

Upvotes: 2

Related Questions