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

前端 未结 2 816
星月不相逢
星月不相逢 2021-01-01 23:51

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?

Examp

相关标签:
2条回答
  • 2021-01-02 00:15

    It looks that you want to plot them in some form of order based on the 50% value of each box plot? Taking a different dataframe 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 plot this, we can see that the labels are messed up (A comes before A*).

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

    We could order this manually as shown above, or we could decide to plot the grades in order of number of students getting each grade. This can also be done manually, but it would be better if we could automate this:

    First we order the dataframe:

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

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

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

    Running the same graph command shown above gives you data plotted with an differently ordered x axis.

    0 讨论(0)
  • 2021-01-02 00:40

    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)
    
    0 讨论(0)
提交回复
热议问题