简体   繁体   中英

Positioning points and labels on x-axis of Google powered line charts

Using Google's new Charts is a wonderful way to build graphicial representations of data, but there are a few things I've been able to do in Excel that I can't yet find a way to replicate using the API.

What I want to do is bring the point that is plotted at the first point on the x-axis closer to the y-axis. Currently, the first point is plotted away from the y-axis, but in the graph I'm generating, the first point should be the origin of the data. Here's what I have currently:

当前的Google图表输出

The point plotted at 0,40 is plotted away from the y-axis. What I want is to have a true 0,0 point so that the data plotted for '1' is seen as the data taken at the end of the first day and the data taken at '0' is just the baseline:

理想的Google图表输出

I've created a jsfiddle for you to play with too, here's the JavaScript:

google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Day');
    data.addColumn('number', 'Slide');
    data.addRows([
        ['0', 40],
        ['1', 36],
        ['2', 32],
        ['3', 28],
        ['4', 24],
        ['5', 20],
        ['6', 16],
        ['7', 12],
        ['8',8],
        ['9', 4],
        ['10', 0],
    ]);

    var options = {
        colors: ['red', 'silver'],
        title: 'Slide',
        hAxis: {minValue: 0}
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}
​

and HTML:

<div id="chart_div" style="width: 900px; height: 500px;"></div>

There are some hints here about customising the axis but they do nothing but break my graph!

When using the charts, defining the x-axis as a string forces a gap at the both the beginning and the end of the chart. This is most notable between the labels on the y-axis and the first point that is plotted, as in the images in the question.

To over come this, define the x-axis as a number (obviously, where appropriate):

data.addColumn('number', 'Day');
data.addColumn('number', 'Slide');
data.addRows([
    [0, 40],
    [1, 36],
    [2, 32],
    [3, 28],
    [4, 24],
    [5, 20],
    [6, 16],
    [7, 12],
    [8,8],
    [9, 4],
    [10, 0],
]);

The first column is now of type number and the values are now numbers and not strings. See it working on jsfiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM