Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write x-axis title with text and superscript ggplot2

Tags:

r

ggplot2

I would like to write the below title at an x-axis using the following code:

Title: Grain yield (ton. ha-1)

labs(x=expression(bold(paste("Grain yield","  ","(ton.", ha^-1,")", sep=""))))

-1 should be superscripted and the entire title should be in bold. I am getting everything right excepted that the superscripted part is not in bold.

I appreciate any help.

Thanks!

like image 936
Carvalho Avatar asked Nov 02 '13 18:11

Carvalho


People also ask

How do you write a superscript in ggplot2?

To add superscript as a title add bquote function with value inside ggtitle(). Parameter : like xlab and ylab functions, we can give the title for plot directly using this function. Here we will bquote() function for writing Superscript value ( Number VS Number2 ) as a title of plot.

How do I add a superscript to text in R?

To 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 name X and Y axis in Ggplot?

To alter the labels on the axis, add the code +labs(y= "y axis name", x = "x axis name") to your line of basic ggplot code.


Video Answer


2 Answers

It's rather unusual to get incorrect advice from @BenBolker, but here is the solution to what he was offering as an example of a problem without solution:

barplot(height=c(1,1), ylab=expression(bold(paste("org.", cm^bold("-2")))))

The trick here is not to use numeric but rather text arguments. In your case you are under the common misconception that paste in plotmath has a 'sep' argument. It doesn't. (Furthermore it is generally not needed if you learn to use "~" and "*" properly.) This is a paste()-less solution:

plot(1,1, xlab=expression(bold(Grain~yield~~"(ton."*ha^"-1"*")")))

(I tested it with a base graphic because you didn't offer a complete example. There is no lab function in base R.)

like image 179
IRTFM Avatar answered Oct 13 '22 17:10

IRTFM


@Dwin thanks for you answer I just needed to make a small modification on the code you showed:

xlab=expression(bold(Grain~yield~~"(ton."*ha^"-1"*")")))

this code did not work on my entire code background back I changed it to

xlab(expression(bold(Grain~yield~~"(ton."*ha^"-1"*")")))

changed the signal = for ( and it worked perfectly.

Thank you very much!!!

like image 31
Carvalho Avatar answered Oct 13 '22 18:10

Carvalho