Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change bar plot colour in geom_bar with ggplot2 in r

I have the following in order to bar plot the data frame.

c1 <- c(10, 20, 40) c2 <- c(3, 5, 7) c3 <- c(1, 1, 1) df <- data.frame(c1, c2, c3) ggplot(data=df, aes(x=c1+c2/2, y=c3)) +   geom_bar(stat="identity", width=c2) +   scale_fill_manual(values=c("#FF6666")) 

I end up having only grey bars: Grey bars for bar plot

I would like to change the color of the bar. I already tried different scale_fill_manual from http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/ but still have grey bars.

Thank you for your help.

like image 786
tuttifolies Avatar asked Aug 05 '16 11:08

tuttifolies


People also ask

How do I change the color of my bar graph in R?

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.

How do I change the color of a stacked barplot in R?

You can change the colors of the stacked bars with a predefined color palette, such as the ones provided by scale_fill_brewer . If you prefer choossing each of the colors you can use scale_fill_manual and pass the vector of colors to the values argument.


1 Answers

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) +  geom_bar(stat="identity", width=c2, fill = "#FF6666") 

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C") df = cbind(df, c4) ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +  geom_bar(stat="identity", width=c2) 

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +  geom_bar(stat="identity", width=c2) +  scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue")) 

enter image description here

like image 154
bVa Avatar answered Oct 25 '22 15:10

bVa