0

I have a dataframe (df) as follows

id count result
a 3 positive
b 4 negative

I have been able to create a bar graph with this

ggplot(df, aes(x=result, y=count, fill = id)) +
  geom_bar(stat = "identity") +
  labs(x = "Example", y = "Frequency", fill = "Group") + 
  scale_x_discrete(labels = c("Positive", "Negative"))

The resulting bar graph looks like this enter image description here

However, I want the Positive to be on the left and i want group a to be blue. How would the modified code look like if i had multiple results (e.g., positive, negative, unknown, small)?

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
Coldgrad
  • 59
  • 7
  • 2
    Just about every question on SO that includes the words "ggplot2" and "order", and usually "axis" or something closely related ... are resolved by the use of `factor`. The default action of ggplot2 is to order things by alphabetic ordering; to force it, do something like `df$result <- factor(df$result, levels=c("positive","negative"))`. – r2evans Feb 23 '23 at 17:51

1 Answers1

0

Character variables mapped to aesthetics (such as x, y, fill, color, etc) in ggplot are converted into factors, and are arranged in the order of the factor levels. Unless you pass a factor with the desired ordering of levels to the discrete scale, they will therefore be arranged alphabetically, since this is the default behaviour when factors are created.

So we simply do this to get the desired ordering:

ggplot(df, aes(factor(result, c('positive', 'negative')), count, 
               fill = factor(id, c('b', 'a')))) +
  geom_col() +
  labs(x = "Example", y = "Frequency", fill = "Group") + 
  scale_x_discrete(labels = c("Positive", "Negative")) +
  scale_fill_discrete(breaks = c('a', 'b'))

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • This works, but is there a way to also invert the colors? So a would be red and b would be blue. – Coldgrad Feb 23 '23 at 17:54
  • 1
    @Coldgrad yes, as explained above. Change the order of the `id` factor to `c('a', 'b')` (this is its default order anyway - I specifically changed it because your question asked for group "a" to be blue) – Allan Cameron Feb 23 '23 at 17:58