2

enter image description hereI am trying to order the bars in descending order according to the frequency (y axis) of the blue area (1 in the legend).

Here is a dummy data and my attempt.

Thank you for you help!

library(ggplot2)

Region <- c('A','B','C', 'D', 'E')
Factor <- c(1, 0)
Freq <- c(0.6, 0.2, 0.5, 0.3, 0.5, 0.4, 0.8, 0.5, 0.7, 0.5)
Value <- c(100, 250, 30, 300, 120, 50, 400, 90, 150, 320)

d <- data.frame(Region, Factor, Freq, Value)

d$Factor <- factor(d$Factor)

ggplot(d, aes(x= reorder(Region, -Freq), y= Freq, fill = Factor)) +
geom_bar(stat = "identity") +
scale_fill_manual(values=c("green", "blue"))+
scale_y_continuous(labels = scales::percent) +
ylab("%") +
xlab(" ") +
theme(legend.title=element_blank())+
geom_text(aes(label = Value), position = position_stack(vjust = 0.5), color 
= "white", check_overlap = T, size = 3) +
coord_flip() +
guides(fill=guide_legend(reverse=T))

Update: The answer showed in the "duplicate" question does not work. The answer showed in this post Order Bars in ggplot2 bar graph seems to do not work.

Julia
  • 35
  • 1
  • 7
  • Use `reorder` to order the levels of your factor [as in this answer](https://stackoverflow.com/a/9231857/903061). – Gregor Thomas Dec 03 '17 at 02:38
  • It doesn't work. Thanks – Julia Dec 03 '17 at 07:34
  • @Julia why it doesn't work? What have you done and what error message did you get? – pogibas Dec 03 '17 at 07:44
  • @Julia please update the question – pogibas Dec 03 '17 at 08:05
  • ggplot(d, aes(x= reorder(Region, -Freq, function(x) - length(x)), y= Freq, fill = Factor)) + geom_bar(stat = "identity") + scale_y_continuous(labels = scales::percent) + scale_fill_manual(values=c("green", "blue"))+ ylab("%") + xlab(" ") + theme(legend.title=element_blank())+ geom_text(aes(label = Value), position = position_stack(vjust = 0.5), color = "white", check_overlap = T, size = 3) + coord_flip() + guides(fill=guide_legend(reverse=T)) -- It does not change the order of the bars, no error – Julia Dec 03 '17 at 08:46
  • Well, you do have to reorder by the values that determine the ordering. You want to reorder by the `Freq` column when `Factor` is `'1'`, so `d$freq_1 = with(d, ifelse(Factor == '1', Freq, NA))`, then `d$Region = reorder(d$Region, d$freq_1, FUN = mean, na.rm = T)`, and your plot will work fine. – Gregor Thomas Dec 03 '17 at 22:22
  • Alternatively,along the lines of the last part of [Gavin's answer at the dupe](https://stackoverflow.com/a/5210833/903061), you could just pull out the levels in the right order and refactor: `s = d[d$Factor == '1', ]`, then `levs = s$Region[order(s$blue_freq)]`, and `d$Region = factor(d$Region, levels = levs)`. – Gregor Thomas Dec 03 '17 at 22:30
  • @Gregor2 That worked. Thanks! – Julia Dec 06 '17 at 01:26

0 Answers0