Skip to content

Commit

Permalink
Initial
Browse files Browse the repository at this point in the history
  • Loading branch information
Niilo Keinänen committed Aug 8, 2023
0 parents commit 7e84fba
Show file tree
Hide file tree
Showing 12 changed files with 415 additions and 0 deletions.
31 changes: 31 additions & 0 deletions .github/workflows/gh-pages-deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: GitHub Pages

on:
push:
branches: [master]

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2

- name: Use Node.js 16.x
uses: actions/setup-node@v1
with:
node-version: "16.x"

- name: Build
env:
LCJS_LICENSE: ${{ secrets.LCJS_DEPLOY_LICENSE }}
run: |
npm install
npm run build
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./dist
publish_branch: gh-pages
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
dist
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 LightningChart Ltd.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
131 changes: 131 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
# JavaScript Histogram of Gaussian Distribution.

![JavaScript Histogram of Gaussian Distribution.](histogramGaussian-darkGold.png)

This demo application belongs to the set of examples for LightningChart JS, data visualization library for JavaScript.

LightningChart JS is entirely GPU accelerated and performance optimized charting library for presenting massive amounts of data. It offers an easy way of creating sophisticated and interactive charts and adding them to your website or web application.

The demo can be used as an example or a seed project. Local execution requires the following steps:

- Make sure that relevant version of [Node.js](https://nodejs.org/en/download/) is installed
- Open the project folder in a terminal:

npm install # fetches dependencies
npm start # builds an application and starts the development server

- The application is available at _http://localhost:8080_ in your browser, webpack-dev-server provides hot reload functionality.


## Description

Example showcasing LightningChart Histogram visualization using Bar Chart.

Bar Chart can be used as a histogram by calculating the bins manually using the following function:

```js
const calculateHistogramBins = (data, numberOfBins) => {
const minValue = Math.min(...data)
const maxValue = Math.max(...data)
const binSize = (maxValue - minValue) / numberOfBins

// Calculate bin intervals
const bins = []
for (let i = 0; i < numberOfBins; i++) {
const binStart = minValue + i * binSize
const binEnd = minValue + (i + 1) * binSize
bins.push({
binStart: parseFloat(binStart.toFixed(2)),
binEnd: parseFloat(binEnd.toFixed(2)),
values: Array(),
})
}
bins[numberOfBins - 1].binEnd = maxValue

// Map data to bins
data.forEach((value) => {
const binIndex = Math.floor((value - minValue) / binSize)
if (binIndex >= 0 && binIndex < numberOfBins) {
bins[binIndex].values.push(value)
}
})

// Create input data for bar chart
const barChartData = []
bins.forEach((interval) => {
barChartData.push({
category: `${(interval.binStart + (interval.binStart === minValue ? 0 : 0.01)).toFixed(2)}${
interval.binEnd < 0 ? `(${interval.binEnd.toFixed(2)})` : interval.binEnd.toFixed(2)
}`,
value: interval.values.length,
})
})
return barChartData
}
```

In this example, a normally distributed dataset is generated by the [Box–Muller transform method](https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform):

```js
const generateGaussianRandom = (length) => {
const samples = []
for (let i = 0; i < length; i++) {
let u = 0,
v = 0,
s = 0
while (s === 0 || s >= 1) {
u = Math.random() * 2 - 1
v = Math.random() * 2 - 1
s = u * u + v * v
}
const temp = Math.sqrt((-2 * Math.log(s)) / s)
const sample = u * temp
samples.push(sample)
}
return samples
}
```

In order to preserve the bell curve shape, automatic sorting has to be turned off by `barChart.setSorting(BarChartSorting.Disabled)`

The number of histogram bins can be changed dynamically by the user using the HTML number input. The chart updates automatically from these interactions.


## API Links

* [Bar Chart]
* [Bar Chart Bar]
* [Bar Chart Value Axis ]
* [Bar Chart Category Axis]
* [Bar Chart Types]
* [Bar Chart Sorting]


## Support

If you notice an error in the example code, please open an issue on [GitHub][0] repository of the entire example.

Official [API documentation][1] can be found on [LightningChart][2] website.

If the docs and other materials do not solve your problem as well as implementation help is needed, ask on [StackOverflow][3] (tagged lightningchart).

If you think you found a bug in the LightningChart JavaScript library, please contact [email protected].

Direct developer email support can be purchased through a [Support Plan][4] or by contacting [email protected].

[0]: https://github.com/Arction/
[1]: https://lightningchart.com/lightningchart-js-api-documentation/
[2]: https://lightningchart.com
[3]: https://stackoverflow.com/questions/tagged/lightningchart
[4]: https://lightningchart.com/support-services/

© LightningChart Ltd 2009-2022. All rights reserved.


[Bar Chart]: https://lightningchart.com/js-charts/api-documentation/v4.2.0/interfaces/BarChart.html
[Bar Chart Bar]: https://lightningchart.com/js-charts/api-documentation/v4.2.0/
[Bar Chart Value Axis ]: https://lightningchart.com/js-charts/api-documentation/v4.2.0/classes/BarChartValueAxis.html
[Bar Chart Category Axis]: https://lightningchart.com/js-charts/api-documentation/v4.2.0/classes/BarChartCategoryAxis.html
[Bar Chart Types]: https://lightningchart.com/js-charts/api-documentation/v4.2.0/
[Bar Chart Sorting]: https://lightningchart.com/js-charts/api-documentation/v4.2.0/

Binary file added histogramGaussian-cyberSpace.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added histogramGaussian-darkGold.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added histogramGaussian-light.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added histogramGaussian-lightNature.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added histogramGaussian-turquoiseHexagon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
26 changes: 26 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"version": "2.0.0",
"scripts": {
"build": "webpack --mode production",
"start": "webpack serve"
},
"license": "MIT",
"private": true,
"main": "./src/index.js",
"devDependencies": {
"clean-webpack-plugin": "^4.0.0",
"copy-webpack-plugin": "^10.0.0",
"html-webpack-plugin": "^5.5.0",
"webpack": "^5.64.4",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.6.0",
"webpack-stream": "^7.0.0"
},
"dependencies": {
"@arction/lcjs": "^4.1.1",
"@arction/xydata": "^1.4.0"
},
"lightningChart": {
"eID": "1400"
}
}
134 changes: 134 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
* A histogram of a normally distributed data.
*/

const lcjs = require('@arction/lcjs')

const {
lightningChart,
AxisTickStrategies,
BarChartTypes,
BarChartSorting,
Themes
} = lcjs

const numberOfBins = 100
const numberOfDataPoints = 50000

// Function for generating normally distributed data
const generateGaussianRandom = (length) => {
const samples = []
for (let i = 0; i < length; i++) {
let u = 0, v = 0, s = 0
while (s === 0 || s >= 1) {
u = Math.random() * 2 - 1
v = Math.random() * 2 - 1
s = u * u + v * v
}
const temp = Math.sqrt(-2 * Math.log(s) / s)
const sample = u * temp
samples.push(sample)
}
return samples
}

// Function for calculating the histogram bins from 1D numerical array
const calculateHistogramBins = (data, numberOfBins) => {
const minValue = Math.min(...data)
const maxValue = Math.max(...data)
const binSize = (maxValue - minValue) / numberOfBins

// Calculate bin intervals
const bins = []
for (let i = 0; i < numberOfBins; i++) {
const binStart = minValue + i * binSize
const binEnd = minValue + (i + 1) * binSize
bins.push({
binStart: Math.round(binStart * 100) / 100,
binEnd: Math.round(binEnd * 100) / 100,
values: Array(),
})
}
bins[numberOfBins - 1].binEnd = maxValue

// Map data to bins
data.forEach(value => {
const binIndex = Math.floor((value - minValue) / binSize);
if (binIndex >= 0 && binIndex < numberOfBins) {
bins[binIndex].values.push(value);
}
})

// Create input data for bar chart
const barChartData = []
bins.forEach(interval => {
barChartData.push({
category: `${
(interval.binStart + (interval.binStart === minValue ? 0 : 0.01)).toFixed(2)}${
interval.binEnd < 0 ? `(${interval.binEnd.toFixed(2)})` : interval.binEnd.toFixed(2)}`,
value: interval.values.length
})
})
return barChartData
}

// Generate the data
const values = generateGaussianRandom(numberOfDataPoints)
const histogramData = calculateHistogramBins(values, numberOfBins)

const barChart = lightningChart().BarChart({
// theme: Themes.darkGold
type: BarChartTypes.Vertical
})
.setTitle('Histogram')
.setSorting(BarChartSorting.Disabled)
.setValueLabels(undefined)
.setData(histogramData)
.setCursorResultTableFormatter((builder, category, value, bar) => builder
.addRow('Range:', '', category)
.addRow('Amount of values:', '', bar.chart.valueAxis.formatValue(value))
)

const barDiv = barChart.engine.container

const label = document.createElement('label')
barDiv.append(label)
label.innerHTML = "Number of bins:"
label.style.position = "relative"

const binInput = document.createElement('input')
barDiv.append(binInput)
barChart.setTitleMargin({top: 25, bottom: -10})
binInput.type = "number"
binInput.min = "1"
binInput.max = "1000"
binInput.value = "100"
binInput.style.position = "relative"
binInput.style.height = "5%"

binInput.addEventListener('input', () => {
const inputValue = parseInt(binInput.value)
if (Number.isInteger(inputValue) && inputValue > 0 && inputValue <= 1000) {
barChart.setData([])
const histogramData = calculateHistogramBins(values, inputValue)
barChart.setData(histogramData).setSorting(BarChartSorting.Disabled)
}
})

// Enable grid lines
barChart.valueAxis.setTickStrategy(AxisTickStrategies.Numeric, ticks =>
ticks.setMajorTickStyle(major =>
major.setGridStrokeStyle(
barChart.getTheme().xAxisNumericTicks.majorTickStyle.gridStrokeStyle
)
).setMinorTickStyle(( tickStyle ) =>
tickStyle.setGridStrokeStyle(
barChart.getTheme().yAxisNumericTicks.minorTickStyle.gridStrokeStyle
)
)
)

// Set same color for all bars
const bars = barChart.getBars()
const fillSTyle = bars[0].getFillStyle()
bars.forEach(bar => { bar.setFillStyle(fillSTyle) })
Loading

0 comments on commit 7e84fba

Please sign in to comment.