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

Viewed 664
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

2 Answers

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

You can just add a custom column called myLabel to your dataframe which holds your desired labels. In the package scales you can find a function that does the converting part for you:

df <- mpg %>% head() %>% mutate(hwy = hwy * 10000)
df$myLabels <- scales::label_number_si()(df$hwy)

Now, use the new column myLabels as the aesthetic for creating the labels

    ggplot(df, aes(cty, hwy)) + 
    geom_point() + 
    scale_y_continuous(label = scales::comma) +
    geom_text(aes(label = myLabels), hjust = -0.25)
Related