Display name
Display name

Reputation: 4481

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

Upvotes: 5

Views: 2027

Answers (3)

lroha
lroha

Reputation: 34376

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

Upvotes: 7

johnm
johnm

Reputation: 320

To keep this up to date, from version 1.2 of {scales}, the final line should use cut_short_scale() as label_number_si() is deprecated

library(scales)
library(ggplot2)

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

Upvotes: 2

Jonas
Jonas

Reputation: 1810

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)

Upvotes: 0

Related Questions