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

问题描述

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

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

two formats for scientific notation

解决方法

从类似的情节开始:

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

enter image description here

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

divisor = 1E-8

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

enter image description here

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

enter image description here


编辑:

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

ggplot(mtcars,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,digits = 0)) +
  coord_cartesian(clip = "off") +
  labs(title = "Title here") +
  theme(plot.title = element_text(margin = margin(0,20,0)))

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...