Search code examples
javascriptchartsgoogle-visualizationgraph-visualization

How to Add Point on Visualization: Area Chart


Visualization: Area Chart

How to add a point inside the Google Charts Visualization: Area chart like the red point in the picture shown above and can i put some label above or beside the point?

Here is the code that outputs the chart above

  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Output1');
    data.addColumn('number', 'Height');
    data.addColumn({type:'string', role:'annotation'});
    data.addRows([
      <?php echo"['',  2, null],"; ?>
      <?php echo"['',  2, '1 Kpa ---------->'],"; ?>
      <?php echo"['2',   1, '<---------- 2'],"; ?>
      <?php echo"['3 σ',   0, '<---------- 3 σ']"; ?>
    ]);

    var options = {
      title: 'Total Stress',
      hAxis: {title: '<-------- Direction',  titleTextStyle: {color: '#333'}},
      vAxis: { ticks: [{v:2, f:'1 Kpa ->'}, {v:1, f:'1 m'},{v:0, f:'length ^ 1 m'},{v:0, f:'1 m'}] }
    };

    var chart = new google.visualization.AreaChart(document.getElementById('total_stress'));
    chart.draw(data, options);
  }

Solution

  • you can use a ComboChart to combine series types

    add another column to the data table for the point

    in the options, define the series types, use 'scatter' for points

    seriesType: 'area',
    series: {
      1: {
        type: 'scatter'
      }
    }
    

    see following working snippet...

    google.charts.load('current', {
      packages: ['corechart']
    }).then(function () {
      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Output1');
      data.addColumn('number', 'Height');
      data.addColumn({type:'string', role:'annotation'});
      data.addColumn('number', 'Scatter');
      data.addRows([
        ['',  2, null, null],
        ['',  2, '1 Kpa ---------->', 1],
        ['2',   1, '<---------- 2', null],
        ['3 s',   0, '<---------- 3 s', null]
      ]);
    
      var options = {
        title: 'Total Stress',
        hAxis: {title: '<-------- Direction',  titleTextStyle: {color: '#333'}},
        vAxis: { ticks: [{v:2, f:'1 Kpa ->'}, {v:1, f:'1 m'},{v:0, f:'length ^ 1 m'},{v:0, f:'1 m'}] },
        seriesType: 'area',
        series: {
          1: {
            type: 'scatter'
          }
        }
      };
    
      var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    });
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="chart_div"></div>