Re: Reordering a grouped bar plot by one of the variables

314 views
Skip to first unread message

Jaydeep Bhat

unread,
Feb 17, 2021, 6:57:39 PM2/17/21
to j0hnCathey, ggplot2
you can try reorder() function. Here is a simple fix in the code (based on your input code):

out of order plot:
  library(viridis) #optional
p <- ggplot(F1, aes(x=reorder(reg,-dat1079), y=dat1079, fill=gene)) + # you just need to reorder using minus
  geom_bar(position="dodge", stat="identity") +
  labs(x= "", y ="Number of samples") +
  theme(legend.title = element_blank()) 
  scale_color_viridis(discrete = TRUE, option = "D") +
  scale_fill_viridis(discrete = TRUE)  
p

Just tested with your example data and it worked. I could produce a bar plot in the descending order (L to R) like you asked.
Hope it helps!

On Tue, Feb 16, 2021 at 9:17 AM j0hnCathey <jtca...@gmail.com> wrote:
I've googled and can't find anything recent about reordering bars on a grouped bar plot. I know how to reorder an ungrouped bar plot. A page on stackoverflow is 4 years old, created the grouping using the melt function in reshape2 and i think there must be a better way now. I want to order the graph by descending order (L to R) of the largest level of the variable gene (OXA-48). The order of the regions doesn't matter.

Here's my data:
reg=c(rep('Northern', 3), rep('Central/Eastern', 3), rep('Western', 3), rep('Southern', 3))
gene=rep(c("OXA-48",'NDM', "OXA-48+NDM"), 4)
dat1079 <- c(21, 9, 4, 54, 19, 8, 72, 18, 14, 150, 56, 11)
F1 <- data.frame(reg, gene, dat1079)
F1

out of order plot:
library(viridis) #optional
ggplot(F1, aes(fill=gene, y=dat1079, x=reg)) + 
        geom_bar(position="dodge", stat="identity") +
        labs(x= "", y ="Number of samples") +
        theme(legend.title = element_blank()) +
        scale_color_viridis(discrete = TRUE, option = "D") +
        scale_fill_viridis(discrete = TRUE)  

thanks for help

--
--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility
 
To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+u...@googlegroups.com
More options: http://groups.google.com/group/ggplot2

---
You received this message because you are subscribed to the Google Groups "ggplot2" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ggplot2+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ggplot2/bed97c99-d9eb-4c1b-b230-0f2df84c0393n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages