0

Im trying to reorder a stacked geom_bar for each x without success. What I would like to achieve is a plot where the y-values are ordered from smallest to largest for each value of x. Something like this:

enter image description here

The problem however seems to be that ggplot threats y as discrete values instead of continuous and therefore I am not able to change breaks and labels of my y-axis. I have tried using scale_x_discrete without success.

library(tidyverse)

df <- data.frame(q= c(rep("2011", 3), rep("2012", 3)), 
                 typ = rep(c("A", "B", "C"), 2), 
                 val = c(7,2,1,2,3,4), stringsAsFactors = F) %>% as_tibble()

ggplot(df) + geom_col(mapping = aes(x = q, y = reorder(val, val), fill = typ)) 



ggplot(df) + geom_col(mapping = aes(x = q, y = reorder(val, val), fill = typ)) + scale_y_continuous()
    Error: Discrete value supplied to continuous scale

The following code does not change my breaks at all.

ggplot(df) + geom_col(mapping = aes(x = q, y = reorder(val, val), fill = typ)) + scale_y_discrete(breaks = 1:10)
Pierre
  • 671
  • 8
  • 25
  • You are correct! I I did not see that question before my post. I managed to solve my problem with your link – Pierre Sep 05 '19 at 09:55

1 Answers1

0

With help from @kath I managed to solve it

library(tidyverse)

df <- data.frame(q= c(rep("2011", 3), rep("2012", 3)), 
                 typ = rep(c("A", "B", "C"), 2), 
                 val = c(7,2,1,2,3,4), stringsAsFactors = F) %>% as_tibble()

bars <- map(unique(df$q)
            , ~geom_bar(stat = "identity", position = "stack"
                        , data = df %>% filter(q == .x)))

df %>% 
  ggplot(aes(x = q, y = val, fill = reorder(typ,val))) + 
  bars +
  guides(fill=guide_legend("ordering")) + 
  scale_y_continuous(breaks = 1:10, limits = c(0, 10))
Pierre
  • 671
  • 8
  • 25