0

This is my data:

Guild           Treatment   value
Ins                Low      59.1
InsAerGleEdge      Low      19.7
InsAerOpen         Low      6.7
InsAerGleEdgeClut  Low      4.4
Frug               Low      3.7
InsAerGleClut      Low      3.5
InsAerEdge         Low      2.3
InsGleClut         Low      0.6
InsAerOpen        Medium    40.1
Frug              Medium    24.3
Ins               Medium    24.3
InsAerGleEdge     Medium    5.3
InsAerEdge        Medium    2.6
InsAerGleEdgeClut Medium    2.6
InsGleClut        Medium    0.7
InsAerGleClut     Medium    0
Frug               High     27.8
InsAerEdge         High     18.6
InsAerGleClut      High     16.7
InsAerGleEdge      High     15.5
Ins                High     11.7
InsAerOpen         High     5.8
InsAerGleEdgeClut  High     3.7
InsGleClut         High     0.3

I would like to have a barplot using ggplot keeping the sequence of the guilds for each treatment. For example in:

  1. Treatment Low the sequence of guilds is Ins, InsAerGleEdge, InsAerOpen etc..based on the highest value.
  2. Treatment "Medium" is InsAerOpen, Frug, Ins etc.

My problem is when I plot it in all the treatments it starts with the same guild.

I have tried "reorder", "factor" but it doesn't change for each treatment individually.

Treatment<-as.character(df$Treatment)
df$Treatment<-factor(df$Treatment, levels = c("Low", "Medium","High"))

m<-ggplot(df, aes(fill=Guild, y=value, x=Treatment)) + 
  geom_bar(position=position_dodge(), stat="identity",color="grey60")+
  scale_fill_manual(values=c("grey80", "grey30","grey60","grey40","grey50","grey70","grey90","grey20"))
Sandy
  • 1,100
  • 10
  • 18
PenF
  • 1
  • 1
    Related: https://stackoverflow.com/questions/7064146/order-bars-within-each-factor-using-ggplot2 – Jon Spring Oct 28 '19 at 20:36
  • Thank you for the suggestion but on that example, I couldn't replicate it thus I didn't understand how they did it – PenF Oct 30 '19 at 17:18

1 Answers1

0

Here's an approach using facets, assigning a global ordering and then adjusting the scale of each facet (scales = "free_x") to only show the values applicable to that facet.

df$order = forcats::fct_inorder(paste(df$Treatment, df$Guild))
ggplot(df, aes(fill=Guild, y=value, x=order)) + 
  geom_bar(position=position_dodge(), stat="identity",color="grey60")+
  scale_fill_manual(values=c("grey80", "grey30","grey60","grey40",
                             "grey50","grey70","grey90","grey20")) +
  # scale_x_discrete(labels = NULL) +    # to leave out x labels
  scale_x_discrete(labels = df$Guild, name = "") +
  facet_wrap(~Treatment, scales = "free_x", switch = "x") +  
  # The "switch" part above moves Treatment to the bottom
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.3))

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53