This is my chart and I am wanting to colour say 4 bars one colour another 4 a different colour and so on. If I can include a legend that would be great too.
How is it best to do this?
Thanks
This is my chart and I am wanting to colour say 4 bars one colour another 4 a different colour and so on. If I can include a legend that would be great too.
How is it best to do this?
Thanks
You can add a fill
in your aes
.
Data for the example:
df <- data.frame(SFC = c("z","f",
"q",
"h",
"g",
"n" ,
"o",
"w"),
share = sample(1:100, 8)) %>%
arrange(share)
SFC share
1 q 4
2 o 24
3 h 25
4 z 29
5 f 44
6 n 59
7 g 72
8 w 93
Code:
ordre <- df$SFC
ggplot(df,aes(x = SFC,
y = share,
fill = factor(rep(seq(1:2), each=4)))) +
geom_col() +
scale_x_discrete(limits = ordre) +
labs(fill = "Legend") +
scale_fill_discrete(labels = c("first","second"))
Output:
One option is to aggregate the data and assign a group that determines the coloring.
plot_data <- tibble::tribble(
~label, ~value, ~group,
"A", 1, "Group 1",
"B", 2, "Group 1",
"C", 3, "Group 2"
)
library(ggplot2)
ggplot(plot_data) +
aes(value, label, fill = group) +
geom_col() +
scale_fill_manual(values = c("steelblue", "darkred")) +
theme_minimal()