R concatenate differently stylized characters - r

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

Related

R plot title involving a subscript and value of a variable

In R, the value of the variable MyVar should be evaluated and appear in the title of a simple R plot p.
MyVar<-0.23
The plot p is called using
plot(p, main = MyTitle)
My plot title needs a subscript and should look like this:
What is the correct statement for MyTitle= ?
I tried dozens of variations using paste, expression, substitute, and bquote. Nothing seems to work...
Any help is highly appreciated!
Thanks a bunch!
Mark
I don't believe you can paste an expression to a variable (paste/print/cat/bquote/etc). As a workaround, you could use the "Fbelow=" expression as the title and use mtext to insert the value of MyVar, e.g.
MyVar<-0.23
plot(mtcars[2:3], main = expression('F'[below]*'='))
mtext(text = MyVar, side = 3, adj = 0.625, padj = -1.75, cex = 1.5)
Obviously this isn't ideal, but unless someone else has a clever way of solving your issue this will at least give you a potential option

Add an equation into scatter plots in R

I have a little trouble to add the equations into scatter plots using "legend"
A simple example is as follow:
plot(1:100)
# The below code can work if I add "= 0.1234" directly.
legend(locator(1), expression(paste("Linear model: ", R^2, "= 0.1234",sep="")),
text.col= "black",cex=1,bty="n")
# The below code cannot work if I add the "ps".
ps = "= 0.1234"
legend(locator(1), expression(paste("Linear model: ", R^2, ps, sep="")),
text.col= "red",cex=1,bty="n")
The real issue I have is a little complex with this example.
So how should I revise this code?
The "ps"-object is being handled as an expression, i.e. not being evaluated. To get around this use bquote and .()
legend(locator(1), legend= bquote("Linear model: "* R^2*.(ps)),
text.col= "red",cex=1,bty="n")
BTW the first version would be more compactly represented without the paste:
legend(locator(1), expression(Linear~model*":"~ R^2 == 0.1234),
text.col= "black",cex=1,bty="n")
The only thing needing to be quoted is the semi-colon.

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.

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 show $\{ X_t \}$ in the title of a plot of R

How to show $\{ X_t \}$ of Latex in the title of a plot of R?
For example
plot(slot(x,"GRID"),slot(x,"PATH"),type="l", xlab="Time t",ylab="X",
main=paste("Simulation of \{X_t\}"))
Thanks!
Assuming you will provide meaningful arguments for the slot expressions, then I think there is a reasonable chance that this is what you want:
plot(1:10,1:10,type="l", xlab="Time t",ylab="X",
main=expression("Simulation of {"*X[t]*"}"))
This is a plotmath expression that presents "t" as a subscript of "X" and that expression is enclosed in curley braces. If I have misread your request, then note that the "*" character is a separator in the plotmath syntax and the braces are simply characters than can be deleted. (The LaTeX expressions don't make a lot of sense to those of us who just use the plotmath syntax, so describing what you want in prose or mathematical jargon would work better for any clarifications.)
To have R emulate LaTeX typesetting, see the examples and methods described in ?plotmath.
To actually have LaTeX typeset your plot text, use the tikz() graphics device provided by the tikzDevice package.
The group() plotmath function can be used to formalise DWin's answer. This solution has the advantage (IMHO) of not using strings as part of the expression. Instead we use the ~ operator to add spacing (whitespace is ignored).
plot(1:10, 1:10, type = "l", xlab = "Time t", ylab = "X",
main=expression(Simulation ~ of ~ group("{", X[t], "}")))
The bgroup() plotmath function provides scalable delimiters but is used in the same manner as the example code above.
Edit (In response to ran2's comment):
The same approaches can be used in ggplot and lattice, using the power of plotmath, just as with base graphics. E.g.
require(ggplot2)
df <- data.frame(A = 1:10, B = 1:10)
qplot(A, B, data = df,
main = expression(Simulation ~ of ~ group("{", X[t], "}")))

Resources