# [R] Graphing complex functions

Duncan Murdoch murdoch.duncan at gmail.com
Tue Oct 22 21:49:03 CEST 2013

```On 22/10/2013 1:07 PM, John Van Praag wrote:
> Does R have any facilities, or packages, for graphing complex functions?

I don't think base R does, but if you have a complex-valued function of
a real variable, it wouldn't be hard to write one.

library(rgl)
xvals <- seq(0, 2*pi, len=256)
f <- function(x) cos(x) + 1i * sin(x)
zvals <- f(xvals)
plot3d(xvals, Re(zvals), Im(zvals), type="l")

For the case of a real-valued function of a complex variable, you could
use persp() or persp3d().  For both argument and value being complex,
you'll need 4 dimensions, and that's hard to do nicely, though I suppose
you could overlay contour or perspective plots of the real and imaginary
parts of the value.  For example:

x <- y <- seq(0, 2*pi, len=50)
z <- outer(x, y, function(x,y) x + 1i*y)
zvals <- f(z)
persp3d(x, y, Re(zvals), col="red", alpha=0.5, xlab="Re(z)",
ylab="Im(z)", zlab="f(z)")
surface3d(x, y, Im(zvals), col="blue", alpha=0.5)

Duncan Murdoch

>
> I find that 'curve' does not do the trick. Example:
>
> > f = function(x) cos(x) + 1i * sin(x)
> > curve(f, -pi, pi)
> Error in xy.coords(x, y, xlabel, ylabel, log) :
>    (converted from warning) imaginary parts discarded in coercion
>
> Enter a frame number, or 0 to exit
>
> 1: curve(f, -pi, pi)
> 2: plot(x = x, y = y, type = type, xlab = xlab, ylab = ylab, xlim = xlim,
> log = lg, ...)
> 3: plot.default(x = x, y = y, type = type, xlab = xlab, ylab = ylab, xlim =
> xlim, log = lg, ...)
> 4: xy.coords(x, y, xlabel, ylabel, log)
> 5: .signalSimpleWarning("imaginary parts discarded in coercion",
> quote(xy.coords(x, y, xlabel, ylabel, log)))
> 6: withRestarts({
>      .Internal(.signalCondition(simpleWarning(msg, call), msg, call))
>      .Internal(.dfltWarn(msg, call))
> }, muffleWarning = function() NULL)
> 7: withOneRestart(expr, restarts[[1]])
> 8: doWithOneRestart(return(expr), restart)
> 9: (function ()
> {
>      error()
>      utils::recover()
> })()
>
> Selection:
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help