Home > Software design >  ggplot letters in x axis replacing a continuos numerical sequence
ggplot letters in x axis replacing a continuos numerical sequence

Time:02-22

I would like to replace the numbers on the X-axis with a string.

df <- data.frame(Start = c(1, 3, 8, 10),
                 End = c(5, 10, 12, 15),
                 Height = c(10, 4, 5, 6))

p <- ggplot(df) 
    geom_segment(aes(x = Start,
                     xend = End,
                     y = Height,
                     yend = Height))

This is the string, each letter should go in a distance of 1: The first segment Will have coverage of ADFLK

lettersString <- 'ADFLKENACOINQLWEJI'    

This is what I would like to obtain. enter image description here

I have tried solving it like this: (It doesn't work)

p   theme(axis.text.x =  strsplit(lettersString, split = " "))

CodePudding user response:

library(ggplot2)    
df <- data.frame(Start = c(1, 3, 8, 10),
                     End = c(5, 10, 12, 15),
                     Height = c(10, 4, 5, 6))
    

xAxis <- unlist(strsplit(lettersString, split = " "))
p <- ggplot(df) 
  geom_segment(aes(x = Start,
                   xend = End,
                   y = Height,
                   yend = Height))  
  scale_x_continuous(labels=xAxis, breaks=1:length(xAxis), limits=c(1,length(xAxis)))
  
p

enter image description here

  • Related