Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

plot

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

like image 636
R_User Avatar asked Aug 11 '11 11:08

R_User


People also ask

How do you do subscript and superscript in R?

Subscripts and SuperscriptsTo indicate a subscript, use the underscore _ character. To indicate a superscript, use a single caret character ^ . Note: this can be confusing, because the R Markdown language delimits superscripts with two carets.

How do you use superscript in R?

Superscript is “started” by the caret ^ character. Anything after ^ is superscript. The superscript continues until you use a * or ~ character. If you want more text as superscript, then enclose it in quotes.


3 Answers

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:

enter image description here

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.

like image 146
Gavin Simpson Avatar answered Oct 21 '22 01:10

Gavin Simpson


You can use substitute:

mn <- substitute(CO[2]~ "emissions in" ~ region, list(region="wetlands") )
plot(1, 1, main=mn )

substitute plot

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.

like image 21
Ari B. Friedman Avatar answered Oct 21 '22 01:10

Ari B. Friedman


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

enter image description here

like image 2
Roman Luštrik Avatar answered Oct 20 '22 23:10

Roman Luštrik