3D Scatter Plots in F#

How to make 3D scatter plots in F# with Plotly.


In [1]:
// #r "nuget: Plotly.NET, 2.0.0-preview.6"
// #r "nuget: Plotly.NET.Interactive, 2.0.0-preview.6"

#r "nuget: Plotly.NET, 2.0.0-preview.8"
#r "nuget: Plotly.NET.Interactive, 2.0.0-preview.8"
open Plotly.NET
Installed Packages
  • Plotly.NET, 2.0.0-preview.8
  • Plotly.NET.Interactive, 2.0.0-preview.8

Loading extensions from Plotly.NET.Interactive.dll

Added Kernel Extension including formatters for Plotly.NET charts.

Basic 3D Scatter Plot

Basic 3D Scatter Plot

If Plotly Express does not provide a good starting point, it is also possible to use the more generic go.Scatter3D class from plotly.graph_objects. Like the 2D scatter plot go.Scatter, go.Scatter3d plots individual data in three-dimensional space.

In [2]:
open System

let t = [0. .. 0.5 .. 10.]

let x,y,z =  
    t
    |> List.map (fun i ->
        let i' = float i 
        let r = 10. * Math.Cos (i' / 10.)
        (r*Math.Cos i',r*Math.Sin i',i')
    )
    |> List.unzip3

let scatter3dLine = 
    Chart.Scatter3d(x,y,z,mode = StyleParam.Mode.Markers)
In [3]:
scatter3dLine
Out[3]:

3D Scatter Plot with Colorscaling and Marker Styling

In [4]:
open Plotly.NET 
open Plotly.NET.TraceObjects
open Plotly.NET.LayoutObjects

open System
 
 
let c = [0. .. 0.5 .. 10.]

let x,y,z =  
    c
    |> List.map (fun i ->
        let i' = float i 
        let r = 10. * Math.Cos (i' / 10.)
        (r*Math.Cos i',r*Math.Sin i',i')
    )
    |> List.unzip3

let marker = Marker.init(Size =12,Opacity=0.8, Colorscale = StyleParam.Colorscale.Viridis)
marker?color <- x

let margin =Margin.init(Left =0., Bottom=0.,Top =0., Right  = 0. )
let layout = Layout.init(  Margin=margin)

let scatter3dLine = 
    Chart.Scatter3d(x,y,z,mode = StyleParam.Mode.Markers)
    |> Chart.withMarker marker
    |> Chart.withLayout layout
In [5]:
scatter3dLine
Out[5]: