ss0208535 ss0208535 - 4 months ago 14
R Question

Change the fill color of one of the dodged bar in ggplot

I want to change the order of the bar plot only for the last set, just to highlight it. I used

, but it didn't help much.

Here's my code:

x<-c(rep(c("Type1", "Type2"),4))
z<-data.frame(type = x, val=y, Time = time)

ggplot(data = z, aes(x=Time,y=val)) +
geom_bar(stat = "identity", position = "dodge", aes(fill=type))+
scale_fill_manual(values = c(rep(c("white", "gray51"),3),"white","red"))

Here's the output:

enter image description here

I want the graph to look like:
enter image description here

Is there any way I can do this? I would appreciate any help. I looked at change color of only one bar in ggplot but it doesn't seem to be about grouped data.


My general mantra is that ggplot is very good at plotting the data you give it. If you want it to plot something different, the easiest way is usually to modify your data.

z$type2 = as.character(z$type)
z$type2[z$type == "Type2" & z$Time == 2013] = "Type2 "

I added a sneaky extra space in "Type2 " for the row you want to highlight. It will be a distinct factor level and get its own color (and even be coerced into the a nice order using the alphabetical default). But it will appear the same in the legend label.

ggplot(data = z, aes(x=Time,y=val)) +
    geom_bar(stat = "identity", position = "dodge", aes(fill=type2))+
    scale_fill_manual(values = c("white", "gray50", "red"))

enter image description here

I thought that omitting the red from the legend would be difficult, but this answer showed me that all that is needed is to add breaks = c("Type1", "Type2") as an argument to scale_fill_manual.