# 'How can I plot a sphere with plotly in R?

I would like to plot a sphere in the following plot:

And that is the code for it:

```
library(plotly)
fig <- plot_ly(mtcars, x = ~wt, y = ~hp, z = ~qsec,
marker = list(color = ~mpg, colorscale = c('#FFE1A1', '#683531'), showscale = TRUE))
fig <- fig %>% add_markers()
fig <- fig %>% layout(scene = list(xaxis = list(title = 'Weight'),
yaxis = list(title = 'Gross horsepower'),
zaxis = list(title = '1/4 mile time')),
annotations = list(
x = 1.13,
y = 1.05,
text = 'Miles/(US) gallon',
xref = 'paper',
yref = 'paper',
showarrow = FALSE
)) %>% add_markers(x = 2.8, y = 120, z = 20, color="red", marker=list(size=30,
opacity = .65,
line=list(width=2,
color='black')))
fig
```

At the moment my best version only contains a 2D circle. How could I integrate a 3d/wireframe sphere into it using plotly R-version?

## Solution 1:^{[1]}

A sphere is an isosurface. You can plot an isosurface with plotly but it is a bit slow, I prefer to use the misc3d package.

```
library(plotly)
f <- function(x, y, z){
x^2 + y^2 + z^2
}
R <- 2 # radius
x <- y <- z <- seq(-R, R, length.out = 100)
g <- expand.grid(x = x, y = y, z = z)
voxel <- array(with(g, f(x, y, z)), dim = c(100, 100, 100))
library(misc3d)
cont <- computeContour3d(voxel, level = R^2, x = x, y = y, z = z)
idx <- matrix(0:(nrow(cont)-1), ncol=3, byrow=TRUE)
plot_ly(
x = cont[, 1], y = cont[, 2], z = cont[, 3],
i = idx[, 1], j = idx[, 2], k = idx[, 3],
type = "mesh3d"
) %>% layout(scene = list(aspectmode = "data"))
```

## Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution | Source |
---|---|

Solution 1 | StÃ©phane Laurent |