Home > Mobile >  duplicating and edit a discrete axis in ggplot2 - 2021
duplicating and edit a discrete axis in ggplot2 - 2021

Time:10-07

There are a couple of other posts on the same topic, but the solutions proposed do not fit my case. Given a data frame like this

    ddff <- structure(
  list(
    SampleID = structure(
      20:16,
      .Label = c(
        "S39",
        "S30",
        "S35",
        "S22",
        "S23",
        "S26",
        "S29",
        "S24",
        "S27",
        "S32",
        "S37",
        "S36",
        "S38",
        "S34",
        "S33",
        "S40",
        "S25",
        "S28",
        "S31",
        "S21"
      ),
      class = "factor"
    ),
    Counts = c(12177, 14367, 15118, 15312,
               16622),
    sampleName = structure(
      20:16,
      .Label = c(
        "2Dr",
        "2Es",
        "1Er",
        "1Bs",
        "1Cs",
        "2As",
        "2Ds",
        "1Ds",
        "2Bs",
        "1Br",
        "2Br",
        "2Ar",
        "2Cr",
        "1Dr",
        "1Cr",
        "2Er",
        "1Es",
        "2Cs",
        "1Ar",
        "1As"
      ),
      class = "factor"
    ),
    compartment = c("soil", "root", "soil",
                    "soil", "root")
  ),
  row.names = c(NA, 5L),
  class = "data.frame"
)

and the following code

library(tidyverse)    
ddff %>%
      ggplot(aes(x = Counts, y = SampleID))  
      geom_point(aes(col = compartment), size = 4, alpha = 0.75)  
      geom_text(
        aes(label = paste0("   ", Counts)),
        size = 3,
        hjust = 0,
        nudge_x = -0.1,
        check_overlap = TRUE,
        color = "blue"
      )  
      xlim(NA, 33000)  
      theme_light()  
      theme(plot.title = element_text(hjust = 0.5), aspect.ratio = 1)  
      theme(# remove the vertical grid lines
        panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank())  
      labs(title = "Library Size Overview",
           x = "Read Counts",
           color = "Compartment")  
      theme(
        legend.position = c(.95, .95),
        legend.justification = c("right", "top"),
        legend.box.just = "right",
        legend.box.background = element_rect(color = "black", size = 1)
      )

I get this plot second axis with categorical data

  • Related