jorenwouters
jorenwouters

Reputation: 105

Set manual order of Bar chart using ggplot2

I have the following data:

# A tibble: 7 x 2
  Time        Number
  <chr>        <dbl>
1 0 hours          7
2 1-5 hours       20
3 6-10 hours       8
4 11-20 hours     13
5 21-40 hours      6
6 40+ hours        3
7 No idea          6

Now, I wanted to make a histogram of it, using the following code (tidyverse):

time_hist = time %>%
    ggplot(aes(x=Time, y=Number, fill=Time)) +
    geom_bar(width=1, stat="identity") +
    theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank()) +
    labs(fill="Time", x="", y="Number", title = "How much time does this problem cost you?") +
    scale_fill_discrete(breaks=c("0 hours", "1-5 hours", "6-10 hours", "11-20 hours", "21-40 hours", "40+ hours", "No idea"))
  plot(time_hist)

Which resulted in the following histogram:

enter image description here

However, I want that the bar for "6-10 hours" is the third bar instead of the 6th bar. How do I achieve this?

Upvotes: 1

Views: 274

Answers (1)

Andrew Barros
Andrew Barros

Reputation: 128

Try turning Time into a factor -- then the axis will be displayed by the ordering of the factor levels. If you use forcats::as_factor (instead of as.factor) the levels are created in the order they appear (Rather than lexicographically sorted)

library(tidyverse)

time <- tibble::tribble(
  ~ Time, ~ Number,
  "0 hours", 7,
  "1-5 hours",20,
  "6-10 hours",8,
  "11-20 hours",13,
  "21-40 hours",6,
  "40+ hours",3,
  "No idea", 6
)

time <- time %>% mutate(Time = as_factor(Time))

When I use the plotting code you show above I now get this figure: enter image description here

Upvotes: 2

Related Questions