Plotting a Sphere with Inputs of Radius and center

Hi all,

I read this forum:

I want to know whether there is a way to plot a sphere based on an inputs of:

  1. radius
  2. center of the sphere (x,y,z)

Instead of using sin,cos inputs.

I use this code from the forum:

using Plots

n = 100
u = range(-π, π; length = n)
v = range(0, π; length = n)
x = cos.(u) * sin.(v)'
y = sin.(u) * sin.(v)'
z = ones(n) * cos.(v)'

plotly()
surface(x, y, z)

Plotly() is great it is very interactive.

Would it be OK to define a sphere function:

using Plots; plotlyjs()

function sphere(r, C)   # r: radius; C: center [cx,cy,cz]
    n = 100
    u = range(-π, π; length = n)
    v = range(0, π; length = n)
    x = C[1] .+ r*cos.(u) * sin.(v)'
    y = C[2] .+ r*sin.(u) * sin.(v)'
    z = C[3] .+ r*ones(n) * cos.(v)'
    return x, y, z
end

surface(sphere(2, [1,2,3]))
1 Like

Wow it is great,

I just want to know the mathematics theory / formula for the

x = C[1] .+ r*cos.(u) * sin.(v)'
y = C[2] .+ r*sin.(u) * sin.(v)'
z = C[3] .+ r*ones(n) * cos.(v)'

What is it called? Parametric equations?

Yes, parametric equations of the sphere using spherical coordinates (radial, polar and azimuthal).

Btw, in the post you linked there is a solution using Cartesian coordinates, but more tricky to stitch.

I tried that code too, but there is a black line in the middle of the sphere when using gr()

I learn the parametric equations so I know the mathematical science behind how to create sphere:

u = range(-π, π; length = n)

This has range of -π, π, while out there a source use range of 0, 2π
image

image