rggplot2

ggplot labels with "K" for thousands or "M" for millions (maintaining 'comma' y-axis labeling)


library(tidyverse)
df <- mpg %>% head() %>% mutate(hwy = hwy * 10000)
ggplot(df, aes(cty, hwy)) + 
  geom_point() + 
  scale_y_continuous(label = scales::comma) +
  geom_text(aes(label = hwy), hjust = -0.25)

I want the labels on this plot to use "K" for thousands (eg 260K instead of 260000). BUT - I want to maintain the y-axis as is, with commas (eg 260,000). How can I achieve this?

geom text desired thousand but have commas


Solution

  • NOTE: This function was deprecated in scales 1.2.0 and no longer works. Use the answer provided by johnm label_number(scale_cut = cut_short_scale())(hwy).

    You can use scales::label_number_si():

    library(scales)
    library(ggplot2)
    
    ggplot(df, aes(cty, hwy)) + 
      geom_point() + 
      scale_y_continuous(label = comma) +
      geom_text(aes(label = label_number_si()(hwy)), hjust = -0.25)
    

    enter image description here