Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change color of only one bar in ggplot

Tags:

I want to color only one bar in ggplot. This is my data frame:

area <- c("Północ", "Południe", "Wschód", "Zachód") sale <- c(16.5, 13.5, 14, 13) df.sale <- data.frame(area, sale) colnames(df.sale) <- c("Obszar sprzedaży", "Liczba sprzedanych produktów (w tys.)") 

And code for plotting:

plot.sale.bad <- ggplot(data=df.sale, aes(x=area, y=sale, fill=area)) +   geom_bar(stat="identity") +   scale_fill_manual(values=c("black", "red", "black", "black")) +   xlab(colnames(df.sale)[1]) +   ylab(colnames(df.sale)[2]) +   ggtitle("Porównanie sprzedaży")  

I would like to have only one bar colored and 3 others to have default color (darkgrey, not black, it looks bad for me). How can I change color of only on bar or how to get name of the default color of bars to put them instead of black?

like image 342
jjankowiak Avatar asked Apr 06 '14 12:04

jjankowiak


People also ask

How do I color individual bars in R?

R barplot() – Set Colors for Bars in Bar Plot To set colors for bars in Bar Plot drawn using barplot() function, pass the required color value(s) for col parameter in the function call. col parameter can accept a single value for color, or a vector of color values to set color(s) for bars in the bar plot.

What does stat identity mean in Ggplot?

In the above example, we've overridden the default count value by specifying stat = "identity" . This indicates that R should use the y-value given in the ggplot() function. Notice that bar graphs use the fill argument instead of the color argument to color-code each cut category.


1 Answers

If you like having everything in the ggplot call, you can use an ifelse statement within factor() for the fill as shown below.

This also separates the legend into two categories (i.e. highlighted and not highlighted) so that you aren't repeating the values shown on the x axis. This also provides another illustrative dimension to the plot in the legend.

plot.sale.bad2 <- ggplot(data=df.sale,                          aes(x=area,                              y=sale,                              fill=factor(ifelse(area=="Południe","Highlighted","Normal")))) +   geom_bar(stat="identity") +   scale_fill_manual(name = "area", values=c("red","grey50")) +   xlab(colnames(df.sale)[1]) +   ylab(colnames(df.sale)[2]) +   ggtitle("Porównanie sprzedaży")   plot.sale.bad2 

Plot with legend

If the legend isn't needed you can add show.legend = FALSE to the geom_bar() call to produce the following:

Plot without legend

like image 168
Russ Thomas Avatar answered Oct 29 '22 02:10

Russ Thomas