Closed jcberny closed 3 years ago
You could change the order of factor levels before fitting the model. This can either be done using the level
argument of the factor()
function or potentially using one of the functions in the forcats
package.
The problem is that when plotted it is arranged by alphabetic order.
In sjPlot the plot_model function has an argument called sort.est that supposedly does this, although I have not been able to make it work.
This plot does not look like an afex_plot
object and you also mention sjPlot
so it is unclear how this issue is related to afex
.
Anyway, for afex_plot
the orderign on the x-axis is based on the order of factor levels in case the variable is a factor and alphabetic otherwise. The following example shows it. Note that treatment
is a factor in the first place with control
being the first level (as shown in the str
call).
library("afex")
data(obk.long, package = "afex")
str(obk.long)
#> 'data.frame': 240 obs. of 7 variables:
#> $ id : Factor w/ 16 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...
#> $ treatment: Factor w/ 3 levels "control","A",..: 1 1 1 1 1 1 1 1 1 1 ...
#> $ gender : Factor w/ 2 levels "F","M": 2 2 2 2 2 2 2 2 2 2 ...
#> $ age : num -4.75 -4.75 -4.75 -4.75 -4.75 -4.75 -4.75 -4.75 -4.75 -4.75 ...
#> $ phase : Factor w/ 3 levels "fup","post","pre": 3 3 3 3 3 2 2 2 2 2 ...
#> $ hour : Factor w/ 5 levels "1","2","3","4",..: 1 2 3 4 5 1 2 3 4 5 ...
#> $ value : num 1 2 4 2 1 3 2 5 3 2 ...
obk.long$treatment_char <- as.character(obk.long$treatment)
mfac <- aov_car(value ~ treatment + Error(id), data = obk.long)
#> Warning: More than one observation per cell, aggregating the data using mean
#> (i.e, fun_aggregate = mean)!
#> Contrasts set to contr.sum for the following variables: treatment
afex_plot(mfac, "treatment")
mchar <- aov_car(value ~ treatment_char + Error(id), data = obk.long)
#> Converting to factor: treatment_char
#> Warning: More than one observation per cell, aggregating the data using mean
#> (i.e, fun_aggregate = mean)!
#> Contrasts set to contr.sum for the following variables: treatment_char
afex_plot(mchar, "treatment_char")
Created on 2020-10-30 by the reprex package (v0.3.0)
To create a factor yourself use factor
and specify the order in levels
. For example:
obk.long$treat2 <- factor(obk.long$treatment_char,
levels = c("B", "control", "A"))
Hi, I have a model with many levels in x and I would like them to reorder them from high to low.
with factor_levels I would have to name each one of them, is there a better way to do this?