我正在尝试遵循一种出版风格指南,只有5位或更多位数的数字才能使用逗号.搜索过此内容但未找到使用'labels =逗号'时覆盖默认值的方法.以下是一个例子:
require(dplyr)
require(ggplot2)
require(scales)
# create mock dataframe
temp <- mpg %>% mutate(newvar=(hwy*300))
ggplot(temp, aes(x=cyl, y=newvar)) + geom_point() +
scale_y_continuous(labels=comma) +
labs(title="When using 'labels=comma'...",
subtitle="How format axis labels such that commas only appear for numbers > 9999?")
Run Code Online (Sandbox Code Playgroud)
使用这个例子,希望最下面的y轴标签读取"4000","6000"等.可以手动实现这一点,但这不值得打扰,因为许多图表的尺度都包含在这个范围内.有什么建议?
我们可以在以下内容中使用匿名函数scale_x_continuous:
library(scales)
library(ggplot2)
# generate dummy data
x <- 9998:10004
df <- data.frame(x, y = seq_along(x))
ggplot(df, aes(x = x, y = y))+
geom_point()+
scale_x_continuous(labels = function(l) ifelse(l <= 9999, l, comma(l)))
Run Code Online (Sandbox Code Playgroud)