Get rid of auto spacing using bquote in r - r

I am attempting to label a plot axis in r using the bquote function. The desired string includes the greek mu character and a variable.
This results in spaces in either side of the mu:
xlab = bquote("Lake NO3 (" ~ mu ~ "mol/L): " ~ .(i))
How can I get rid of the spaces next to mu?
I tried using paste and paste0 expressions, but neither of these allow both a greek character and a variable.

If you want to get rid off space on either side of mu
i <- 25
plot(1, xlab=bquote("Lake NO3 ("*mu*"mol/L): " ~.(i) ))
If you need space on the right
plot(1, xlab=bquote("Lake NO3 ("*mu~ "mol/L): " ~.(i) ))

Related

R: Usage of greek letters within captions in ggtitle [duplicate]

I want to add a greek character to the y-axis of my barplot in R.
The problem is that I need this character to be integrated in the title. I want to write:
Diameter of aperture ("mu"m)
in the axis label.
With
ylab=expression()
I can write the greek character, with
ylab="axis title"
I can write the title with proper spaces between the words.
But I can't find a way to put all these together and write a proper label with a greek word in the axis label. I hope I was clear enough.
If you're using plotmath{grDevices}, the main help page (plotmath) contains an example of what you appear to want:
xlab = expression(paste("Phase Angle ", phi))
or for your case, I guess:
ylab = expression(paste("Diameter of aperture ( ", mu, " )"))
Does this work for you?
I think I followed your question properly. The ~ forces a space between characters in a call to expression(). Is this what you want?
plot(1:3, ylab = expression("Diameter of apeture (" * mu ~ "m)"),
, xlab = expression("Force spaces with ~" ~ mu ~ pi * sigma ~ pi)
, main = expression("This is another Greek character with space" ~ sigma))
And if you want to substitute variables in the text, use bquote. For instance, if you have a variable mu and want to show it in the title, then use the following idiom:
mu <- 2.8
plot(1:3, main=bquote(mu == .(mu)))
The part enclosed in .() will be substituted, so that the value of mu will be printed and not the greek "mu" character. Consult the R help on bquote for details.
This should be much more straight forward with latex2exp:
require(latex2exp)
plot(1, xlab = TeX('$\\mu$'))
And, in case you were dealing with an estimated quantity, plotmath{grDevices} also offers the possibility of adding a hat to your greek letter:
ylab = expression(paste("Diameter of aperture ( ", hat(mu), " )"))
The mu enclosed in hat() does the trick.
I give an updated answer to Chase's plot example (from 2011) above while working with Windows 10 with a suitable TrueType Font with the help package utf8 on R 3.62.
In my answer, I assign a value to μ. The unicode characters I just call out by their hex (??) code. The space is just a 'space' inside quotes. See my answer here:
See also:
http://www.unicode.org/Public/10.0.0/ucd/UnicodeData.txt
utf8-package {utf8}
# pi small case
utf8_print("\u03C0")
"π"
# sigma small case
utf8_print("\u03C3")
"σ"
μ <- abs(digamma(1))
μseq <- seq(μ,3*μ,μ)
dev.new()
plot(μseq, ylab = "Diameter of apeture ( μ m)",
, xlab = "Force spaces with ~ μ \u03C0 \u03C3 \u03C0 ",
, main = "This is another Greek character with space \u03C3")
#

In R, why is there awkward output in the legend when I am using paste() instead of c() in addition to pretty10exp()?

I'm trying to make the legend of this plot pretty, so I need there the be an actual superscript, which is why I am using the pretty10exp() function from the sfsmisc library. It works when I use the c() function.
However, I am also trying to keep the string and the scientific notation number on the same line. The legend() is broken into two lines, which I think is due to c(). I thought I could use paste(), but for some reason the output is now incorrect.
plot(1:12)
pVal <- 4
legend("topright", legend = c("P value:", sfsmisc::pretty10exp(pVal)), cex = 1.5)
legend("topright", legend = paste("P value:", sfsmisc::pretty10exp(pVal)), cex = 1.5)
pVal being an arbitrary number represented in scientific notation. The second line results in output like this: "P value: (significand) %*% 10^-4". The first line also doesn't give me what I want. How can I fix this problem?
pretty10exp returns an expression which allows it to use the ?plotmath features for making nice looking numbers. When working with expressions, you can't just paste values in like strings. You need to manipulate them with a special set of functions. One such function is substitute. You can do
plot(1:12)
pVal <- 4
legend("topright", cex = 1.5,
legend = substitute("P value: "*x, list(x=sfsmisc::pretty10exp(pVal)[[1]])) )
We use substitute() to take the value contained in the expression from pretty10exp and prefix it with the label you want. (We use * to concatenate rather than paste() since plotmath allows it)
This is what I would do:
fun <- function(text, pVal) {
y <- floor(log10(pVal))
x <- pVal / 10^y
bquote(.(text)*":" ~ .(x) %.% 10 ^ .(y))
}
plot.new()
text(0.5,0.7,fun("P value", 0.4))
text(0.5, 0.3, fun("P value", signif(1/pi, 1)))
No package is needed.

Superscript R squared for legend

I want to write a R-squared term for my legend but I do not know how. Could someone help me please?
My legend syntax is:
legend(2,10, c("BW (MPE=3%, R-squared=0.77)",
"MY (MPE=5%, R-squared=0.80)", pch=c(2,3))
I would liek to express R-squared as R2 as we normally have in the text.
It will work if you combine bquote and as.expression:
plot(1:10)
legend(2, 10, c(as.expression(bquote("BW (MPE = 3%," ~ R^2 ~ "= 0.77)")),
as.expression(bquote("MY (MPE = 5%," ~ R^2 ~ "= 0.80)"))),
pch=c(2,3))
This is less complex than using c( as.expression ( bquote... multiple times:
plot(1:10)
legend(2, 10, expression("BW (MPE = 3%," ~ R^2 ~ "= 0.77)",
"MY (MPE = 5%," ~ R^2 ~ "= 0.80)"),
pch=c(2,3))
It is useful to understand that the expression function is really a way to make lists of expressions and that commas are therefore reserved as separators for that process. This means you cannot have a "naked" comma in something you want to be inside one of the distinct elements. The commas immediately after the %-signs are protected from parsing by the quotes. This could fully plotmath()-ified with:
plot(1:10)
legend(2, 10, expression(BW * list(MPE == 3*'%',
R^2 == 0.77),
MY * list( MPE == 5*'%',
R^2 == 0.80)
),
pch=c(2,3))
That way the only character needing special attention is the '%'-sign because plotmath() uses that character to delimit items in the list of 'special' math tokens. See ?plotmath for the full list.

Adding greek character to axis title

I want to add a greek character to the y-axis of my barplot in R.
The problem is that I need this character to be integrated in the title. I want to write:
Diameter of aperture ("mu"m)
in the axis label.
With
ylab=expression()
I can write the greek character, with
ylab="axis title"
I can write the title with proper spaces between the words.
But I can't find a way to put all these together and write a proper label with a greek word in the axis label. I hope I was clear enough.
If you're using plotmath{grDevices}, the main help page (plotmath) contains an example of what you appear to want:
xlab = expression(paste("Phase Angle ", phi))
or for your case, I guess:
ylab = expression(paste("Diameter of aperture ( ", mu, " )"))
Does this work for you?
I think I followed your question properly. The ~ forces a space between characters in a call to expression(). Is this what you want?
plot(1:3, ylab = expression("Diameter of apeture (" * mu ~ "m)"),
, xlab = expression("Force spaces with ~" ~ mu ~ pi * sigma ~ pi)
, main = expression("This is another Greek character with space" ~ sigma))
And if you want to substitute variables in the text, use bquote. For instance, if you have a variable mu and want to show it in the title, then use the following idiom:
mu <- 2.8
plot(1:3, main=bquote(mu == .(mu)))
The part enclosed in .() will be substituted, so that the value of mu will be printed and not the greek "mu" character. Consult the R help on bquote for details.
This should be much more straight forward with latex2exp:
require(latex2exp)
plot(1, xlab = TeX('$\\mu$'))
And, in case you were dealing with an estimated quantity, plotmath{grDevices} also offers the possibility of adding a hat to your greek letter:
ylab = expression(paste("Diameter of aperture ( ", hat(mu), " )"))
The mu enclosed in hat() does the trick.
I give an updated answer to Chase's plot example (from 2011) above while working with Windows 10 with a suitable TrueType Font with the help package utf8 on R 3.62.
In my answer, I assign a value to μ. The unicode characters I just call out by their hex (??) code. The space is just a 'space' inside quotes. See my answer here:
See also:
http://www.unicode.org/Public/10.0.0/ucd/UnicodeData.txt
utf8-package {utf8}
# pi small case
utf8_print("\u03C0")
"π"
# sigma small case
utf8_print("\u03C3")
"σ"
μ <- abs(digamma(1))
μseq <- seq(μ,3*μ,μ)
dev.new()
plot(μseq, ylab = "Diameter of apeture ( μ m)",
, xlab = "Force spaces with ~ μ \u03C0 \u03C3 \u03C0 ",
, main = "This is another Greek character with space \u03C3")
#

How to add nice formated anotations to a R base graph using expression and the value of a variable?

Say, I have a variable rv which has some numerical value. Now, I want to plot the value of this variable on a base plot but preceded by a nicely formatted symbol e.g., r subscript m, using expression. To write on the plot I use mtext.
However, what I get is either the value of the variable, but no nicely formatted symbol (left annotation), or a nicely formatted symbol, but not the value of the variable, but the variable name...
I tried to play around with eval, but didn't get what I wanted. Here is my code:
plot(1:10, rep(10,10), ylim=c(0,12))
rv <- 0.43
#left annotation:
mtext(paste(expression(italic(r[M])), " = ", rv), side = 1, line = -1.5, adj = 0.1)
#right annotation:
mtext(expression(paste(italic(r[M]), " = ", rv)), side = 1, line = -1.5, adj = 0.9)
This is the result:
How do i get both, nice format and value of the variable? Thanks.
btw: I know that I can get it, if I use two times mtext and play around with adj and stuff. But I would really like to get it in one call or without playing around with the position of two annotations.
The bquote function will create an expression and alow substitution of values using .(var) syntax. for your case do something like:
text( 5,1, bquote( italic(r[M]) == .(rv) ) )
Just combine what you have and plot two pieces, joined by using adj:
R> plot(1:10, rep(10,10), ylim=c(0,12))
R> text(2,12, expression(paste(italic(r[M]))), adj=1)
R> text(2,12, paste("=", rv), adj=0)

Resources