Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dash.NET interactive notebook example version 2
#!fsharp
#r "nuget:Dash.NET.Interactive,0.2.0-alpha.4"
#!fsharp
open System.Net
// Download Iris dataset
let webClient = new WebClient()
let irisDataSet = webClient.DownloadString("https://raw.githubusercontent.com/dotnet/machinelearning/main/test/data/iris.data")
// Parse it into workable parts
let parts = irisDataSet.Split("\n",StringSplitOptions.RemoveEmptyEntries)
let parseLine(x:string) =
let xxx = x.Split(",") in (Convert.ToDecimal xxx.[0],Convert.ToDecimal xxx.[1],Convert.ToDecimal xxx.[2],Convert.ToDecimal xxx.[3],xxx.[4])
let parsed = Seq.map parseLine parts
let scale = 5
let spec = Seq.map (fun (a,b,_,_,x) -> x) parsed
// map species to different colors
let colorMap = function | "Iris-setosa" -> "#4287f5" | "Iris-versicolor" -> "#cb23fa" | "Iris-virginica" -> "#23fabd"
#!fsharp
// Learn more about Dash.NET at https://plotly.github.io/Dash.NET/
open Dash.NET.Suave
open Dash.NET.Html
open Dash.NET.DCC
open Dash.NET
open Plotly.NET
// Use plotly charts
let scatterPlot low high =
let filtered = Seq.filter (fun (a,b,c,d,e) -> d > low && d < high) parsed
let points = Seq.map (fun (a,b,_,_,_) -> a,b) filtered
let petal_length = Seq.map (fun (a,b,c,d,e) -> scale*int(c)) filtered
let markers = TraceObjects.Marker.init(MultiSize=petal_length)
markers?color <- Seq.map colorMap spec
Chart.Scatter(points,StyleParam.Mode.Markers)
|> Chart.withMarker markers
|> Chart.withTitle("Iris Dataset")
|> Chart.withXAxisStyle("Sepal Length")
|> Chart.withYAxisStyle("Sepal Width")
|> GenericChart.toFigure
// Layout for our dash app
let myLayout =
Html.div [
Attr.children [
Graph.graph "my-graph-id" [];
Html.p [ Attr.children "Petal Width:" ]
RangeSlider.rangeSlider "range-slider" [
RangeSlider.Attr.min 0.
RangeSlider.Attr.max 2.5
RangeSlider.Attr.step 0.1
RangeSlider.Attr.marks (
[ 0.; 2.5 ]
|> List.map (fun v -> v, v |> sprintf "%g" |> RangeSlider.Mark.Value)
|> Map.ofList
)
RangeSlider.Attr.value [ 0.5; 2. ]
RangeSlider.Attr.tooltip <|
RangeSlider.TooltipOptions.init (
alwaysVisible = true,
placement = RangeSlider.TooltipPlacement.Bottom
)
]
]
]
let callback =
let outputTarget = "my-graph-id" @. CustomProperty "figure"
Callback.singleOut(
"range-slider" @. Value,
outputTarget,
(fun (sliderRange: decimal []) ->
let low, high =
let r1 = sliderRange.[0]
let r2 = sliderRange.[1]
if r1 < r2 then r1, r2 else r2, r1
outputTarget => scatterPlot low high
),
PreventInitialCall = false
)
let dashApp =
DashApp.initDefault()
|> DashApp.withLayout myLayout
|> DashApp.addCallback callback
// display the application inside the notebook
dashApp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment