I am trying to make a stacked bar chart with the following code described below.
library(ggplot2)
library(reshape2)
# Generate artificial data
set.seed(123)
deciles <- rep(1:10, 2)
variable <- rep(c("cars", "bicyclis"), each = 10)
value <- runif(20, min = 0, max = 100)
# Create data frame
df <- data.frame(deciles, variable, value)
df$variable <- factor(df$variable, levels = c("cars", "bicyclis"))
ggplot(df, aes(x = factor(deciles), y = value, fill = variable)) +
geom_bar(stat = "identity", position = "identity") +
scale_fill_manual(values = c("royalblue", "red"))
What I don’t like about this bar chart is that the ordering is not what I expected. Namely, the data for cars, which are shown in blue, I want to be displayed first, while the data for bicycles, which are shown in red, I want to be displayed second.
Can someone help me solve this problem so that the data for cars are shown first and then the data for bicycles is shown?
>Solution :
First of all, if you want a stacked bar chart use position="stack". Additionally, you can reverse the order of the stack using reverse=TRUE (or by reversing the order of the levels of your factor):
library(ggplot2)
ggplot(df, aes(x = factor(deciles), y = value, fill = variable)) +
geom_bar(stat = "identity", position = position_stack(reverse = TRUE)) +
scale_fill_manual(values = c("royalblue", "red"))

