Search code examples
javascriptamcharts

Category guides don't show on chart Amcharts


I'm trying to add vertical guides on the category axis to show sport activities on my chart. I have a variable in my json file called UNIX_TIMESTAMP(start_time) which is a Unix timestamp. I use this field to show on my category axis. Here is a codepen is created with my code for the chart: https://codepen.io/thomasdesaranno-r0629748/pen/jJrQgO

this is an example of my JSON file:

{
    "id": "NULL",
    "bg": "NULL",
    "UNIX_TIMESTAMP(start_time)": 1546603542000,
    "duration": 30,
    "sport_type": "running",
    "average_hr": 60,
    "average_speed": 30,
    "calories": 496,
    "fat_percentage_of_calories": 36,
    "food": "NULL",
    "ci": "NULL",
    "emotion": "NULL"
}

Does anybody know why my guides don't show?


Solution

  • The guides can not be created automatically from dataProvider, but you can extract the data you need and create the guides:

    var data = [/* your data */]
    var guides = data
      .map(i => i['UNIX_TIMESTAMP(start_time)'])
      .filter(i => i !== "NULL")
      .map(timestamp => ({
        "date": timestamp,
        "color": "#0000ff",
        "lineColor": "#0000ff",
        "lineAlpha": 1,
        "label": new Date(timestamp),
        "labelRotation": 90,
        "inside": true
      }));
    

    You now can set the guides in the chart config:

    {
      // ...
      "guides": guides,
      // ...
    }
    

    Here I have created a code pen as reference.

    If you want to use the dataLoader property to load external data for your chart you can use the dataUpdated event to generate the guides and add them to the chart:

    {
      // ...
      "listeners": [{
        "event":"dataUpdated", 
        "method": function(event) {
          event.chart.guides = event.chart.dataProvider
            .map(i => i['UNIX_TIMESTAMP(start_time)'])
            .filter(i => i !== "NULL")
            .map(timestamp => ({
              "date": timestamp,
              "color": "#0000ff",
              "lineColor": "#0000ff",
              "lineAlpha": 1,
              "label": new Date(timestamp),
              "labelRotation": 90,
              "inside": true
          }));
          event.chart.validateNow();
        }
      }],
      // ...
    }
    

    Don't forget to call chart.validateNow(), otherwise the chart don't shows the guides.

    Here I have created a code pen for the dataLoader solution.

    In the official docs you can read more about guides and their configuration.