2

After looking at many examples and lots of trying, I'm still failing to combine text strings and an expression into ggplot2 axis labels to exactly what I want.

what I am trying to get here is the x-axis label to be: axis label

the ingredients:

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

to change the numbers to 10^n notations I use this formula:

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

the name would then be build by:

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

I'm hoping to replace 10^04 with 10 followed by a 4 in superscript and to add a linebreak to the labels as the first image shows

The test code:

 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)) ~ ")" ))

gives:

best effort

p.s. I also tried

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

which only gives the 10^03 part to see if that would change the outcome of my label, but no.

Mark
  • 2,789
  • 1
  • 26
  • 66
  • sorry, typo there. should be a . instead of , and also the name of the equation should be the same. Making correction now. – Mark Jul 26 '19 at 17:45
  • I tested your code. But, it gives an error `Error in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : invalid multibyte string at '<8d><88> 10^02'` – akrun Jul 26 '19 at 17:48
  • Hmmm I just tested the updated code block after restarting R, I do not get the same error (without loading any other packages than the ones in the question), but sometimes the \xB7 floating point seems to give problems. You can try to remove that from the function sci_form10() – Mark Jul 26 '19 at 17:52
  • Though I can't test it, an option is `bquote(atop(` – akrun Jul 26 '19 at 17:57
  • I removed the problematic symbol in the question code Akrun. Perhaps it works now. – Mark Jul 26 '19 at 17:59
  • Doess this work `plot(1, main = bquote(atop(.(gsub("\\.", "\\ ", parname))~"(a.u.)"~phantom(), "(" ~ mu~ " = "~ .(sci_form10(xmean))~ ", "~ sigma~ " = "~ .(sci_form10(xsigma))~ ")")))` – akrun Jul 26 '19 at 18:08
  • Can you check the solution I posted below. I am using the new. `sci_form10`. So the values would be differeent. Otherwise, it should work – akrun Jul 26 '19 at 18:45

2 Answers2

2

An option would be wrap with atop to create line breaks

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)~ ")")))

-output

enter image description here

akrun
  • 874,273
  • 37
  • 540
  • 662
  • looks good. I will try to figure out how to also get the actual values of mu and sigma into this line – Mark Jul 26 '19 at 19:53
  • @Mark I think it should work on your side wiht the actual function. For me, it is ssome issue with the encoding – akrun Jul 26 '19 at 20:23
  • no it turns for instance 8451 into 8.451^3 (where ^ indicated superscript) – Mark Jul 26 '19 at 21:21
  • @Mark If you check the output now, it is pretty much similar to the expected output you showed – akrun Jul 26 '19 at 22:02
  • my R studio is breaking it's neck again over \u00B7. Running it outside of R shiny, it produces  instead of mid point. Even after changing the saving encoding to UTF-8 – Mark Jul 27 '19 at 10:50
  • 1
    I changed it to a * for now and it works great! Thanks for the help Akrun – Mark Jul 27 '19 at 10:56
  • One last follow up question. Would there be a way to get rid of the left value and the comma (before the sigma symbol) somehow? – Mark Aug 01 '19 at 11:23
  • DId you meant the `mu = 1.23 * 10^2 , ` – akrun Aug 01 '19 at 13:02
  • yes, or the 105.79 , when the nr is smaller than 1000 (I added a condition to the exp. format) – Mark Aug 01 '19 at 13:10
  • @Mark. Sorry, I didn't get the question correctly. Can you post as a new question if it needs some major changes – akrun Aug 01 '19 at 15:58
  • No it's only a minor thing. Just how to remove the space before the comma in bquote – Mark Aug 01 '19 at 19:56
  • 1
    @Mark Ok, that would be just `labs( x = bquote(atop(.(gsub("\\.", "\\ ", parname))~"(a.u.)"~phantom(), "(" ~ mu~ " = "~ .(xmean1) ~ .(post1)*", " ~ sigma ~ " = " ~ .(xsigma1) ~ .(post2)~ ")")))` – akrun Aug 01 '19 at 20:08
  • 1
    Ah, the * instead of ~. Thanks – Mark Aug 01 '19 at 20:22
0

I have something that does most of what you wanted.

changeSciNot <- function(n) {
  output <- format(n, digits=3, scientific = TRUE) # Transforms the number into scientific notation even if small
  output <- sub("e", "*10^", output) # Replace e with 10^
  output <- sub("\\+0?", "", output) # Remove + symbol and leading zeros on exponent, if > 1
  output <- sub("-0?", "-", output) # Leaves - symbol but removes leading zeros on exponent, if < 1
  output
}

# example data
parname <- "FL.Red.Total"
xmean <- 123.34
xsigma <- 2580.23
label <- bquote(atop(.(gsub("\\.", "\\ ", parname)) ~ "(a.u.)",
                     mu*"="*.(changeSciNot(xmean))*"," ~ sigma*"="*.(changeSciNot(xsigma))))

ggplot(mtcars, aes(x=mpg,y=cyl)) +
  geom_point() +  
  labs(x = label)

The changeSciNot function came from this thread. I had some problems using \xB7 for the multiplication, so I left *. I also hard coded the number of digits for the format, but you can also make it into an argument. Hopefully, this will get you closer to the exact desired output.

Arienrhod
  • 2,451
  • 1
  • 11
  • 19
  • I run into this error again with my shiny app that has the real plot in it when I use your approach: "Warning: Error in grid.Call.graphics: Metric information not available for this family/device" Will test tomorrow what causes it – Mark Jul 26 '19 at 19:53