How to change the order of the x axis in a graph in R?

Using plot in R causes the x-axis factors to be sorted alphabetically.

How can I indicate the order of 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 leads to:

enter image description here

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

+7
source share
2 answers

You just need to indicate your factor levels 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] BBBAAACCC Levels: BCA 

Now the plot function works as expected.

 plot(y ~ x1) 
+9
source

Looks like you want to build them in some order based on 50% of the cost of each square? Let's take another data file as an example:

 temp <- structure(list( Grade = c("U","G", "F", "E", "D", "C", "B", "A", "A*"), n = c(20L, 13L, 4L, 13L, 36L, 94L, 28L, 50L, 27L)), .Names = c("Grade", "n"), class = c("tbl_df", "data.frame"), row.names = c(NA, -9L)) 

If we build this, we will see that the labels are confused (A comes before A *).

 library(ggplot2) ggplot(temp) + geom_bar(stat="identity", aes(x=Grade, y=n)) 

enter image description here

We could order it manually, as shown above, or we could decide to make estimates in order of the number of students receiving each class. It can also be done manually, but it would be better if we could automate this:

First we order a dataframe:

 library(dplyr) temp <- temp %>% arrange(n) 

Then we change the levels inside the Grade column to represent the data order.

 temp$Grade <- as.vector(temp$Grade) #get rid of factors temp$Grade = factor(temp$Grade,temp$Grade) #add ordered factors back 

Running the same chart command shown above gives you data plotted using another ordered x axis.

enter image description here

+2
source

All Articles