3d surface plots with RStudio and Plotly

[This article was first published on Modern Data » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Recently you may have seen how to build a 3d surface plot with Plotly and IPython notebook. Here you can learn the basics of creating a 3d surface plot with Plotly in RStudio.

Just add the Plotly library into your RStudio environment then add a Plotly username and key:

install.packages("plotly") library(plotly) py <- plotly() set_credentials_file(username = 'your_username', key = 'your_key')

To create a surface plot, use two vectors: x and y of length m and n, and a matrix: z of size m*n. In this example, x and y both consist of 100 points ranging from -5 to 4.9.

x_vec = c(seq(-5, 4.9, 0.1))

*note this results in the same dimensions (1 column X 100 rows) as specifying:
x_matrix = matrix(c(x_vec), nrow = 100, ncol = 1)

The size of x is 1 column with 100 rows. In order to multiply x * y to create matrix z with 100 columns and 100 rows, y should be 100 columns with 1 row.

y_matrix = matrix(c(x_vec), nrow = 1, ncol = 100)

To multiply the vertical and horizontal vectors to create matrix z in RStudio, the basic syntax is z = x %*% y. In this example, a function is applied to z to create waves. Below, dimensions x, y, and z are defined. y used here is different than y1 used above because y should be the default, 1 column vector, not 1 row x 100 columns. Type is defined as “surface”.

data <- list(         x = x_vec,         y = x_vec,         z = matrix(c(cos(x_matrix %*% y_matrix) + sin(x_matrix %*% y_matrix)), nrow = 100, ncol = 100),         type = "surface")

Finally, specify layout information and filename:

layout <- list(           title = "Waaaves in r",           scene = list(bgcolor = "rgb(244, 244, 248)")) response <- py$plotly(data,                       kwargs = list(                                 layout = layout,                                 filename = "waves example",                                 fileopt = "overwrite"))

The result will be similar to the interactive 3d plot displayed below:

Creating dashboards or visualizations at your company? Consider Plotly Enterprise for modern intracompany graph and data sharing.

To leave a comment for the author, please follow the link and comment on their blog: Modern Data » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)