How to remove automatic space after greek lettters using the cairo library? - r

I am using expression() to create a string that includes greek letters. My legend label is as follows:
legend.label = paste(mu, "+", sigma, ", ", mu, ", ", mu, "+", sigma, " of
random strategy", sep ="")
This should give me something like: μ+σ, μ, μ+σ of random strategy, but instead I am getting this:
It seems as if there is an automatic space after the greek letters. I already tried using the * and ~ operator, but it didnt help. I am using the cairo package to create anti-anialised plots. However, without using the cairo package I seem to get the right result. Does anybody have an idea how to fix this? Thanks!

I don't know how you defined the "greek letters" but you can use the unicode to put them without space in your legend:
plot(0:1, 0:1, type="none", main="\U03BC+\U03C3, \U03BC, \U03BC+\U03C3 of
random strategy")

The way to do this is described in help("plotmath"):
plot(1)
legend("top", legend = expression(paste(mu + sigma,
", ",
mu,
", ",
mu + sigma,
" of random strategy")),
lty = 1, col = "red", bty = "n")

Related

legend in R plot display all lines

I have a following problem.
I want to put a legend into my graph. My code:
plot(Lc(`BEL_2016_final.csv`$value),col="red",lwd=2,
xaxt="n", yaxt="n", cex.lab = 1.5)
axis(side=1, at=axTicks(1), cex.axis = 1.5)
axis(side=2, at=axTicks(2), cex.axis = 1.5)
par(new=TRUE)
plot(Lc(`CRO_2016_final.csv`$value),col="blue",lwd=2,
xaxt="n", yaxt="n", cex.lab = 1.5)
axis(side=1, at=axTicks(1), cex.axis = 1.5)
axis(side=2, at=axTicks(2), cex.axis = 1.5)
legend(x = "topleft", legend=paste0(c("Belgium, Gini "),
round(Gini(`BEL_2016_final.csv`$value), digits = 2),
c("Croatia, Gini "),
round(Gini(`CRO_2016_final.csv`$value), digits = 2)),
col=c("red", "blue"), lty=1:2, cex=1, lwd=1.5)
However, the legend looks like this:
When I try:
legend=paste0(c("Belgium, Gini ", "Croatia, Gini "),
round(c(Gini(`BEL_2016_final.csv`$value)),
Gini(`CRO_2016_final.csv`$value)),
digits = 2)
I got this result:
which is wrong, because Gini index for Croatia is 0.73.
How can I modify my code to display both lines (red and blue) in the legend, both on a new line? Thanks a lot.
Your parentheses are mismatched. Whatever IDE/editor you are using I encourage the use of matching (sometimes "rainbow") parentheses. For example, in RStudio, if the cursor is the _ symbol (and accepting RStudio's insistence on its indentation preference):
notice that the ( next to paste0 is highlighted, suggesting you that digits=2 is the last argument in paste0. This is incorrect. Another hint is using RStudio's indentation preference (highlight the block and press Ctrl-I, the default keypress for "Reindent Lines"): the second Gini lines up with c(, not with the first Gini, meaning that c( and second-Gini are at the same level ... where I would expect the second-Gini to be nested within the c(.
To validate what is going on, I'll replace the Gini(.) calls with your 0.52 and 0.73 values, verbatim (but please keep them as Gini(.) in your code:
paste0(c("Belgium, Gini ", "Croatia, Gini "),
round(c(0.52),
0.73),
digits = 2)
# [1] "Belgium, Gini 0.52" "Croatia, Gini 0.52"
Looking at it this way, it appears as if the first right-paren after 0.52 might have been intended to be after the 0.73, since grouping 0.52 and 0.73 makes sense.
Here is corrected code, where all I do is remove one right-paren from after the first-Gini, and add one right-paren to the very end of this expression:
legend=paste0(c("Belgium, Gini ", "Croatia, Gini "),
round(c(Gini(`BEL_2016_final.csv`$value),
Gini(`CRO_2016_final.csv`$value)),
digits = 2) )
and the associated matching-paren highlighting (again, _ is the current cursor):
<soapbox>
PS: I am not saying that one must use the RStudio IDE for R work. In fact, I don't, I use emacs/ess. There are other editors to use as well. However, as much as indentation and similar can be viewed as style and therefore not important for programming, I argue that indentation and some editor functionality like matching-parens can help in readability as well as troubleshooting code before you even get to a mistake; for instance, a consistent indentation style alone here hints to improper paren-closure, and the matching-paren-highlighter confirms it. Use what you prefer, but some programming styles are actually beneficial functionally (and therefore pragmatic).
</soapbox>
Correct solution is:
legend(x = "topleft", legend=paste0(c("Belgium, Gini ", "Croatia, Gini "),
c(round(Gini(`BEL_2016_final.csv`$value), digits = 2),
round(Gini(`CRO_2016_final.csv`$value), digits = 2)
)),
col=c("red", "blue"), lty=1:2, cex=1, lwd=1.5)

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.

Get rid of auto spacing using bquote in 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) ))

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

Resources