Write x̄ (meaning average) in legend and how to prevent linebreak? - r

Good day!
I am not that familiar to R so I'd be glad to get a little help.
Assume I have the following minimal example:
test <- c(10,20,40,80,80)
avg <- mean(test)
avg <- format(avg,digits=2)
plot(test, xlab="x", ylab="y", pch = 4)
legend("topleft", legend= c("Average: ", avg))
I'd like to write x̄ instead of "average" - wonder if this is event possible as it's not a regular symbol - merely a combination of two (letter plus overline).
The other thing I'd like to get rid of is the line break after the word "Average (see arrow in graphic below):

There are two issues here. The first is that this is handled using ?plotmath in R. The operator you are looking for is bar(). This is not a function but markup that plotmath understands.
The second is that you need an expression in which avg is converted to its value. You need an expression because that is what plotmath works with. There are several solutions to this problem, but the one I use below is bquote(). You provide it an expression and anything wrapped in .( ) will be converted its value by evaluating the thing inside the .( ).
Here is your code and a suitably modified legend() call:
test <- c(10,20,40,80,80)
avg <- mean(test)
avg <- format(avg,digits=2)
plot(test, xlab="x", ylab="y", pch = 4)
legend("topleft", legend = bquote(bar(x)*":" ~ .(avg)))
Do note that this will insert exactly what is in avg. You may need to do
avg <- round(avg)
or some other formatting fix to get something nice and presentable.

Related

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.

R concatenate differently stylized characters

I'd like to name my plot such as "Plot 1 (p=0.05)".
Please note that the title is bolded and p value is italicized.
I could do manually after plotting contents and do something like:
text(x1, y, "Plot 1", font=2)
text(x2, y, "(p=0.05)", font=3)
However, it's cumbersome to compute coordinates so I'd like to do something like:
title <- (string concatenation here?)
plot(..., main=title)
I failed to find any help on this matter so leave this question here.
Thanks in advance for your help!
I would suggest using the ?plotmath expressions to do your formatting rather than the font= parameters. For example
plot(c(1,3), c(1,3))
text(2,2,expression(bold("Plot 1") ~ (italic("p=.05"))))
Results in
Note that you can't paste() expressions together as easily as you can strings. People often then try to but variables for the parts in quotes but in order to do that, you need to build an expression using bquote() or substitute(). For example
plotname <- "Plot 1"
pvalue <- paste0("p=", formatC(.04944, digits=2, format="f"))
text(2,2,bquote(bold(.(plotname)) ~ (italic(.(pvalue)))))
It is quite simple. Try adding expressions into main=.
like this:
x<- seq(6:1)
y<-c(5,3,77,6,5,1)
main="title", sub="subtitle"
plot(x,y, main=expression(paste(bold("Plot1"), italic("(p=0.05)"))))

Use Tex expression in R `main` label

I'm plotting a histogram in R and I want to include a $\bar{X}$ expression in the main argument of hist and combine it with the value of a dynamically calculated variable average.
x <- rnorm(100, 1, 1)
average <- mean(x)
hist(x, main=paste("Average $\bar{X}=", average))
That SO doesn't work and I spent hours trying to get it working with an expression statement or a substitute statement, both of which I dont find a case in the examples where the value of a variable is substituted in the text.
This solution uses * to paste text and expressions and uses substitute to replace 'average' with the calculated value.
hist(x, main = substitute("Average "*bar(x)*" = "*average, list(average=average)))
Try:
hist(x, main=bquote(Average~bar(X)==.(average) )
bquote's main use is to "import-and-evaluate" named values from the global (or enclosing) environment(s) into an expression which would otherwise not be evaluating its tokens. You could add spaces to make the expression more readable but the parser ignores them:
hist(x, main=bquote( Average ~ bar(X) == .( average ) )
If you need extra spaces use multiple tilde's: ~~~
It's rather interesting to look at the code for bquote (easy since it's not hidden):
bquote

Using subscript and variable values at the same time in Axis titles in R

I want to use the title "CO2 emissions in wetlands" in a plot in R, whereas the 2 in CO2 is in subscript, and the value for the region (here: "wetlands") is contained in a variable named "region".
region = "wetlands"
plot (1, 1, main=expression(CO[2]~paste(" emissions in ", region)))
The problem is, that not the value of the variable is pasted, but the name of the variable. This gives "CO2 emissions in region" instead of "CO2 emissions in wetlands". I also tried:
region="wetlands"
plot (1,1,main=paste(expression(CO[2]), "emissions in", region))
But the subscript is not done here, and the title is: "CO[2] emissions in wetlands".
Is it somehow possible to get values of variables into expression?
Thanks for your help,
Sven
There is no need to use paste() in producing an expression for plothmath-style annotation. This works just fine:
region <- "foo"
plot (1, 1, main = bquote(CO[2] ~ "emissions in" ~ .(region)))
giving:
Using paste() just gets in the way.
Nb: You have to quote "in" because the parser grabs it as a key part of R syntax otherwise.
You can use substitute:
mn <- substitute(CO[2]~ "emissions in" ~ region, list(region="wetlands") )
plot(1, 1, main=mn )
From the ?substitute help file:
The typical use of substitute is to create informative labels for
data sets and plots. The myplot example below shows a simple use of
this facility. It uses the functions deparse and substitute to create
labels for a plot which are character string versions of the actual
arguments to the function myplot.
For your case, stolen from one of the answers at the duplicated link:
x <- "OberKrain"
plot(1:10, 1:10, main = bquote(paste(CO[2], " in ", .(x))))

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