Search code examples
rplotchartsgoogle-visualizationline-plot

Add spacing between gVisLineChart series


I'm working on a simple line chart using Google Vis (gVisLineChart) in R. I have several series that are displayed on the same chart. They have no relation between them.

If I had only two series, I would use the left vertical axis for one, and the right one for the other. However, I have 4 series. I hid the axes (they make no sense in my case), and I end up with lines crossing each other. Here is an example : gVisLineChart with data series over one another

Here is what I would like to have:

Artistic view of a gVisLineChart with increased spacing

I'm not a very good artist, but as you can see, I would like to increase the spacing between the series in order to limit lines crossing.

I've read the documentation of Google Vis for hours and tried all the options I could find, but I can't manage to do that.


Solution

  • there aren't any config options,
    but you could increase the values displayed,
    so they are actually larger and plot higher,
    but display the real values in the tooltips.

    the tooltip will display the formatted value of the cell in the data table.
    there are a couple ways we can accomplish.

    1) load the data table, then use data table method setFormattedValue to change the formatted value

    2) using object notation, we can provide the value (v:) and the (f:) formatted value,
    when loading the data table.

    {v: 100, f:'10'}  // <-- will plot 100 but display 10
    

    see following working snippet,
    here, I use a data view and calculated columns to change the plot values,
    but display the real values in the tooltip.

    google.charts.load('current', {
      packages: ['corechart']
    }).then(function () {
      var chartData = [
        ['x', 'y0', 'y1', 'y2'],
        [0, 10, 12, 18],
        [2, 16, 18, 19],
        [4, 18, 19, 24],
        [6, 26, 28, 22],
        [8, 13, 15, 21],
        [10, 32, 31, 33]
      ];
    
      var data = google.visualization.arrayToDataTable(chartData);
    
      var columns = [0];
      for (var i = 1; i < data.getNumberOfColumns(); i++) {
        addColumn(i);
      }
    
      var view = new google.visualization.DataView(data);
      view.setColumns(columns);
    
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(view, {
        height: 400,
        vAxis: {
          textPosition: 'none'
        }
      });
    
      function addColumn(index) {
        columns.push({
          calc: function (dt, row) {
            return {
              v: dt.getValue(row, index) + (index * 20),
              f: dt.getFormattedValue(row, index)
            };
          },
          label: data.getColumnLabel(index),
          type: data.getColumnType(index)
        });
      }
    });
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="chart_div"></div>

    for instance