-1

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?

Thanksenter image description here

  • Does this answer your question? [Change bar plot colour in geom\_bar with ggplot2 in r](https://stackoverflow.com/questions/38788357/change-bar-plot-colour-in-geom-bar-with-ggplot2-in-r) – Martin Gal Jul 27 '21 at 08:46

2 Answers2

1

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:

Output

MonJeanJean
  • 2,876
  • 1
  • 4
  • 20
0

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()

enter image description here

Gregor de Cillia
  • 7,397
  • 1
  • 26
  • 43