Home > OS >  Ordering the dots based on their size in ggplot2
Ordering the dots based on their size in ggplot2

Time:07-19

I have faced a similar problem as it already has been asked here and no proper answer has been shared yet. So basically the order of y-axis should change based on the size of the dots. Unfortunately the facet_grid is not helpful and changes the original dot plot. It would be great if you could help with this.

CodePudding user response:

To get the y-axis in the same order as the dot size, I did the following:

  • sort the data in ascending order of Count which determines dot size
  • add a column order equal to the row number
  • user order as the y-axis but use scale_y_continuous to take the labels from the GOs column

(This uses the sample code from the question you linked to.)


library("ggplot2")
# create fake data
set.seed(1024) # keep reproducibility
go <- paste0("GO", sample(1000:2000, 5))

Count <- sample(1:20, 10)
data <- data.frame("GOs" = rep(go, 2), 
                   "Condition" = rep(c("A", "B"), each = 5),
                   "GeneRatio" = 1 / sample(10, 10), 
                   "p.adjust" = 0.05 / sample(10, 10),
                   "Count" = Count)


# sort the data by Count (Count determines dot size)
data <- data[order(data$Count),]
   
# add a row number variable `order`
data <- cbind(data,order=1:nrow(data))

# plot: dot plot
ggplot(data = data, aes(x = GeneRatio, y = order, # use `order` as the y-axis
                        color = `p.adjust`, size = Count))   
  geom_point()  
  scale_color_gradient(low = "red", high = "blue")  
  theme_bw()   
  ylab("")  
  xlab("")   
  scale_y_continuous(breaks=1:nrow(data),labels=data$GOs)   # use scale_y_continuous to use GOs for labels
  ggtitle("GO enrichment analysis")

  • Related