This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Reorder GO terms using R

Hello,

I plotted my GO data using this code:

ggplot(result_ego_filtered, aes(Count, Description, fill = ONTOLOGY)) +
  geom_bar(stat = "identity") +
  theme(legend.position = "bottom", axis.title.y = element_blank()) +
  geom_text(
    aes(label = paste(Count)),
    color = "black",
    size = 4,
    hjust = 0.1,
    position = position_dodge(0.9)
  )

And, I've got this plot:

enter image description here

How could I reorder ontology? I would like to show BP together followed by MF, and CC.

enrichment-analysis go

1 answer

To order things in ggplot2, you use factors and specify factor levels as the order. The key thing in your example is that you actually want to order your pathways: your y variable (Description), based on your database: your fill variable (ONTOLOGY).

A solution could be to:

  1. specify the database (ONTOLOGY) variable as a factor where the levels are the desired order (you could use forcats for this as Mark suggests)
  2. arrange your input data by this database factor with dplyr::arrange
  3. speficy the pathway (Description) variable as a factor where the levels are the final order in which they are

For example:

# Libraries
library(ggplot2)
library(dplyr)

# Example data
data <- data.frame(
  Description = c("A","E","B","I","O","J","K"),
  ONTOLOGY = c("BP","MF","BP","MF","CC","BP","CC"),
  Count = sample(1:10,7)
)

# Your initial plot
ggplot(data, aes(Count, Description, fill = ONTOLOGY)) + geom_bar(stat = "identity") +
  theme(legend.position = "bottom", axis.title.y = element_blank()) +
  geom_text( aes(label = paste(Count)), color = "black", size = 4, hjust = 0.1, position = position_dodge(0.9) )

# Define the order for the ontology types (BP, MF, CC)
data$ONTOLOGY <- factor(data$ONTOLOGY, levels = rev(c("BP","MF","CC")))

# Arrange the dataframe by the ontology types
data <- dplyr::arrange(data, ONTOLOGY)

# Set the final factor order for the pathways
data$Description <- factor(data$Description, levels = data$Description)

# Final ordered plot
ggplot(data, aes(Count, Description, fill = ONTOLOGY)) + geom_bar(stat = "identity") +
  theme(legend.position = "bottom", axis.title.y = element_blank()) +
  geom_text( aes(label = paste(Count)), color = "black", size = 4, hjust = 0.1, position = position_dodge(0.9) )

Thank you so much. It worked perfectly.

Log in to answer this question.