KennyPeanuts KennyPeanuts - 1 year ago 123
R Question

How can I reorder the x axis in a plot in R?


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?


y <- 1:9
x <- c(rep("B", 3), rep("A", 3), rep("C", 3))
plot(y ~ as.factor(x))

This results in:

enter image description here

How can I get this to plot as "B", "A", "C"?

Answer Source

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"))


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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download