Home > Software design >  Add special character to persp plot
Add special character to persp plot

Time:09-02

I am using the persp() function to make a 3d plot.

I just want to add a greek letter or math expression to the axes labels, but that has proven to be difficult. I have tried the following, but it didn't work:

rm()
library(graphics)#for 3d plot

beta_grid=c(1,2,3,4)
alpha_grid=c(1,2,3,4)
z=matrix(c(1,2,3,4,5,6,7,8,1,1,1,1,1,1,1,1),4)


labNames <- c('xLab','yLab')
xlab <- bquote(.(labNames[1]) ~ x^2)
ylab <- bquote(.(labNames[2]) ~ y^2)
persp(alpha_grid, beta_grid, z,theta=45, phi=45,xlab = xlab, ylab=ylab)

I have also tried this more obvious solution:

persp(alpha_grid, beta_grid, z,theta=45, phi=45,main=expression(x^2 gamma),xlab=expression(x^2),ylab=expression(gamma))

but as you can see, this only works for the tile of the graph, not for the axes (see figure below).

enter image description here

Any help on how to fix this issue?

CodePudding user response:

According to the docs you cannot use expressions in the axis labels:

xlab, ylab, zlab titles for the axes. N.B. These must be character strings; expressions are not accepted. Numbers will be coerced to character strings.

However, all is not lost. You can get superscript digits and Greek letters via Unicode escape sequences:

xlab <- "x\u00b2"
ylab <- "\u03b3"

persp(alpha_grid, beta_grid, z, theta = 45, phi = 45, 
      xlab = xlab, ylab = ylab, cex.lab = 2)

enter image description here

CodePudding user response:

I think the docs describe the limitation to character strings for xlab and ylab. An alternative is to use rgl::persp3d instead. It doesn't accept bquote(.(labNames[1]) ~ x^2), but it is fine with expression(x^2) and similar:

library(rgl)

beta_grid <- c(1,2,3,4)
alpha_grid <- c(1,2,3,4)
z <- matrix(c(1,2,3,4,5,6,7,8,1,1,1,1,1,1,1,1),4)

persp3d(alpha_grid, beta_grid, z,theta=45, phi=45,
        main=expression(x^2 gamma),
        xlab=expression(x^2),
        ylab=expression(gamma),
        front = "lines",
        back = "lines")

Created on 2022-09-01 with reprex v2.0.2

You'll probably want to customize it a bit; the default view is kind of ugly.

  • Related