在ggplot中显示以百万为单位的轴值 [英] Display an axis value in millions in ggplot

查看:174
本文介绍了在ggplot中显示以百万为单位的轴值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图表,其中以百万为单位绘制了一些非常大的数字.我的听众不太可能理解科学计数法,因此我希望将y轴标记为"2M"之类的数字,例如为200万.

I have a chart where I am charting some very large numbers, in the millions. My audience is unlikely to understand scientific notation, so I'm hoping to label the y axis in something like "2M" for two million for example.

这是一个例子.显示完整值(scales::comma)优于其默认的科学计数法,但仍然有点忙:

Here's an example. Showing the full value (scales::comma) is better than the scientific notation it defaults to, but is still a bit busy:

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)

我不想重新缩放数据,因为我还将包括带有各个数据点值的标签.

I don't want to rescale the data, since I will be including labels with the values of the individual data points as well.

推荐答案

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

I think you can just manually set your 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
  )

修改:添加更通用的解决方案

add a more generic solution

# 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)

reprex软件包(v0.2.1.9000)<创建于2018年10月1日

Created on 2018-10-01 by the reprex package (v0.2.1.9000)

这篇关于在ggplot中显示以百万为单位的轴值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆