2015-08-16 84 views
0

我想使用Google圖表中的燭臺圖或折線圖。 有沒有什麼辦法從圖的最右邊的點(最後一個值)到Y軸繪製水平線,軸上顯示Y值? 我只是想在圖上清楚地顯示「最後」點的Y值。谷歌圖表中單個點的水平線指示軸值

回答

1

由於谷歌圖表使用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>

+0

所以,我必須做我自己呢。這很奇怪,谷歌圖表不包含這樣的基本功能。誰不想在某個圖表上的某個點上顯示某個值? – Alehar