Marcos Alex
Marcos Alex

Reputation: 1630

R - Plot: How to format in 10-base scientific notation and put it text, mtex, title etc functions?

I have numeric variable, say K=3.5e-5 (its values is calculated throughout my script). I want to write this value somewhere (title, as text in the plot, etc) in my plot as:

K_{root} = 3.5 10^{-5} cm /d

I have tried the functions bquote, substitute and no one worked.

Let's put the question in examples. I have tried the following:

1)

png("exp_1.png")
kroot = 3.5e-5
plot(1:10,1:10,
text(4,9,bquote(italic(K[root])~"="~.(kroot)~"cm/d")))
dev.off()

Upvotes: 1

Views: 1690

Answers (2)

IRTFM
IRTFM

Reputation: 263352

I try to avoid using paste inside expressions. There is generally a cleaner way to approach this:

expon <- floor(log10(kroot))  # returns -5
mantis <- kroot*10^(-1*expon ) # returns 3.5
plot(1:10,1:10,
text(4,9,substitute( italic(K[root]) == mantis %.% pten* expon ~cm/d, 
                        list(expon=expon, mantis=mantis, pten=" 10^")))

enter image description here

Upvotes: 1

Drew75
Drew75

Reputation: 297

Try my favorite function, paste().

plot(1:10,1:10,
text(4,9,gsub("e",paste("K[root]=",format(k,scientific=TRUE),"cm/d",sep=" "),replacement=" 10^")))

You can replace the "e" here using the function gsub. I've edited my answer to include this.

The output:

 > k=.0000035
 > k
 [1] 3.5e-06


> gsub("e",paste("K[root]=",format(k,scientific=TRUE),"} cm/d",sep=" "),replacement=" 10^{ ")
[1] "K[root]= 3.5 10^{ -06 } cm/d"

You can remove the extra spaces around { -06 } by using the function substr, if it's important, or simply leave out the curly brackets in the gsub statement.

Upvotes: 2

Related Questions