Skip to content

Commit

Permalink
#265: Add Chart.PointDensity plus tests/docs
Browse files Browse the repository at this point in the history
  • Loading branch information
kMutagene committed Feb 8, 2022
1 parent 5da1b8b commit 8533cbb
Show file tree
Hide file tree
Showing 7 changed files with 244 additions and 11 deletions.
1 change: 1 addition & 0 deletions Plotly.NET.sln
Expand Up @@ -79,6 +79,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "docs", "docs", "{7B09CC0A-F
docs\04_3_contour-plots.fsx = docs\04_3_contour-plots.fsx
docs\04_4_2d-histograms.fsx = docs\04_4_2d-histograms.fsx
docs\04_5_splom.fsx = docs\04_5_splom.fsx
docs\04_6_point-density.fsx = docs\04_6_point-density.fsx
docs\05_0_geo-vs-mapbox.fsx = docs\05_0_geo-vs-mapbox.fsx
docs\05_1_geo-plots.fsx = docs\05_1_geo-plots.fsx
docs\05_2_choropleth-map.fsx = docs\05_2_choropleth-map.fsx
Expand Down
10 changes: 2 additions & 8 deletions docs/04_4_2d-histograms.fsx
Expand Up @@ -60,12 +60,7 @@ let y = Array.init n (fun i -> ((step i)**6.) + (0.3 * (normal (rnd) 0. 2.) ))
A Histogram2D chart can be created using the `Chart.Histogram2D` or `Chart.Histogram2DContour` functions.
*)

let histogramContour =
[
Chart.Histogram2DContour (x,y,ContourLine=Line.init(Width=0.))
Chart.Point(x,y,Opacity=0.3)
]
|> Chart.combine
let histogramContour = Chart.Histogram2DContour (x,y,ContourLine=Line.init(Width=0.))

(*** condition: ipynb ***)
#if IPYNB
Expand All @@ -76,8 +71,7 @@ histogramContour
histogramContour |> GenericChart.toChartHTML
(*** include-it-raw ***)

let histogram2D =
Chart.Histogram2D (x,y)
let histogram2D = Chart.Histogram2D (x,y)

(*** condition: ipynb ***)
#if IPYNB
Expand Down
85 changes: 85 additions & 0 deletions docs/04_6_point-density.fsx
@@ -0,0 +1,85 @@
(**
---
title: PointDensity
category: Distribution Charts
categoryindex: 5
index: 6
---
*)

(*** hide ***)

(*** condition: prepare ***)
#r "nuget: Newtonsoft.JSON, 13.0.1"
#r "nuget: DynamicObj, 1.0.1"
#r "../bin/Plotly.NET/netstandard2.0/Plotly.NET.dll"

(*** condition: ipynb ***)
#if IPYNB
#r "nuget: Plotly.NET, {{fsdocs-package-version}}"
#r "nuget: Plotly.NET.Interactive, {{fsdocs-package-version}}"
#endif // IPYNB

(**
# PointDensity
[![Binder]({{root}}img/badge-binder.svg)](https://mybinder.org/v2/gh/plotly/Plotly.NET/gh-pages?filepath={{fsdocs-source-basename}}.ipynb) 
[![Script]({{root}}img/badge-script.svg)]({{root}}{{fsdocs-source-basename}}.fsx) 
[![Notebook]({{root}}img/badge-notebook.svg)]({{root}}{{fsdocs-source-basename}}.ipynb)
*Summary:* This example shows how to create PointDensity plots in F#.
let's first create some data for the purpose of creating example charts:
*)

let rnd = new System.Random()
let x = [for i in 0 .. 100 -> rnd.NextDouble()]
let y = [for i in 0 .. 100 -> rnd.NextDouble()]

(**
`Chart.PointDensity` is a combination of a scatter plot and a histogram2dcontour.
It helps assessing the 2 dimensional distribution of a scatter plot by adding density contours based on the same data.
*)

open Plotly.NET

let pointDensityChart =
Chart.PointDensity(x,y)

(*** condition: ipynb ***)
#if IPYNB
pointDensityChart
#endif // IPYNB

(***hide***)
pointDensityChart |> GenericChart.toChartHTML
(***include-it-raw***)

(**
## More styled example
This example shows the usage of some of the styling possibility using `Chart.PointDensity`.
*)

let pointDensityChartStyled =
Chart.PointDensity(
x,
y,
PointMarkerColor = Color.fromKeyword Purple,
PointMarkerSymbol = StyleParam.MarkerSymbol.X,
PointMarkerSize = 4,
ColorScale = StyleParam.Colorscale.Viridis,
ColorBar = ColorBar.init(Title = Title.init("Density")),
ShowContourLabels = true
)

(*** condition: ipynb ***)
#if IPYNB
pointDensityChartStyled
#endif // IPYNB

(***hide***)
pointDensityChartStyled |> GenericChart.toChartHTML
(***include-it-raw***)
6 changes: 3 additions & 3 deletions src/Plotly.NET.ImageExport/PuppeteerSharpRenderer.fs
Expand Up @@ -81,7 +81,7 @@ type PuppeteerSharpRenderer() =
let fetchAndLaunchBrowserAsync () =
async {
match PuppeteerSharpRendererOptions.localBrowserExecutablePath with
| None ->
| None ->
use browserFetcher = new BrowserFetcher()

let! revision = browserFetcher.DownloadAsync() |> Async.AwaitTask
Expand All @@ -95,9 +95,9 @@ type PuppeteerSharpRenderer() =
| Some p ->
let launchOptions =
PuppeteerSharpRendererOptions.launchOptions

launchOptions.ExecutablePath <- p

return! Puppeteer.LaunchAsync(launchOptions) |> Async.AwaitTask
}

Expand Down
1 change: 1 addition & 0 deletions src/Plotly.NET/ChartAPI/Chart.fs
Expand Up @@ -1227,6 +1227,7 @@ type Chart =
?BackgroundColor = BackgroundColor,
?ShowBackground = ShowBackground
)

Chart.withYAxis (yaxis, ?Id = Id)


Expand Down
111 changes: 111 additions & 0 deletions src/Plotly.NET/ChartAPI/Chart2D.fs
Expand Up @@ -5018,3 +5018,114 @@ module Chart2D =
?ShowUpperHalf = ShowUpperHalf,
?UseDefaults = UseDefaults
)

/// <summary>
/// Creates a point density plot - a combination of a Scatter plot and Histogram2DContour.
///
/// Additionally to plotting the (x,y) data as points on a 2D plane, a density contour plot is computed by grouping a set of points specified by their x and y coordinates into bins, and applying a count aggregation function to compute the value to be used to compute contours.
/// The sample data from which statistics are computed is set in `x` and `y` (where `x` and `y` represent marginal distributions, binning is set in `xbins` and `ybins` in this case). The resulting distribution is visualized as a contour plot.
///
/// </summary>
/// <param name="x">Sets the x coordinates of the plotted data as well as the sample data to be binned on the x axis.</param>
/// <param name="y">Sets the y coordinates of the plotted data as well as the sample data to be binned on the y axis.</param>
/// <param name="PointOpacity">Sets the opacity of the point trace.</param>
/// <param name="PointMarkerColor">Sets the marker color of the point trace.</param>
/// <param name="PointMarkerSymbol">Sets the marker symbol of the point trace.</param>
/// <param name="PointMarkerSize">Sets the marker size of the point trace.</param>
/// <param name="ContourLineColor">Sets the color of the contour lines of the histogram2dcontour trace.</param>
/// <param name="ContourLineSmoothing">Sets the smoothing of the contour lines of the histogram2dcontour trace.</param>
/// <param name="ContourLineWidth">Sets the width of the contour lines of the histogram2dcontour trace.</param>
/// <param name="ShowContourLines">Wether or not to show contour lines</param>
/// <param name="ShowContourLabels">Wether or not to show contour labels</param>
/// <param name="ContourColoring">Determines the coloring method showing the contour values. If "fill", coloring is done evenly between each contour level If "heatmap", a heatmap gradient coloring is applied between each contour level. If "lines", coloring is done on the contour lines. If "none", no coloring is applied on this trace.</param>
/// <param name="NContours">Sets the maximum number of contour levels. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is "true" or if `contours.size` is missing.</param>
/// <param name="HistNorm">Specifies the type of normalization used for this histogram trace. If "", the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If "percent" / "probability", the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points (here, the sum of all bin HEIGHTS equals 100% / 1). If "density", the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval (here, the sum of all bin AREAS equals the total number of sample points). If "probability density", the area of each bar corresponds to the probability that an event will fall into the corresponding bin (here, the sum of all bin AREAS equals 1).</param>
/// <param name="ContourOpacity">Sets the opacity of the histogram2dcontour trace.</param>
/// <param name="ColorBar">Sets the color bar.</param>
/// <param name="ColorScale">Sets the colorscale of the histogram2dcontour trace.</param>
/// <param name="ShowScale">wether or not to show the colorbar</param>
/// <param name="UseDefaults">If set to false, ignore the global default settings set in `Defaults`</param>
[<Extension>]
static member PointDensity
(
x: seq<#IConvertible>,
y: seq<#IConvertible>,
?PointOpacity: float,
?PointMarkerColor: Color,
?PointMarkerSymbol: StyleParam.MarkerSymbol,
?PointMarkerSize: int,
?ContourLineColor: Color,
?ContourLineSmoothing: float,
?ContourLineWidth: float,
?ShowContourLines: bool,
?ShowContourLabels: bool,
?ContourColoring: StyleParam.ContourColoring,
?NContours: int,
?HistNorm: StyleParam.HistNorm,
?ContourOpacity: float,
?ColorBar: ColorBar,
?ColorScale: StyleParam.Colorscale,
?ShowScale: bool,
?UseDefaults: bool
) =

let showContourLines = defaultArg ShowContourLines false
let pointOpacity = defaultArg PointOpacity 0.3

let contourColoring =
defaultArg ContourColoring StyleParam.ContourColoring.Fill

let useDefaults = defaultArg UseDefaults true

let contourLineWidth =
ContourLineWidth |> Option.map (fun v -> if showContourLines then v else 0.) |> Option.defaultValue 0.

let marker =
Marker.init (?Color = PointMarkerColor, ?Symbol = PointMarkerSymbol, ?Size = PointMarkerSize)

let pointTrace =
Trace2D.initScatter (
Trace2DStyle.Scatter(
X = x,
Y = y,
Mode = StyleParam.Mode.Markers,
Marker = marker,
Opacity = pointOpacity
)
)

let contourLine =
Plotly.NET.Line.init (
?Color = ContourLineColor,
?Smoothing = ContourLineSmoothing,
Width = contourLineWidth
)

let contours =
Contours.init (
ShowLines = showContourLines,
Coloring = contourColoring,
?ShowLabels = ShowContourLabels
)

let densityContourTrace =
Trace2D.initHistogram2DContour (
Trace2DStyle.Histogram2DContour(
X = x,
Y = y,
Contours = contours,
Line = contourLine,
?NContours = NContours,
?ColorBar = ColorBar,
?ColorScale = ColorScale,
?ShowScale = ShowScale,
?HistNorm = HistNorm,
?Opacity = ContourOpacity
)
)

[
densityContourTrace :> Trace
pointTrace :> Trace
]
|> GenericChart.ofTraceObjects useDefaults

0 comments on commit 8533cbb

Please sign in to comment.