r - bquote轴标签ggplot2中的换行符和上标

标签 r ggplot2 scientific-notation

在查看了许多示例并进行了大量尝试之后,我仍然无法将文本字符串和表达式组合到 ggplot2 轴标签中,以达到我想要的效果。

我想要得到的是 x 轴标签: axis label

成分:

parname <- 'FL.Red.Total'
xmean <- 123.34
xsigma <- 2580.23

要将数字更改为 10^n 表示法,我使用以下公式:

sci_form10 <- function(x) {
    paste(gsub("e\\+", " \xB7 10^", scientific_format()(x)))
}

名称将由以下方式构建:

  labs( x = bquote(.(gsub('\\.', '\\ ', parname)) ~ " (a.u.) (" ~ mu ~ "=" ~ .(sci_form10(xmean)) ~ ", " ~ sigma ~ " =" ~ .(sci_form10(xsigma)) ~ ")" ))

我希望将 10^04 替换为 10,后跟上标中的 4,并在标签中添加换行符,如第一张图片所示

测试代码:

 library(ggplot2)
 library(scales)
 sci_form10 <- function(x) {
        paste(gsub("e\\+", " * 10^", scientific_format()(x)))
 }

 parname <- 'FL.Red.Total'
 xmean <- 123.34
 xsigma <- 2580.23
 ggplot(mtcars, aes(x=mpg,y=cyl)) +
        geom_point() +  
        labs( x = bquote(.(gsub('\\.', '\\ ', parname)) ~ " (a.u.) (" ~ mu ~ "=" ~ .(sci_form10(xmean)) ~ ", " ~ sigma ~ " =" ~ .(sci_form10(xsigma)) ~ ")" ))

给出:

best effort

附:我也尝试过

sci_form10 <- function(x) {
        paste(gsub(".*e\\+", "10^", scientific_format()(x)))
  }

它只给出了 10^03 部分,看看这是否会改变我的标签的结果,但不会。

最佳答案

选项将用 atop 包裹起来以创建换行符

sci_form10 <- function(x) {
  paste(gsub("e\\+", " \u00B7 10^", scientific_format()(x)))
    }

x1 <-  sci_form10(xmean)
x2 <-  sci_form10(xsigma)
lst1 <- strsplit(c(x1,x2), "\\s(?=10)", perl = TRUE)
pre <- sapply(lst1, `[`, 1)
post <- sapply(lst1, `[`, 2)  
xmean1 <- parse(text = paste0("'", pre[1], "'"))[[1]]
xsigma1 <- parse(text = paste0("'", pre[2], "'"))[[1]]
post1 <- parse(text = post[1])[[1]]
post2 <- parse(text = post[2])[[1]]
ggplot(mtcars, aes(x=mpg,y=cyl)) +
                  geom_point() +  
                    labs( x = bquote(atop(.(gsub("\\.", "\\ ", 
                      parname))~"(a.u.)"~phantom(), "(" ~ mu~ " = "~ .(xmean1) ~ .(post1) ~ ", " ~ sigma ~ " = " ~ .(xsigma1) ~ .(post2)~ ")")))

-输出

enter image description here

关于r - bquote轴标签ggplot2中的换行符和上标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57224569/

相关文章:

r - 如何在 Shiny Leaflet map 中将图层置于顶部

子目录中的 RStudio 项目和 git 存储库

r - 无法读取 R 中的 Outlook(.msg) 文件

r - R中的ggplot错误

r - 可以在R中绘制图表吗?

c - 分步创建二进制文件

r - 如何比较不同阶数的因子水平?

r - ggplot 带虚线的箭头

ruby-on-rails - ruby /rails : How can I display a number in scientific notation?

python - 我可以关闭 matplotlib 条形图中的科学记数法吗?