r - Rank Stacked Bar Chart by Sum of Subset of Fill Variable -


sample data:

set.seed(145)  df <- data.frame(age=sample(c(1:10),20,replace=true),                  rank=sample(c("extremely","very","slightly","not @ all"),                              20,replace=true),                  percent=(runif(10,0,.01)))  df.plot <- ggplot(df,aes(x=age,y=percent,fill=rank))+            geom_bar(stat="identity")+            coord_flip() df.plot 

within ggplot, how can reorder x=age, sum of ranks "extremely" , "very" only?

i tried using below, without success.

df.plot <- ggplot(df,aes(x=reorder(age,rank=="extremely",sum),y=percent,fill=rank))+               geom_bar(stat="identity")+               coord_flip() df.plot 

couple of notes:

  1. the way simulating data not rule out possibility ages, categories not represented (which fine), ages, categories duplicated. assuming not true real data, have let be. note simulation logic not produce percentages add up, although category names indicate should.
  2. the way create ordering of age based on desired logic, , pass order factor call. decouples ordering logic , allows arbitrary ordering logic.

here think looking for:

library(ggplot2) library(dplyr) library(scales)  set.seed(145)  # simulate data df_foo = data.frame(age=sample(c(1:10),20,replace=true),                  rank=sample(c("extremely","very","slightly","not @ all"),                              20,replace=true),                  percent=(runif(10,0,.01)))  # ordering interested in age_order = df_foo %>%    filter(rank %in% c("extremely", "very")) %>%    group_by(age) %>%    summarize(sumrank = sum(percent)) %>%    arrange(desc(sumrank)) %>%    `[[`("age")  # in cases ages not appear in order because  #   ordering logic not span categories age_order = c(age_order, setdiff(unique(df_foo$age), age_order))  # make age factor sorted ordering above   ggplot(df_foo, aes(x = factor(age, levels = age_order), y = percent, fill = rank))+   geom_bar(stat = "identity") +   coord_flip() +    theme_bw() +    scale_y_continuous(labels = percent) 

which code produces:

enter image description here


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

http - Safari render HTML as received -