Drawing visual Lines in Google Charts

2019-02-09 05:37发布

问题:

I'm writing a Google Chart. It has stacked columns. On top of that I want to draw 2 lines, which indicate min and max allowed value.

The only solution I came up with, was modifying the first example of ComboCharts. My result looks like this:

Which isn't sufficient. The graph is variable, so if there's only 1 Quartal shown, the line will solely be a dot. My Questions are:

  • Is there a way to draw the line further, so it hits the left and right boundary of the Graph?
  • Can I draw markup lines into the graph, without pretending it's another datapoint?

You can fiddle with a ComboChart here if you want.

回答1:

You can't get the lines to go edge-to-edge with a discrete (string-based) x-axis. If you switch to a continuous (number, date, datetime, timeofday) axis, then you can add one row before your real data and one row after that contain the goal lines (and nulls for the other data series):

function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('number', 'Quarter');
    data.addColumn('number', 'Value 1');
    data.addColumn('number', 'Value 2');
    data.addColumn('number', 'Value 3');
    data.addColumn('number', 'Goal 1');
    data.addColumn('number', 'Goal 2');
    data.addRows([
        [0, null, null, null, 10, 14],
        [1, 5, 4, 7, null, null],
        [2, 6, 9, 6, null, null],
        [3, 2, 6, 4, null, null],
        [5, null, null, null, 10, 14]
    ]);

    var chart = new google.visualization.ComboChart(document.querySelector('#chart_div'));
    chart.draw(data, {
        height: 400,
        width: 600,
        isStacked: true,
        legend: {
            position: 'top'
        },
        seriesType: 'bars',
        interpolateNulls: true,
        series: {
            3: {
                type: 'line'
            },
            4: {
                type: 'line'
            }
        },
        hAxis: {
            format: 'Q#',
            ticks: [1, 2, 3, 4],
            viewWindow: {
                min: 0.5,
                max: 4.5
            }
        },
        chartArea: {
            left: '10%',
            width: '80%'
        }
    });
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});

See working example: http://jsfiddle.net/asgallant/W67qU/