gpt4 book ai didi

r - 在ggplot中以百万为单位显示轴值

转载 作者:行者123 更新时间:2023-12-04 06:14:31 25 4
gpt4 key购买 nike

我有一张图表,我正在绘制一些非常大的数字,以百万计。我的听众不太可能理解科学记数法,所以我希望将 y 轴标记为“2M”之类的东西,例如 200 万。

这是一个例子。显示完整值 ( scales::comma ) 比它默认的科学记数法要好,但仍然有点忙:

library(ggplot2)
ggplot(as.data.frame(list(x = c(0, 200,100), y = c(7500000,10000000,2000000))),
aes(x = x, y = y)) +
geom_point() +
expand_limits( x = c(0,NA), y = c(0,NA)) +
scale_y_continuous(labels = scales::comma)

enter image description here

我不想重新调整数据,因为我还将包含带有各个数据点值的标签。

最佳答案

我认为您可以手动设置您的 labels & breaks

library(ggplot2)

ylab <- c(2.5, 5.0, 7.5, 10)

ggplot(as.data.frame(list(x = c(0, 200, 100), y = c(7500000, 10000000, 2000000))),
aes(x = x, y = y)) +
geom_point() +
expand_limits(x = c(0, NA), y = c(0, NA)) +
scale_y_continuous(labels = paste0(ylab, "M"),
breaks = 10^6 * ylab
)



编辑:添加更通用的解决方案

# Ref: https://5harad.com/mse125/r/visualization_code.html
addUnits <- function(n) {
labels <- ifelse(n < 1000, n, # less than thousands
ifelse(n < 1e6, paste0(round(n/1e3), 'k'), # in thousands
ifelse(n < 1e9, paste0(round(n/1e6), 'M'), # in millions
ifelse(n < 1e12, paste0(round(n/1e9), 'B'), # in billions
ifelse(n < 1e15, paste0(round(n/1e12), 'T'), # in trillions
'too big!'
)))))
return(labels)
}

ggplot(as.data.frame(list(x = c(0, 200, 100, 250, 300),
y = c(500000, 1000000, 200000, 90000, 150000))),
aes(x = x, y = y)) +
geom_point() +
expand_limits(x = c(0, NA), y = c(0, NA)) +
scale_y_continuous(labels = addUnits)



创建于 2018-10-01 由 reprex package (v0.2.1.9000)

关于r - 在ggplot中以百万为单位显示轴值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52602503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com