Generate a list of expression literals from an integer sequence - r

I would like to map a sequence of integers to a sequence of expression literals in order to use the latter as tick mark labels in a plot, e.g.
lbls <- lapply(-2:2, function(i) expression(i * pi))
plot(...)
axis(1, at=seq(-2,2)*pi, labels=lbls)
So far I've tried all variations of bquote, substitute, expression etc. that I could think of, but apparently I must have missed something.
Also, the FAQ and related SO questions & answers didn't fully solve this for me.
How would I do it correctly (I want axis to render pi as the greek letter and have -2 ... 2 substituted for i in the above example)?

try this:
lbls <- do.call("expression", lapply(-2:2, function(i) substitute(X * pi, list(X = i))))
plot(-10:10, -10:10, xaxt="n")
axis(1, at=seq(-2,2)*pi, labels=lbls)

Try this:
lbls <- parse(text = paste(seq(-2, 2), "pi", sep = "*"))

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.

How to include subscript in text for plot point labels

Hi I'm new to R so I apologise if this is a very basic question.
I'm trying to add text to a plot at point 11 on the x axis and point 900 on the y axis that will read t0= -4.0280 with the 0 as subscript. Where t0 <- -4.0280
To do this I've tried:
text(11,900,paste("t[0]=",t0),cex=0.8)
# which gives
't[0]= -4.0280'
text(11,900,expression(paste("t[0]=",t0)),cex=0.8)
# which gives
't[0]=t0'
# the closest I've gotten is:
text(11,900,expression(paste(t[0]==t0)),cex=0.8)
which will use subscript but return t0 instead of my value of -4.0280.
Could anyone show me where Ive gone wrong?
Cheers.
You can replace expression with substitute. There's no need for the paste. The argument list(t0 = t0) tells substitute to replace the string t0 with the value of the object t0:
plot(1,1)
t0 <- 1.3
text(1, 0.8, substitute(t[0]==t0, list(t0 = t0)), cex = 0.8)
Slightly shorter than substitute is with bquote:
plot(1,1)
t0 <- -4.0280
text(1, 0.8, bquote("t"[0] ~ "=" ~ .(t0)))
of if you'd like to use paste in there:
text(1, 0.8, (bquote("t"[0]~.(paste0('=',t0)))))
This kind of Q has popped up previously:
Using subscript and variable values at the same time in Axis titles in R
Concatenate strings and expressions in a plot's title

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

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.

Add values and superscript to pie-labels

I'm struggling with adding a superscript to the labels of a plot.
I would like to have the '3' in the labels (..m^3) as superscript. I tried expression(), substitute() etc. but didn't find the correct solution.
values <- c(2, 4, 5)
pie(values, labels = paste(values, "m^3") )
Thanks for any hint!
A bit cumbersome workaround:
foo <- sapply(as.list(values), function(x) bquote(.(x) ~ m^3))
pie(values, labels = as.expression(foo))

use of mathematical annotation as factor in R

I refer to my previous question, and want to know more about characteristics of factor in R.
Let say I have a dataset like this:
temp <- data.frame(x=letters[1:5],
y=1:5)
plot(temp)
I can change the label of x easily to another character:
levels(temp[,"x"]) <- letters[6:10]
But if I want to change it into some expression
levels(temp[,"x"]) <- c(expression(x>=1),
expression(x>=2),
expression(x>=3),
expression(x>=4),
expression(x>=5))
The >= sign will not change accordingly in the plot. And I found that class(levels(temp[,"x"])) is character, but expression(x>=1) is not.
If I want to add some mathematical annotation as factor, what can I do?
I do not see any levels arguments in ggplot and assigning levels to a character vector should not work. If you are trying to assign expression vectors you should just use one expression call and separate the arguments by commas and you should use the labels argument in a scale function:
p <- qplot(1:10, 10:1)+ scale_y_continuous( breaks= 1:10,
labels=expression( x>= 1, x>=2, x>=3, x>= 4,x>=5,
x>= 6, x>=7, x>= 8,x>=9, x>= 10) )
p
I would just leave them as character strings
levels(temp[,"x"]) <- paste("x>=", 1:5, sep="")
If you then want to include them as axis labels, you could do something like the following to convert them to expressions:
lev.as.expr <- parse(text=levels(temp[,"x"]))
For your plot, you could then do:
plot(temp, xaxt="n")
axis(side=1, at=1:5, labels=lev.as.expr)
Expression is used to generate text for plots and output but can't be the variable names per se. You'd have to use the axis() command to generate your own labels. Because it can evaluate expressions you could try...
plot(temp, xaxt = 'n')
s <- paste('x>', 1:5, sep = '=')
axis(1, 1:5, parse(text = s))

Resources