banner



How To Change The Order Of Factors In R

Reordering groups in a ggplot2 chart tin can be a struggle. This is due to the fact that ggplot2 takes into business relationship the order of the factor levels, not the order y'all observe in your information frame. You tin can sort your input information frame with sort() or arrange(), it will never have any impact on your ggplot2 output.

This post explains how to reorder the level of your factor through several examples. Examples are based on two dummy datasets:

                                          # Library                                            library(ggplot2)                              library(dplyr)                                            # Dataset 1: one value per group                            data                <-                data.frame(                              proper name=                c("north","south","south-east","north-west","south-westward","northward-east","westward","east"),                              val=                sample(seq(1,10),                eight                )              )                                                          # Dataset 2: several values per group (natively provided in R)                                            # mpg                                    

Method 1: the forcats library


The forcats library is a library from the tidyverse especially fabricated to handle factors in R. It provides a suite of useful tools that solve mutual issues with factors. The fct_reorder() role allows to reorder the factor (data$proper noun for instance) post-obit the value of another column (data$val hither).

                                                # load the library                                                  library(forcats)                                                  # Reorder post-obit the value of another column:                                information                  %>%                                                  mutate(name =                  fct_reorder(name, val))                  %>%                                                  ggplot(                  aes(x=name,                  y=val))                  +                                                  geom_bar(stat=                  "identity",                  fill up=                  "#f68060",                  alpha=.six,                  width=.iv)                  +                                                  coord_flip()                  +                                                  xlab("")                  +                                                  theme_bw()                                                                  # Reverse side                                data                  %>%                                                  mutate(name =                  fct_reorder(proper name,                  desc(val)))                  %>%                                                  ggplot(                  aes(ten=name,                  y=val))                  +                                                  geom_bar(stat=                  "identity",                  make full=                  "#f68060",                  alpha=.vi,                  width=.four)                  +                                                  coord_flip()                  +                                                  xlab("")                  +                                                  theme_bw()                          

If y'all have several values per level of your factor, yous can specify which function to apply to determine the social club. The default is to use the median, but you tin can use the number of data points per group to brand the nomenclature:

                                                # Using median                                mpg                  %>%                                                  mutate(class =                  fct_reorder(class, hwy,                  .fun=                  'median'))                  %>%                                                  ggplot(                  aes(x=                  reorder(class, hwy),                  y=hwy,                  fill=class))                  +                                                  geom_boxplot()                  +                                                  xlab("course")                  +                                                  theme(legend.position=                  "none")                  +                                                  xlab("")                                                                  # Using number of ascertainment per group                                mpg                  %>%                                                  mutate(form =                  fct_reorder(grade, hwy,                  .fun=                  'length'                  ))                  %>%                                                  ggplot(                  aes(x=grade,                  y=hwy,                  make full=course))                  +                                                  geom_boxplot()                  +                                                  xlab("class")                  +                                                  theme(legend.position=                  "none")                  +                                                  xlab("")                  +                                                  xlab("")                          

The last common performance is to provide a specific order to your levels, you lot tin do and then using the fct_relevel() function every bit follow:

                                                            # Reorder post-obit a precise order                                        p                      <-                      data                      %>%                                                              mutate(name =                      fct_relevel(name,                                                              "due north",                      "n-due east",                      "east",                                                              "south-e",                      "s",                      "s-west",                                                              "due west",                      "n-west"))                      %>%                                                              ggplot(                      aes(x=name,                      y=val))                      +                                                              geom_bar(stat=                      "identity")                      +                                                              xlab("")                                          #p                                                      

Method 2: using dplyr merely


The mutate() function of dplyr allows to create a new variable or modify an existing one. It is possible to use it to recreate a factor with a specific order. Here are 2 examples:

  • The kickoff apply adjust() to sort your information frame, and reorder the cistron following this desired club.
  • The 2d specifies a custom society for the cistron giving the levels one by 1.
                              information                  %>%                                                  arrange(val)                  %>%                  # First sort by val. This sort the dataframe but NOT the gene levels                                                  mutate(name=                  factor(proper noun,                  levels=name))                  %>%                  # This pull a fast one on update the gene levels                                                  ggplot(                  aes(x=name,                  y=val))                  +                                                  geom_segment(                  aes(xend=name,                  yend=                  0))                  +                                                  geom_point(                  size=                  4,                  color=                  "orange")                  +                                                  coord_flip()                  +                                                  theme_bw()                  +                                                  xlab("")                                                data                  %>%                                                  conform(val)                  %>%                                                  mutate(proper noun =                  gene(name,                  levels=                  c("due north",                  "north-east",                  "east",                  "s-eastward",                  "south",                  "s-w",                  "westward",                  "north-w")))                  %>%                                                  ggplot(                  aes(10=proper noun,                  y=val))                  +                                                  geom_segment(                  aes(xend=name,                  yend=                  0))                  +                                                  geom_point(                  size=                  4,                  color=                  "orange")                  +                                                  theme_bw()                  +                                                  xlab("")                          

Method 3: the reorder() function of base R


In example your an unconditional user of the practiced old R, here is how to control the club using the reorder() part inside a with() call:

                                                            # reorder is close to order, simply is made to alter the society of the factor levels.                                        mpg$class                      =                      with(mpg,                      reorder(grade, hwy, median))                                        p                      <-                      mpg                      %>%                                                              ggplot(                      aes(x=class,                      y=hwy,                      fill=class))                      +                                                              geom_violin()                      +                                                              xlab("class")                      +                                                              theme(legend.position=                      "none")                      +                                                              xlab("")                                          #p                                                      

Source: https://r-graph-gallery.com/267-reorder-a-variable-in-ggplot2.html

Posted by: quinnoloplath.blogspot.com

0 Response to "How To Change The Order Of Factors In R"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel