javascriptamcharts5

AmCharts v5: pre-zooming date axis


I am setting up a candlestick chart from this example:

https://www.amcharts.com/demos/candlestick-chart/

What I am trying to do is to pre-zoom the chart to the last 10% of the available data. In the documentation ( https://www.amcharts.com/docs/v5/charts/xy-chart/zoom-and-pan/ ) it says to use the start parameter:

var xAxis = chart.xAxes.push(
  am5xy.DateAxis.new(root, {
    start: 0.9,
    renderer: am5xy.AxisRendererX.new(root, {})
  })
);

In the note below this code it says if a scrollbar is used, add the very same start offset as in the chart date axis.

So, within the sample code I set:

var xAxis = chart.xAxes.push(
  am5xy.DateAxis.new(root, {
    start: 0.95,
    groupData: true,
    maxDeviation:0.5,
    baseInterval: { timeUnit: "day", count: 1 },
    renderer: am5xy.AxisRendererX.new(root, {pan:"zoom"}),
    tooltip: am5.Tooltip.new(root, {})
  })
);

and for the srollbar:

var sbxAxis = scrollbar.chart.xAxes.push(
  am5xy.DateAxis.new(root, {
    start: 0.95,
    groupData: true,
    groupIntervals: [{ timeUnit: "week", count: 1 }],
    baseInterval: { timeUnit: "day", count: 1 },
    renderer: am5xy.AxisRendererX.new(root, {
      opposite: false,
      strokeOpacity: 0
    })
  })
);

I tried everything. I tried from https://www.amcharts.com/docs/v5/charts/xy-chart/axes/category-date-axis/

xAxis.zoomToDates(new Date(2021, 0, 1), new Date(2022, 0, 1));

and

series.events.once("datavalidated", function(ev) {
  ev.target.get("xAxis").zoomToDates(new Date(2021, 0, 1), new Date(2022, 0, 1));
});

I tried adding "end: 1" to both elements. No luck.

Please, advice. Thanks a lot in advance.


Solution

  • As it happens the second option was correct and works fine. The confusion was with the dates. All the dates data for the chart is in timestamp which caused the confusion. Just in case posting here a final result - zooming to the last 130 records of the data and adding additional margin to the right for a little "air":

    series.events.once("datavalidated", function(ev) {
    
            //pre-zooming to last date
            
            var startDate = chartData[0].date;
            
            if(chartData.length >= 130){
                startDate = chartData[chartData.length - 130].date;
            }
            
            ev.target.get("xAxis").zoomToDates(new Date(startDate), new Date(chartData[chartData.length - 1].date + 600000));
        });
    

    Here we take the first alement as the start date and if there are more than 130 records, we take only those 130. On the finale line I add 600000 to the last date (I have minutely chart, so I am adding 10 minutes: 60 seconds * 10 minutes * 1000 microseconds).

    Hope this helps someone some day.