【问题标题】:Horizontal line indicating axis value for a single point in Google Charts水平线表示谷歌图表中单个点的轴值
【发布时间】:2015-08-18 05:28:51
【问题描述】:

我想使用 Google Charts 中的烛台图或折线图。 有没有办法从图形的最右边(最后一个值)到 Y 轴绘制一条水平线,Y 值显示在轴上? 我只想在图表上清楚地显示“最后一个”点的 Y 值。

【问题讨论】:

    标签: google-visualization


    【解决方案1】:

    由于 Google 图表使用 HTML5/SVG 呈现,您可以考虑使用以下解决方案来呈现 自定义水平轴

    google.load('visualization', '1.1', { packages: ['corechart'] });
    google.setOnLoadCallback(drawChart);
    
    function drawChart() {
        var data = google.visualization.arrayToDataTable([
            ['Year', 'Sales'],
            ['2004', 1000],
            ['2005', 1170],
            ['2006', 660],
            ['2007', 1030]
        ]);
    
        var options = {
            title: 'Company Performance',
            curveType: 'function',
            legend: { position: 'bottom' }
        };
    
        var chart = new google.visualization.LineChart(document.getElementById('chart'));
        chart.draw(data, options);
        drawAdditionalHAxis(chart, data);  //render custom axis (line & label) for the last value 
    }
    
    
    function drawAdditionalHAxis(chart,dataTable){
        var layout = chart.getChartLayoutInterface();
        var chartArea = layout.getChartAreaBoundingBox();
    
        var svg = chart.getContainer().getElementsByTagName('svg')[0];
        var lastVal = dataTable.getValue(dataTable.getNumberOfRows()-1,1);
        var yLoc = layout.getYLocation(lastVal);
        svg.appendChild(createLine(chartArea.left,yLoc,chartArea.width + chartArea.left,yLoc,'#cccccc',1)); // axis line
        svg.appendChild(createText(chartArea.left - 40 ,yLoc + 5,'Arial','13',lastVal)); // axis label 
    }
    
    
    
    
    
    function createLine(x1, y1, x2, y2, color, w) {
        var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
        line.setAttribute('x1', x1);
        line.setAttribute('y1', y1);
        line.setAttribute('x2', x2);
        line.setAttribute('y2', y2);
        line.setAttribute('stroke', color);
        line.setAttribute('stroke-width', w);
        return line;
    }
    
    function createText(x, y, fontFamily, fontSize,value) {
        var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
        text.setAttribute('x', x);
        text.setAttribute('y', y);
        text.setAttribute('font-family', fontFamily);
        text.setAttribute('font-size', fontSize);
        text.innerHTML = value;
        return text;
    }
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <div id="chart" style="width: 640px; height: 480px"></div>

    【讨论】:

    • 所以我必须自己做。奇怪的是,谷歌图表中不包含这样一个基本功能。谁不想时不时地在图表上显示某个点的值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多