0

I am attempting to create a grouped bar plot in R that is ordered in terms of the treatment level given. I have read elsewhere that assigning levels to the factors of treatment can allow you to reorder the bars within groups however I have just found that this causes R to change the colour assignments for the groups and not actually move them

The data I am using consists of:

  • 6 ID numbers as factors
  • 4 treatment levels (0,4,6,8) as factors
  • A weight measurement

enter image description here

As you can see in the graph produced, ggplot has ordered the groups in terms of their relative weight value, from smallest to largest (specifically for landraces 227 and 277, where treatment 6 is placed before treatment 8)

If I try re-ordering the factor levels, as I said the color just changes

EffectOfNa$Na.Treatment <- factor(EffectOfNa$Na.Treatment, levels = c(0,6,4,8)) (Random Order)

enter image description here

(Treatment 6 is still placed before treatment 8 for landraces 227 and 277)

Ideally I would like it so that regardless of the weight values, the order of the groups always goes from 8 to 0, rather than in just ascending weight value

Again I have read that a common solution is to simply apply levels to the factors of treatment and ggplot will stick to that, but it doesn't seem to be the case here.

Here is the relevant code I have used so far

WeightData$Landrace <- as.factor(WeightData$Landrace)
WeightData$Na.Treatment <- as.factor(WeightData$Na.Treatment)
WeightData$Na.Treatment <- factor(WeightData$Na.Treatment, levels=c(0,4,6,8)
ggplot(WeightData, aes(x=Landrace, y=Weight, fill=Na.Treatment)) +
    geom_col(position="dodge)

I am assuming there is a value I need to change that decides whether ggplot follows factor order or simply orders by y-value magnitude

Hopefully that makes sense, and any advice or help would really be appreciated

Ben Haynes
  • 23
  • 2
  • 1
    Hm. That's weird. Would you mind sharing a snippet of your data? See See [how to make a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) To post your data type `dput(NAME_OF_DATASET)` into the console and copy & paste the output starting with `structure(....` into your post. – stefan Aug 04 '21 at 18:10
  • 1
    Additionally. ggplot2 does not order by value except when you tell it to do so. One more point. After a closer look at your plot (expsecially the y axis) I would guess that your Weight Variable is a categorical variable too instead of a numeric which maybe one reason for your issue. Maybe you could check that too. – stefan Aug 04 '21 at 18:11
  • 1
    @stefan Thank you you've nailed it! Turns out because my weight data was being classed as categorical it wasn't sure which factor to order things by, changed it to numerical and now it's working fine! – Ben Haynes Aug 04 '21 at 18:24

0 Answers0