Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to color-code the positive and negative bars in barplot using ggplot

I have the following data:

df
    rowname   repo
1   revrepo  0.888
2  bankrate  0.402
3       CRR  0.250
4  Callrate  0.723
5       WPI  0.049
6       GDP -0.318
7       FED  0.110
8     width  0.209
9       nse  0.059
10      usd  0.185

I am plotting the barplot as shown below:

df %>% mutate(rowname = factor(rowname, levels = rowname[order(repo)])) %>%
ggplot(aes(x = rowname, y = repo)) +
geom_bar(stat = "identity") +
ylab("Correlation with repo") +
xlab("Independent Variable")

I get the following plot: ggplot bar plot

I would like to color the negative bars as red and all positive bars as grey.

like image 233
Nishant Avatar asked Jan 26 '18 14:01

Nishant


People also ask

How do you separate colors for positive and negative bars in a column bar chart?

1. If you have Excel 2013, choose the Format Data Series from the right click menu to open the Format Data Series pane, and then click Fill & Line icon, and check Invert if negative option, then check Solid fill and specify the colors for the positive and negative data bar as you want beside Color section.

How do I color a specific bar 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 barplot?

You can change the color of bars in a barplot using color argument. RGB is a way of making colors. You have to to provide an amount of red, green, blue, and the transparency value to the color argument and it returns a color.

Which of the following is the attribute used to change the color of bars in a bar chart?

The color attribute is used to set the color of the bars(maroon in this case).


1 Answers

Writing Andrey Kolyadin comment as a solution to make it stop it appearing as a question unanswered:

geom_bar(aes(fill = repo < 0), stat = "identity") + scale_fill_manual(guide = FALSE, breaks = c(TRUE, FALSE), values=c("gray", "red"))
like image 159
cdutra Avatar answered Oct 22 '22 09:10

cdutra