ggplot 标签“K”代表数千或“M”代表百万(保持“逗号”y 轴标签)

Jas*_*ter 4 r ggplot2

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)
Run Code Online (Sandbox Code Playgroud)

我希望该图上的标签使用“K”表示数千(例如260K代替260000)。但是 - 我想保持 y 轴不变,并使用逗号(例如260,000)。我怎样才能实现这个目标?

geom 文本需要千但有逗号

H 1*_*H 1 8

您可以使用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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述