Search code examples
rggplot2geom-text

How to align text labels to left side of a geo_segment


I want to add labels next to the left side of the line but there is a gap between the beginning of the line and the end of the label that seems to be associated with how long the label is. The longer the label the bigger the gap and vice-versa. Is there a way to make all the labels have the same distance from the beginning of the line? Below is toy data to mimic the issue.

library(tidyverse)
 data.frame(start = seq(from = 50000, to = 90000, by = 10000),
                  end = seq(from = 60000, to = 104000, by = 11000),
                  type = c("Tesla","Tesla Extended Range", "EV Volvo",
                           "EV Volvo XC90 7 Passanger","EV BMW")) %>% 
mutate(type = fct_reorder(type, start, .fun='sum' )) %>% 
ggplot +
geom_segment(aes(x = start, y = type, 
               xend = end, yend = type),
           show.legend = FALSE, alpha = .8) +
geom_text(aes(x = start, y = type, label = type),
        vjust = -1 , size = 3, hjust = 1.4, nudge_x = -1, alpha = .8) +
coord_cartesian(xlim =c(40000, NA)) +
theme(axis.title.y = element_blank(),
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank()) 

enter image description here


Solution

  • Simply set hjust=1 and shift your labels using nudge_x:

    Note: That's one of the reason why I try to avoid setting a value for hjust or vjust outside of [0, 1].

    library(tidyverse)
    
    data.frame(
      start = seq(from = 50000, to = 90000, by = 10000),
      end = seq(from = 60000, to = 104000, by = 11000),
      type = c(
        "Tesla", "Tesla Extended Range", "EV Volvo",
        "EV Volvo XC90 7 Passanger", "EV BMW"
      )
    ) %>%
      mutate(type = fct_reorder(type, start, .fun = "sum")) %>%
      ggplot() +
      geom_segment(
        aes(
          x = start, y = type,
          xend = end, yend = type
        ),
        show.legend = FALSE, alpha = .8
      ) +
      geom_text(aes(x = start, y = type, label = type),
        vjust = -1, size = 3, hjust = 1, nudge_x = -1000, alpha = .8
      ) +
      coord_cartesian(xlim = c(40000, NA)) +
      theme(
        axis.title.y = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank()
      )