R_User
R_User

Reputation: 11082

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

Upvotes: 5

Views: 11800

Answers (3)

Ari B. Friedman
Ari B. Friedman

Reputation: 72779

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.

Upvotes: 7

Roman Luštrik
Roman Luštrik

Reputation: 70653

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

Upvotes: 2

Gavin Simpson
Gavin Simpson

Reputation: 174948

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.

Upvotes: 13

Related Questions