Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot complex numbers in R with ggplot2

Is there a way to plot complex number in an elegant way with ggplot2? plot {graphics} does it for my snowflake vector of values, but I would prefer to have it in ggplot2. The ggplot2 tutorials I came across do not mention a complex word.

snowflake <- c(complex(real=0, imaginary=0),
               complex(real=1/3, imaginary=0),
               complex(real=1/2, imaginary=(3^(1/2))/6),
               complex(real=2/3, imaginary=0),
               complex(real=1, imaginary=0))
plot(snowflake, type="l")

enter image description here

UPDATE

Unfortunately, It appears the suggestion below does not work with my more complex figures - plot {graphics} lines the points in the order given by the vector of values, whereas qplot does not. Se the example below:

my.snowflake <- c( 0.0000000+0.0000000i, 0.1111111+0.0000000i,
                   0.1666667+0.0962250i, 0.2222222+0.0000000i,
                   0.3333333+0.0000000i, 0.3888889+0.0962250i,
                   0.3333333+0.1924501i, 0.4444444+0.1924501i,
                   0.5000000+0.2886751i, 0.5555556+0.1924501i,
                   0.6666667+0.1924501i, 0.6111111+0.0962250i,
                   0.6666667+0.0000000i, 0.7777778+0.0000000i,
                   0.8333333+0.0962250i, 0.8888889+0.0000000i,
                   1.0000000+0.0000000i)

Results:

plot(my.snowflake, type = "l")

enter image description here

qplot(Re(my.snowflake), Im(my.snowflake), geom="line")

enter image description here

like image 818
Marta Karas Avatar asked Jan 23 '14 22:01

Marta Karas


1 Answers

Just extract the real and imaginary parts of the number with Re and Im, then pass them to ggplot2 as x and y:

qplot(Re(snowflake), Im(snowflake), geom="path")

The OP's plot in ggplot2

In your update, you pointed out that geom_line doesn't work for a nontrivial case, so you'll want to use geom_path instead, which connects the points in the order they're provided. Here's your more complex example with geom_path:

The OP's updated plot in ggplot2, with geom_path

like image 176
Peyton Avatar answered Oct 31 '22 12:10

Peyton