This is the assignment for the third week of the Developing Data Products course on Coursera. Three plots are generated with Plotly, one 2D scatterplot, one 3D scatterplot of two particular data sets and one simple flat surface plot which can be used to see how plot_ly interprets the matrix object that is give to add_surface().
knitr::opts_chunk$set(verbose = FALSE, message = FALSE, warning = FALSE)
suppressPackageStartupMessages(library(ggplot2))
suppressPackageStartupMessages(library(plotly))
## Warning: package 'plotly' was built under R version 3.3.3
x_coord <- -100:100
y_coord <- -100:100
z_coord <- (x_coord^2)/3000 - (3*x_coord)/1000 + 3*y_coord/1000 + 5*sin(x_coord+y_coord)
# We can create a matrix by binding the data sets, just for playing around with a 3D plot
matrix <- cbind(x_coord,y_coord,z_coord)
plot_ly(x= x_coord, y= z_coord, mode="markers", color = z_coord)
This plot corresponds with the plane x=y through the plane for the function z(x,y). It is a nice play of squares, a linear term and a mixed sinusoid term.
We can now use to plot a surface (3D) with plotly. In the matrix the first row and column are taken for the x-axis and y-axis. One can clearly see the sinusoidal character along the x=2 line (see above). For x=1 (first column), the value is simply linear (from 1-201 points ranging from -100 to 100, the y_coord) and one can see that plotly is connecting this while smoothing it greatly (from a sinusoid to a flat line). This is a caveat for interpreting plots with plot_ly !! The plotting code is actually showing patterns which are absolutely not on basis of the data points (of which there are only two series on the edges). All the surface between the edges is an artifact of the software.
p <- plot_ly() %>% add_surface(z = ~matrix)
p
Finally we can generate a flat surface and see how plot_ly is interpreting the input matrix, see for yourself.
matrix2 <- cbind(c(1,2,3,4,5), c(2,3,4,5,6), c(3,4,5,6,7), c(4,5,6,7,8))
q <- plot_ly() %>% add_surface(z = ~matrix2)
q