A simple Histogram chart
This demo shows how we can take an array of plain values, and build a Histogram chart - a distribution of values as a column series.
Open in:New tab
/** * --------------------------------------- * This demo was created using amCharts 4. * * For more information visit: * https://www.amcharts.com/ * * Documentation is available at: * https://www.amcharts.com/docs/v4/ * --------------------------------------- */
am4core.useTheme(am4themes_animated);
// Source datavar data = [ 3.5, 3, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3, 3, 4, 4.4, 3.9, 3.5, 3.8, 3.8, 3.4, 3.7, 3.6, 3.3, 3.4, 3, 3.4, 3.5, 3.4, 3.2, 3.1, 3.4, 4.1, 4.2, 3.1, 3.2, 3.5, 3.6, 3, 3.4, 3.5, 2.3, 3.2, 3.5, 3.8, 3, 3.8, 3.2, 3.7, 3.3, 3.2, 3.2, 3.1, 2.3, 2.8, 2.8, 3.3, 2.4, 2.9, 2.7, 2, 3, 2.2, 2.9, 2.9, 3.1, 3, 2.7, 2.2, 2.5, 3.2, 2.8, 2.5, 2.8, 2.9, 3, 2.8, 3, 2.9, 2.6, 2.4, 2.4, 2.7, 2.7, 3, 3.4, 3.1, 2.3, 3, 2.5, 2.6, 3, 2.6, 2.3, 2.7, 3, 2.9, 2.9, 2.5, 2.8, 3.3, 2.7, 3, 2.9, 3, 3, 2.5, 2.9, 2.5, 3.6, 3.2, 2.7, 3, 2.5, 2.8, 3.2, 3, 3.8, 2.6, 2.2, 3.2, 2.8, 2.8, 2.7, 3.3, 3.2, 2.8, 3, 2.8, 3, 2.8, 3.8, 2.8, 2.8, 2.6, 3, 3.4, 3.1, 3, 3.1, 3.1, 3.1, 2.7, 3.2, 3.3, 3, 2.5, 3, 3.4, 3];
var maxCols = 10;function getHistogramData(source) { // Init var data = []; var min = Math.min.apply(null, source); var max = Math.max.apply(null, source); var range = max - min; var step = range / maxCols;
// Create items for (var i = 0; i < maxCols; i++) { var from = min + i * step; var to = min + (i + 1) * step; data.push({ from: from, to: to, count: 0 }); }
// Calculate range of the values for (var i = 0; i < source.length; i++) { var value = source[i]; var item = data.find(function (el) { return value >= el.from && value <= el.to; }); item.count++; }
return data;}
// Create chart instancevar chart = am4core.create("chartdiv", am4charts.XYChart);
// Add datachart.data = getHistogramData(data);
// Create axesvar categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());categoryAxis.dataFields.category = "from";categoryAxis.renderer.grid.template.location = 0;categoryAxis.renderer.minGridDistance = 30;
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
// Create seriesvar series = chart.series.push(new am4charts.ColumnSeries());series.dataFields.valueY = "count";series.dataFields.categoryX = "from";series.columns.template.tooltipText = "{from} - {to}\n[bold]Count: {count}[/]";<div id="chartdiv"></div>body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";}
#chartdiv { width: 100%; height: 500px;}histogram