Reputation: 113
I have a dataframe which contains the minimum values of two separate months for 15 different banks.
I want bar chart that compares the minimum values for each bank. I was hoping to achieve two bars per bank, since there are two minimum values, with each bar having the same color BUT each bank having a different color.
That way if bank1 identifies itself with blue the bars would be blue and if bank identifies with green the bars would be both green.
I tried the following code and this was the result.
library(ggplot2)
bank <- paste0("bank", c(1:15))
month1 <- c(-0.0750,-0.0350,-0.0250,0.0025,-0.0325,-0.0175,-0.0575,0.0025,-0.0775,-0.0050,-0.0275,-0.0550,-0.3700,-0.0475,-0.0100)
month2 <- c(-0.0775,0.0100,0.0075,-0.0225,0.0075,-0.0075,-0.0125,-0.0825,-0.0150,0.0050,-0.0025,-0.0750,-0.0050,-0.0750,0.0025)
values <- data.frame(bank, month1, month2)
values_gather <- gather(data = values, key = "month", value = "value", -1)
ggplot(values_gather, aes( x = bank, y = value, fill = bank )) +
geom_bar(stat = "identity", position = "dodge") +
theme_bw() +
theme(axis.text.x = element_text(angle = 60, hjust = 1))
Then I tried this, which was more less what I wanted but without those undesirable color surrounding the bars.
ggplot(values_gather, aes( x = bank, y = value, fill = bank, color = month)) +
geom_bar(stat = "identity", position = "dodge") +
theme_bw() +
theme(axis.text.x = element_text(angle = 60, hjust = 1))
So how do I manage to do a bar chart has one bar per minimum value, with both bars being the same color, and each bank having a different color?
Upvotes: 0
Views: 406
Reputation: 4520
Something like this?
[Edit] With spaces between bars.
values_gather %>%
ggplot(aes( x = bank, y = value, fill = bank, group = month )) +
geom_bar(stat = "identity",
position = position_dodge(width = 1)) +
theme_bw() +
theme(axis.text.x = element_text(angle = 60, hjust = 1), legend.position = "null")
P.S. You can do it, but I wonder is this graph readable? Does it bring additional information, when you plot two bars together? Maybe it is better to show some variability of the data by geom_errorbar
or even better - by geom_boxplot
?
Upvotes: 1
Reputation: 1868
Utilize "group" in the ggplot aesthetics.
ggplot(values_gather, aes(x = bank, y = value, fill = bank, group = month)) +
geom_bar(stat = "identity", position = "dodge") +
theme_bw() +
theme(axis.text.x = element_text(angle = 60, hjust = 1))
Upvotes: 0