Search code examples
rsortingdot-plot

How can I rearrange the order of y-axis on cleveland dot plot?


I have a Table and I generated a Hallmark Cleveland plot to visualize the enrichment scores before and after applying my software. But how can I rearrange the order of my plot to look like this ? I was thinking to sum up scores of all statuses in each hallmark and plot the hallmarks in a descending order based on the sum of status scores. But I am not sure how to do it. T

The code is as follows

library(ggplot2)
ggplot(Table, aes(Table$`Enrichment Scores`, Table$Hallmarks)) + 
    geom_point(aes(color=Table$Status)) + 
    ggtitle("Hallmarks") + geom_line(aes(group = Table$Hallmarks)) + 
    geom_vline(xintercept = ES_cutoff, color = "blue", linetype = "dashed", size = 1)

Solution

  • Using a little made-up data, you could use fct_reorder to reorder the hallmarks based on the distance of the scores for that hallmark from the cut-off.

    library(tidyverse)
    
    # Made-up data
    df <- tribble(~hallmarks, ~scores, ~status,
            "a", 10, "x",
            "a", 12, "x",
            "a", 14, "x",
            "b", 30, "x",
            "b", 31, "x",
            "b", 32, "x",
            "c", 20, "y",
            "c", 22, "y",
            "c", 26, "y",
            "d", 40, "y",
            "d", 39, "y",
            "d", 41, "y",
            "e", 30, "y",
            "e", 40, "y",
            "e", 60, "y"     
    ) 
    
    cut_off <- 30
    
    df |> 
      group_by(hallmarks) |> 
      mutate(distance = if_else(min(scores) >= cut_off, 
                                min(scores) - cut_off, max(scores) - cut_off)) |> 
      ggplot(aes(scores, fct_reorder(hallmarks, distance), color= status)) + 
      geom_point(aes(color = status)) + 
      ggtitle("Hallmarks") + 
      geom_line(aes(group = hallmarks)) + 
      geom_vline(xintercept = cut_off, color = "blue", linetype = "dashed", size = 1) +
      labs(y = "Hallmarks")
    

    Created on 2022-06-08 by the reprex package (v2.0.1)