Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Specific Ordering in Staked Bar Chart

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"))

enter image description here

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading