在 R 上使用 ggplot2 生成紧凑的科学记数法

Generating compact scientific notation with ggplot2 on R

我用 ggplot2 生成的图看起来像左边的图,在 y 轴的每个刻度上都有完整的科学记数法。我怎样才能让它看起来像右边的图一样紧凑,它在角落里用红色圆圈标记了科学记数法?

我没有在 ggplot2 包文档或堆栈溢出中看到这一点。有人有解决方法吗?

two formats for scientific notation

从类似的情节开始:

ggplot(mtcars, aes(wt, mpg * 1E-8)) +
  geom_point()

如果我们知道要使用的比例,我们可以定义它,然后我们可以在输入的过程中缩放数据,或者更改 y 轴上的标签,看起来一样,除了 y轴标签(我们可以随意重命名):

divisor = 1E-8

ggplot(mtcars, aes(wt, mpg * 1E-8 / divisor)) +
  geom_point() +
  labs(title = formatC(divisor, format = "e", digits = 0))

ggplot(mtcars, aes(wt, mpg * 1E-8)) +
  geom_point() +
  scale_y_continuous(labels = function(x) x / divisor) +
  labs(title = formatC(divisor, format = "e", digits = 0))


编辑:

如果你也想要一个标题,你也可以使用annotate将文本写在绘图区域之外,然后将标题向上滑动:

ggplot(mtcars, aes(wt, mpg * 1E-8)) +
  geom_point() +
  scale_y_continuous(labels = function(x) x / divisor) +
  annotate("text", x = -Inf, y = Inf, hjust = 0, vjust = -0.5,
           label = formatC(divisor, format = "e", digits = 0)) +
  coord_cartesian(clip = "off") +
  labs(title = "Title here") +
  theme(plot.title = element_text(margin = margin(0,0,20,0)))