0

Hi I have written a simple function to make a plot of a-th polynomial of x in ggplot2. Following is my code:

PlotPower <- function(x,a){
y <- x^a
dat <- data.frame(x,y)
f <- function(x) x^a
ggplot(dat,aes(x,y)) + geom_point() + stat_function(fun = f, colour = "red") +
    scale_x_continuous(breaks = pretty(dat$x, n = 10)) +
    scale_y_continuous(breaks = pretty(dat$y, n = 10)) +
                 labs(x = "x", y = expression(x^a), title = "Polynomial plot of x")
}

Now say I am calling PlotPower(1:10,3), the plot looks like enter image description here

But I want y axis label to automatically change into x^3. I have not been able to do that. I have tried to write

labs(y = "x"^a)

but I am getting error message: Error in "x"^a : non-numeric argument to binary operator, which is expected as I am mixing a character variable with a numerical variable.

Please help me writing the ggplot2 y axis label properly inside my PlotPower function so that with whatever "a" I call the PlotPower function, I get y axis label as x^a, where x is the character x but a is the value of argument a.

B Misra
  • 71
  • 1
  • 3

1 Answers1

2

Replace the expression with bquote. The variable inside .(a) is the one that gets substituted. For more variations -like the ones mentioned in the comments- look at this answer.

PlotPower <- function(x,a){
  y <- x^a
  dat <- data.frame(x,y)
  ylab = paste("x", a, sep='^')
  f <- function(x) x^a
  ggplot(dat,aes(x,y)) + geom_point() + stat_function(fun = f, colour = "red") +
    scale_x_continuous(breaks = pretty(dat$x, n = 10)) +
    scale_y_continuous(breaks = pretty(dat$y, n = 10)) +
    labs(x = "x", y = bquote(x^.(a)), title = "Polynomial plot of x")
}

enter image description here

Gene Burinsky
  • 9,478
  • 2
  • 21
  • 28