Adding greek character and asterisk (*) to axis title

Viewed 1325

I want to add a greek character to the x-axis of my histogram plot in R. I can write the greek character alone or with the hat, but the problem is that I need this character to be come with a hat and asterisk () together. More specifically, I want the something like hat(phi^). Here is what I have done:

x = rnorm(1000)
hist( x, nclass = 100, cex.lab=1.5, xlab = expression(hat(phi^*)), 
ylab="Frequency", main="", cex.axis=1.5 )

Thanks.

2 Answers

What about using ggplot2 instead of base R. You can then use latex2exp::TeX to use (some) LaTeX expressions in the axes labels.

set.seed(2018)
x = rnorm(1000)

library(ggplot2)
library(latex2exp)

ggplot(data.frame(x = x), aes(x)) +
    geom_histogram(bins = 100) +
    theme_minimal() +
    xlab(TeX("$\\widehat{\\phi^*}$"))

enter image description here

You need to escape the backslashes with an extra backslash and wrap math expressions inside $ delimiters (just as in regular LaTeX inline math). I used \widehat{}, but you can also use hat{} instead.

Here is the best looking solution that I found:

hist( x, nclass = 100, cex.lab=1.5, xlab = expression(hat(phi)~"*"), 
      ylab="Frequency", main="", cex.axis=1.5 )

enter image description here


To get the star under the hat, I don't know of any nice looking solution with base plot functions. I think @Maurits Evers' method is the best compromise between complexity and prettiness of the result.

But here is anyway a more "advanced" (and maybe a little bit over the top, but well...) solution. It is based on this blog post: http://iltabiai.github.io/tips/latex/2015/09/15/latex-tikzdevice-r.html

To make it work, you will need to install the tikzDevice package.

First, load the packages and create the data-set.

library(tikzDevice)
library(ggplot2)
dat <- data.frame(x = rnorm(1000))

Then create a TeX file that will contain the "translation" of your R plot in "tikz" language.

tikz(file = "plot_test.tex", width = 5, height = 5, standAlone = TRUE)
ggplot(dat, aes(x = x)) + 
  geom_histogram(color="white") + theme_bw() +
  labs( x = "$\\widehat{\\phi^*}$")
dev.off()

Then, you can either directly copy or call the LaTeX code into your own LaTeX document (then the standAlone=TRUE argument is not necessary), or you can use these two very useful function to generate a pdf version and see the result.

tools::texi2dvi("plot_test.tex", pdf=TRUE)
system(paste(getOption('pdfviewer'), "plot_test.pdf"))

TikZ result

Related