1
votes

I'm rendering Amcharts Line Chart, I've add dynamic graphs with value axis and user should be able to manipulate value axis for each graph on fly. Ex. If I add 2 graphs with 2 value axis, after user should be able to combine value axis for both graph and display as single on fly.

I've created almost everything but on assigning value axis to multiple graph, it gives error 'cannot ready property value of undefined'

I've this code,

    $(function(){

   var t = $('#example').DataTable({
     info:false,
     paging:false,
     searching:false,
   });
    var counter = 1;

    $('#addRow').on( 'click', function () {
        t.row.add( [
            counter +'.1',
        ] ).draw( false );
        $('#yaxisselect').append(new Option(counter+ '.1',counter+ '.1',false,false));
        counter++;
    });
    $('#save').click(function(){
      if($('#yaxisselect').val() != null && $('#yaxisselect').val() != ""){
        for(i in chart.graphs){
          if(chart.graphs[i].id == $('#yaxisselect').val()){
            chart.graphs[i].title = $("#CrrGraphTitle").val();
          }
        }
      }
      chart.validateNow();
    });
     $('#yaxisselect').on('change',function(){
        var graphExist = false;
        for(i in chart.graphs){
          if(chart.graphs[i].id == $('#yaxisselect').val()){
            graphExist = true;
            $("#CrrGraphTitle").val(chart.graphs[i].title);
            $("#CurrValueAxisTitle").val(chart.graphs[i].valueAxis.title);
            $("#ValueAxisSelect").val(chart.graphs[i].valueAxis.id).trigger('change');
          }
        }
        if(!graphExist){
           var offsets = {
              left: 0,
              right: 0
            }
            let offset = 0;
            let position = Math.random() * 10 > 5 ? "left" : "right";

            for (var i1 = 0; i1 < chart.valueAxes.length; i1++) {
              offsets[chart.valueAxes[i1].position] += 75;
            }
          // Add value axis
          var a = new AmCharts.ValueAxis();
          a.id = $("#yaxisselect").val();
          a.axisThickness = 2;
          a.gridAlpha = 0;
          a.axisAlpha = 1;
          a.minimum = undefined
          a.maximum = undefined
          a.position = position;
          a.offset = offsets[position];
          chart.addValueAxis(a);

          var graph = new AmCharts.AmGraph();
            graph.title = "test" + chart.graphs.length;
            graph.valueField = $("#yaxisselect").val();
            graph.id = $("#yaxisselect").val();
            graph.balloonText = "[[title]]: [[value]]";
            graph.type = "line";
            graph.valueAxis =  $("#yaxisselect").val();
            for (i in chartData) {
            chartData[i][$("#yaxisselect").val()] = Math.round(Math.random() * 12) + 1;
          }
          chart.addGraph(graph);

            $("#CrrGraphTitle").val(graph.title);
            $('#ValueAxisSelect').append(new Option(graph.id,graph.id,true,true));
        }
     });

     $('#ValueAxisSelect').on('change',function(){

     })

     $('#yaxisselect').on('select2:close',function(){
        chart.validateNow();
     })

    $('#yaxisselect').on('select2:opening',function(){
          var graphExist = false;
          for(i in chart.graphs){
            if(chart.graphs[i].id == $('#yaxisselect').val()){
              graphExist = true;
              chart.graphs[i].title = $("#CrrGraphTitle").val();
              for(g in chart.valueAxes){
                  if(chart.valueAxes[g].id ==  $("#ValueAxisSelect").val()){
                      chart.graphs[i].valueAxis = chart.valueAxes[g] // If I comment out this, everything works fine but required is not satisfied.
                  }
              }

              console.log(chart)
            }
          }
      })


  $('#slider').slideReveal({
    trigger: $("#trigger,#save"),
    position:'right'
  });

  $('.iselect').select2({
     dropdownParent: $('#slider'),
     placeholder: "Select a state",
    allowClear: true
  });


})

var chartData = generatechartData();

function generatechartData() {
    var chartData = [];
    var firstDate = new Date();
    firstDate.setDate(firstDate.getDate() - 150);
    var visits = 500;

    for (var i = 0; i < 150; i++) {
        // we create date objects here. In your data, you can have date strings
        // and then set format of your dates using chart.dataDateFormat property,
        // however when possible, use date objects, as this will speed up chart rendering.
        var newDate = new Date(firstDate);
        newDate.setDate(newDate.getDate() + i);

        visits += Math.round((Math.random()<0.5?1:-1)*Math.random()*10);

        chartData.push({
            date: newDate,
            visits: visits
        });
    }
    return chartData;
}


var chart = AmCharts.makeChart("chartdiv", {
    "theme": "light",
    "type": "serial",
    "marginRight": 80,
    "autoMarginOffset": 20,
    "marginTop":20,
    "dataProvider": chartData,
     "legend": {
    "useGraphSettings": true
    },
    "valueAxes": [{
        "id": "v1",
        "axisAlpha": 0.1
    }],
    "graphs": [{
        "useNegativeColorIfDown": true,
        "balloonText": "[[category]]<br><b>value: [[value]]</b>",
        "bullet": "round",
        "bulletBorderAlpha": 1,
        "bulletBorderColor": "#FFFFFF",
        "hideBulletsCount": 50,
        "lineThickness": 2,
        "lineColor": "#fdd400",
        "negativeLineColor": "#67b7dc",
        "valueField": "visits"
    }],
    "chartScrollbar": {
        "scrollbarHeight": 5,
        "backgroundAlpha": 0.1,
        "backgroundColor": "#868686",
        "selectedBackgroundColor": "#67b7dc",
        "selectedBackgroundAlpha": 1
    },
    "chartCursor": {
        "valueLineEnabled": true,
        "valueLineBalloonEnabled": true
    },
    "categoryField": "date",
    "categoryAxis": {
        "parseDates": true,
        "axisAlpha": 0,
        "minHorizontalGap": 60
    },
    "export": {
        "enabled": true
    }
});

chart.addListener("dataUpdated", zoomChart);
//zoomChart();

function zoomChart() {
    if (chart.zoomToIndexes) {
        chart.zoomToIndexes(130, chartData.length - 1);
    }
}

https://jsfiddle.net/14076Ly0/

steps,

Click Add Rows 2-3 times to generate data click trigger to open settings select y axis to add graph and value axis on fly add 2-3 graphs and change default value axis change y axis to save configuration --> this give error and graph is not plotted..

any idea what I'm doing wrong here?

1

1 Answers

0
votes

You should use validateData() or validateNow(true, false) when manipulating the value axis since its appearance depends on the values in your data. Updating the select2:close event for #yaxisselect will fix it.

Updated fiddle: https://jsfiddle.net/14076Ly0/1/