0

Im following the example given in this post for creating a grouped and stacked bar-chart: How to produce stacked bars within grouped barchart in R

From that post:

library(reshape2)
library(dplyr)
library(ggplot2)

test  <- data.frame(person=c("A", "B", "C", "D", "E"), 
                value1=c(100,150,120,80,150),     
                value2=c(25,30,45,30,30) , 
                value3=c(100,120,150,150,200)) 


melted <- melt(test, "person")

melted$cat <- ''
melted[melted$variable == 'value1',]$cat <- "first"
melted[melted$variable != 'value1',]$cat <- "second"


ggplot(melted, aes(x = cat, y = value, fill = variable)) + 
 geom_bar(stat = 'identity', position = 'stack') + 
 facet_grid(~ person)

As it is above, the plot orders value2 on top of value3.

What I am trying to do is change the order of the stacked portion,ie; I'd like to place value3 on top of value2.

Ive tried manually changing the order of the variable:

melted2 <- melted %>% 
  arrange(desc(variable))

ggplot(melted2, aes(x = cat, y = value, fill = variable)) + 
 geom_bar(stat = 'identity', position = 'stack') + 
 facet_grid(~ person)

But the plot output looks identical to the first one. Essentially, the reordering of the input data does not accomplish the task.

Thank you in advance!

Community
  • 1
  • 1
tomathon
  • 834
  • 17
  • 32
  • Possible duplicate of [How to control ordering of stacked bar chart using identity on ggplot2](http://stackoverflow.com/questions/32345923/how-to-control-ordering-of-stacked-bar-chart-using-identity-on-ggplot2) or [this](http://stackoverflow.com/questions/8186436/order-stacked-bar-graph-in-ggplot) or [that](http://stackoverflow.com/questions/7150453/order-categorical-data-in-a-stacked-bar-plot-with-ggplot2) – Roman May 02 '17 at 15:30
  • Read my post. I tried reordering as is shown in that post. – tomathon May 02 '17 at 15:31
  • There is no indication that you've reordered the levels - just the values. You need to explicitly order factor levels. Try `?factor` or `?reorder`. – Roman Luštrik May 03 '17 at 11:45

1 Answers1

1

This should work though it isn't clear to me exactly what order you'd like these in. But you can use levels to accomplish this:

melted$variable <- factor(melted$variable, levels = c("value1","value3","value2"))

ggplot(melted, aes(x = cat, y = value, fill = variable)) + 
 geom_bar(stat = 'identity', position = 'stack') + 
 facet_grid(~ person)

This approach that you use before only arranges the values in order of their value.

melted2 <- melted %>% 
  arrange(desc(variable))

Works better for continuous vectors. You actually needs to change the levels of the factor. You can check the levels using this:

levels(melted$variable)

[1] "value1" "value3" "value2"

melted$variable was already a factor but you just needed to override the default levels to what you wanted.

boshek
  • 4,100
  • 1
  • 31
  • 55