Instead of iterating through all the data, we can leverage the chart's built-in calculations for min and max values on each value axis. By tapping into these auto-calculated values, we can easily add Guides to highlight the highest and lowest points.
The key here is to utilize the chart's "rendered" event. This event triggers after the chart is constructed, ensuring that the minimum and maximum values are already determined.
Within the value axis object, we have access to properties such as maxReal
and minReal
, which we can use to create Guides. These guides will visually display the highest and lowest points on the chart.
Below is a snippet of the code implementation:
chart.addListener( "rendered", function( event ) {
// retrieve the chart and value axis
var chart = event.chart;
var axis = chart.valueAxes[0];
// create guide for max value
var guideMax = new AmCharts.Guide();
guideMax.value = guideMax.label = axis.maxReal;
guideMax.lineAlpha = 0.2;
guideMax.lineThickness = 2;
guideMax.lineColor = guideMax.color = "#00cc00";
axis.addGuide(guideMax);
// create guide for min value
var guideMin = new AmCharts.Guide();
guideMin.value = guideMin.label = axis.minReal;
guideMin.lineAlpha = 0.2;
guideMin.lineThickness = 2;
guideMin.lineColor = guideMin.color = "#cc0000";
axis.addGuide(guideMin);
} );
For a fully functional demonstration, refer to the complete working code example of the chart below:
// Chart configuration script
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"path": "http://www.amcharts.com/lib/3/",
"dataProvider": [
// Data entries...
],
"valueAxes": [{}],
"graphs": [{
// Graph configurations...
}],
"chartCursor": {
// Cursor settings...
},
"dataDateFormat": "YYYY",
"categoryField": "year",
"categoryAxis": {
// Category axis settings...
}
});
// Event listener to add guides after rendering
chart.addListener("rendered", function(event) {
var chart = event.chart;
var axis = chart.valueAxes[0];
// create guide for max value
var guideMax = new AmCharts.Guide();
guideMax.value = guideMax.label = axis.maxReal;
guideMax.lineAlpha = 0.2;
guideMax.lineThickness = 2;
guideMax.lineColor = guideMax.color = "#00cc00";
axis.addGuide(guideMax);
// create guide for min value
var guideMin = new AmCharts.Guide();
guideMin.value = guideMin.label = axis.minReal;
guideMin.lineAlpha = 0.2;
guideMin.lineThickness = 2;
guideMin.lineColor = guideMin.color = "#cc0000";
axis.addGuide(guideMin);
});
#chartdiv {
width: 100%;
height: 500px;
}
<script src="http://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="http://www.amcharts.com/lib/3/serial.js"></script>
<script src="http://www.amcharts.com/lib/3/themes/light.js"></script>
<div id="chartdiv"></div>