Reputation: 1095
I am trying to create 3 barplots in one plot using ggplot2
. The 3 barplots share the same x axis values and thats how I want to group it, rather than putting the entire plots side by side like this:
Since the dataframe I am using is fairly large, I have put an idealised one below:
> d1rm.null
Threat1_Cat Threat1 Threat2_Cat Threat2 Threat3_Cat Threat3
1 1 1.2 5 5.2 7 7.2
2 7 7.2 4 4.1 2 2.1
3 4 4.3 7 7.2 1 1.1
4 5 5.1 7 7.1 1 1.1
5 4 4.2 2 2.1 3 3.0
The scripts I have used to create one is below:
ggplot(data = d1rm.null, aes(x = Threat1_Cat, colour = Threat1)) +
geom_bar() +
labs(x = "Higher Threat Category", y="Frequency") +
ggtitle("Threat 1 Distribution Before Any Exclusions") +
guides(colour=guide_legend(title="Higher Resolution Threat Category"))
Which has the output:
It's something similar to this that I am aiming the plot to look like, but with all 3 threats present.
Thank you!
Upvotes: 0
Views: 129
Reputation: 2436
I tried to reshape the data, but I couldn't find something to do it automatically, so I did it "by hand". There must be a better solution. Anyway, here is my code
T1 <- d1rm.null %>%
select(1:2) %>%
gather(Threat, Value, Threat1) %>%
rename(Cat = Threat1_Cat)
T2 <- d1rm.null %>%
select(3:4) %>%
gather(Threat, Value, Threat2) %>%
rename(Cat = Threat2_Cat)
T3 <- d1rm.null %>%
select(5:6) %>%
gather(Threat, Value, Threat3) %>%
rename(Cat = Threat3_Cat)
Total <- bind_rows(T1, T2, T3)
Total
# A tibble: 15 × 3
# Cat Threat Value
# <dbl> <chr> <dbl>
# 1 1 Threat1 1.2
# 2 7 Threat1 7.2
# 3 4 Threat1 4.3
# 4 5 Threat1 5.1
# 5 4 Threat1 4.2
# 6 5 Threat2 5.2
# 7 4 Threat2 4.1
# 8 7 Threat2 7.2
# 9 7 Threat2 7.1
# 10 2 Threat2 2.1
# 11 7 Threat3 7.2
# 12 2 Threat3 2.1
# 13 1 Threat3 1.1
# 14 1 Threat3 1.1
# 15 3 Threat3 3.0
And then the graph, if I understand what you want.
ggplot(data = Total, aes(x = Cat, fill = Threat)) +
geom_bar(position = "dodge")
Upvotes: 2