angularlineamchartsamcharts4timeserieschart

How to indicate the specific datapoint on the XY am4chart upon clicking on it?


It may seem really trivial but I haven't been able to find the solution for my problem anywhere. So I have a classic XY am4chart with couple hundreds data points in the line series. I want the chart to draw a vertical line (or indicate in any other way) upon clicking on the given point in chart. So if I click once then the indication appears in that point and if I click somewhere else on the chart - the indication moves to the new place. Thanks a lot in advance!


Solution

  • You can trigger the cursor when a point is clicked. Here is an example:

    // Themes begin
    am4core.useTheme(am4themes_animated);
    // Themes end
    
    // Create chart instance
    var chart = am4core.create("chartdiv", am4charts.XYChart);
    
    // Add data
    chart.data = [{
      "date": new Date(2018, 3, 20),
      "value": 90
    }, {
      "date": new Date(2018, 3, 21),
      "value": 102
    }, {
      "date": new Date(2018, 3, 22),
      "value": 65
    }, {
      "date": new Date(2018, 3, 23),
      "value": 62
    }, {
      "date": new Date(2018, 3, 24),
      "value": 55
    }, {
      "date": new Date(2018, 3, 25),
      "value": 81
    }];
    
    // Create axes
    var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
    
    // Create value axis
    var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
    
    // Create cursor
    chart.cursor = new am4charts.XYCursor();
    chart.cursor.yAxis = valueAxis;
    chart.cursor.lineX.disabled = true;
    chart.cursor.interactionsEnabled = false;
    chart.cursor.events.on("track", event => {
      chart.cursor.hide();
      chart.cursor.interactionsEnabled = false;
    });
    
    // Create series
    var lineSeries = chart.series.push(new am4charts.LineSeries());
    lineSeries.dataFields.valueY = "value";
    lineSeries.dataFields.dateX = "date";
    lineSeries.name = "Sales";
    lineSeries.strokeWidth = 3;
    
    // Add simple bullet
    var bullet = lineSeries.bullets.push(new am4charts.Bullet());
    var image = bullet.createChild(am4core.Image);
    image.href = "https://www.amcharts.com/lib/images/star.svg";
    image.width = 30;
    image.height = 30;
    image.horizontalCenter = "middle";
    image.verticalCenter = "middle";
    // attach click event
    bullet.events.on("hit", event => {
      chart.cursor.interactionsEnabled = true;
      var point = event.target.dataItem.point;
      chart.cursor.triggerMove(point);
    });
    

    enter image description here