brad
brad

Reputation: 9773

How do I order components of bars within bar plot in R/ggplot2

Similar questions to this have been asked, but I have not been able to apply the suggested solutions successfully.

I have created a plot like so;

> elective_ga <- c(68, 51, 29, 10, 5)
> elective_epidural <- c(29, 42, 19, 3, 1)
> elective_cse <- c(0, 0, 0, 20, 7)
> elective_spinal <- c(3, 7, 52, 67, 87)
> years <- c('1982', '1987', '1992', '1997', '2002')
> values <- c(elective_ga, elective_epidural, elective_cse, elective_spinal)
> elective_technique <- data.frame(years, values)
> p <- ggplot(elective_technique, aes(years, values))
> p +geom_bar(stat='identity', aes(fill=c(rep('GA', 5), rep('Epidural', 5), rep('CSE', 5), rep('Spinal', 5)))) +labs(x='Year', y='Percent', fill='Type')

which produces the following chart;

enter image description here

I was expecting the bars to be stacked in the order (from top to bottom) GA, Epidural, CSE, Spinal. I would have thought the way I constructed the data frame that they should be ordered in this way but obviously I have not. Can anyone explain why the bars are ordered the way they are, and how to get them the way I want?

Upvotes: 1

Views: 193

Answers (2)

Jack Brookes
Jack Brookes

Reputation: 3830

One way is to reorder the levels of the factor.

library(ggplot2)

elective_ga <- c(68, 51, 29, 10, 5)
elective_epidural <- c(29, 42, 19, 3, 1)
elective_cse <- c(0, 0, 0, 20, 7)
elective_spinal <- c(3, 7, 52, 67, 87)
years <- c('1982', '1987', '1992', '1997', '2002')
values <- c(elective_ga, elective_epidural, elective_cse, elective_spinal)
type = c(rep('GA', 5), rep('Epidural', 5), rep('CSE', 5), rep('Spinal', 5))
elective_technique <- data.frame(years, values, type)

# reorder levels in factor
elective_technique$type <- factor(elective_technique$type,
                                  levels = c("GA", "Epidural", "CSE", "Spinal"))

p <- ggplot(elective_technique, aes(years, values))
p +
  geom_bar(stat='identity', aes(fill = type)) +
  labs(x = 'Year', y = 'Percent', fill = 'Type')

enter image description here

The forcats package may provide a cleaner solution.

Upvotes: 1

Antonios
Antonios

Reputation: 1937

How about this?

elective_ga <- c(68, 51, 29, 10, 5)
elective_epidural <- c(29, 42, 19, 3, 1)
elective_cse <- c(0, 0, 0, 20, 7)
elective_spinal <- c(3, 7, 52, 67, 87)
years <- c('1982', '1987', '1992', '1997', '2002')
values <- c(elective_ga, elective_epidural, elective_cse, elective_spinal)
Type=c(rep('GA', 5), rep('Epidural', 5), rep('CSE', 5), rep('Spinal', 5))
elective_technique <- data.frame(years, values,Type)
elective_technique$Type=factor(elective_technique$Type,levels=c("GA","Epidural","CSE","Spinal"))
p <- ggplot(elective_technique, aes(years, values,fill=Type))+geom_bar(stat='identity') +
  labs(x='Year', y='Percent', fill='Type')

enter image description here

Upvotes: 2

Related Questions