我想将ggplot2轴上的科学记数法从3.23e+6格式更改为3.23 × 10^6格式。谢天谢地,这个问题已经在这里得到了回答:How do I change the formatting of numbers on an axis with ggplot?
它在基本情况下效果很好。但是,当您要更改轴标签的格式时,它不起作用。下面的例子说明了这一点:
library(tidyverse)
ggplot(mpg, aes(displ, hwy*10^9)) + geom_point()
#makes the scientific notation using "AeB" explicitly write out Ax10^B
fancy_scientific <- function(l) {
# turn in to character string in scientific notation
l <- format(l, scientific = TRUE)
# quote the part before the exponent to keep all the digits
l <- gsub("^(.*)e", "'\\1'e", l)
# turn the 'e+' into plotmath format
l <- gsub("e", "%*%10^", l)
# return this as an expression
parse(text=l)
}
ggplot(mpg, aes(displ, hwy*10^9)) +
theme_classic() +
geom_point() +
scale_y_continuous(labels= fancy_scientific) +
theme(text = element_text(face = "bold")) 这会产生:

问题是Y轴文本并不像theme调用中指定的那样是粗体的。当我使用browser查看fancy_scientific内部发生的事情时,我看到它返回一个"expression“类的对象,在本例中,该对象被打印为expression('2'%*%10^+01, '3'%*%10^+01, '4'%*%10^+01),而函数scales::scientific直接返回一个字符串向量,该函数可用于强制使用我希望避免的那种科学记数法,但它符合我设置的任何主题规范。当我修改fancy_scientific以返回像'2'%*%10^+01这样的字符串向量时,它们被直接呈现到显示的Y轴上。
因此,问题是如何使fancy_scientific函数的输出符合我的主题规范?
发布于 2020-08-20 10:54:37
正如评论所建议的那样,一种方法是使用ggtext包。
library(tidyverse)
library(ggtext)
ggplot(mpg, aes(displ, hwy*10^9)) + geom_point()
#makes the scientific notation using "AeB" explicitly write out Ax10^B
fancy_scientific <- function(l) {
# turn in to character string in scientific notation
l <- format(l, scientific = TRUE)
# quote the part before the exponent to keep all the digits
l <- gsub("^(.*)e", "'\\1'e", l)
# turn the 'e+' into plotmath format
l <- gsub("e", "%*%10^", l)
# return this as an expression
parse(text=l)
}
ggplot(mpg, aes(displ, hwy*10^9)) +
theme_classic() +
geom_point() +
scale_y_continuous(labels= fancy_scientific) +
theme(text = element_text(face = "bold"),
axis.text.y = element_markdown(face = "bold")) 但是,如果您运行此代码,您会注意到一些问题。前导数字周围有引号,可以通过删除l <- gsub("^(.*)e", "'\\1'e", l)中的单引号来删除引号。当我将text指定为element_markdown()时,我得到了一个错误,因为显然需要为文本的其他部分设置一些默认值。因此,我必须明确地将axis.text.y设置为element_markdown。这就留下了显示实时标志的问题。我将就此问一个后续问题,因为我已经回答了如何应用粗体格式的问题,尽管我也很好奇如何正确地将默认值设置为element_markdown,以便我可以使用它来指定text而不是axis.text.y。
https://stackoverflow.com/questions/63477686
复制相似问题