Reputation: 770
I have example data below:
> eg_data <- data.frame(period = c("1&2", "1&2","1", "1", "2","2"), size = c("big", "small", "big", "small","big", "small"), trip=c(1000, 250, 600, 100, 400, 150))
I want to make a stacked bar chart, where I have both periods as the first bar, period one as second, and period two as third. This is specified in the data as they are entered, but when I run the ggplot
bar command, R
decides that period one is a better candidate for first position.
ggplot() +
geom_bar(data = eg_data, aes(y = trip, x = period, fill = size),
stat = "identity",position = 'stack')
First, why does R
feel the need to display data in a manner other than how I fed it in, and second, how do I correct this IE specify which groupings I want and in what order.
All help is appreciated, thank you.
Upvotes: 2
Views: 138
Reputation: 887901
We can create the column as a factor
with levels
specified as the unique
values of that column. With that, the values are not sorted and would be in the same order as in the order of sequence of occurrence of the first unique
value of 'period'
library(tidyverse)
eg_data %>%
mutate(period = factor(period, levels = unique(period))) %>%
ggplot() +
geom_bar(aes(y = trip, x = period, fill = size),
stat="identity",position='stack')
EDIT - solution with baseR would be as follows -
eg_data$period <- factor(eg_data$period, levels = c("1 & 2", "1", "2"))
Upvotes: 2