Using plot
in R causes the factors on the x-axis to be alphabetically ordered.
How can I specify the order of the factors on the x-axis?
Example:
y <- 1:9
x <- c(rep("B", 3), rep("A", 3), rep("C", 3))
plot(y ~ as.factor(x))
This results in:
How can I get this to plot as "B", "A", "C"?
To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.
The easiest way to change the Y-axis title in base R plot is by using the ylab argument where we can simply type in the title. But the use of ylab does not help us to make changes in the axis title hence it is better to use mtext function, using which we can change the font size, position etc.
You just need to specify the levels of your factor in the order you want. So here I create a new variable x1
x1 = factor(x, levels=c("B", "C", "A"))
where
R> x1
[1] B B B A A A C C C
Levels: B C A
The plot
function now works as expected.
plot(y ~ x1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With