工具提示:簡介
工具提示是彈出的方塊,當您將滑鼠遊標懸停在某個項目上時。(醒目資訊卡較為籠統,可以顯示在畫面上的任意位置;工具提示一律會附加在某個項目上,例如散佈圖上的圓點或長條圖上的長條)。
本文件將說明如何在 Google 圖表中建立和自訂工具提示。
指定工具提示類型
Google 圖表會自動為所有核心圖表建立工具提示。預設會以 SVG 格式算繪,但在 IE 8 中則會顯示為 VML。如要在核心圖表上建立 HTML 工具提示,請在傳遞至 draw() 呼叫的圖表選項中指定 tooltip.isHtml: true,您也可以建立工具提示動作。
標準工具提示
如未加入任何自訂內容,則會根據基礎資料自動產生工具提示內容。將滑鼠遊標懸停在圖表中的任一長條上,即可查看工具提示。
自訂工具提示內容
在這個範例中,我們在 DataTable 中新增資料欄,並加上工具提示角色,將自訂內容新增至工具提示。
注意:泡泡圖呈現方式「不」支援此功能。
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string', 'Year');
dataTable.addColumn('number', 'Sales');
// A column for custom tooltip content
dataTable.addColumn({type: 'string', role: 'tooltip'});
dataTable.addRows([
['2010', 600,'$600K in our first year!'],
['2011', 1500, 'Sunspot activity made this our best year ever!'],
['2012', 800, '$800K in 2012.'],
['2013', 1000, '$1M in sales last year.']
]);
var options = { legend: 'none' };
var chart = new google.visualization.ColumnChart(document.getElementById('tooltip_action'));
chart.draw(dataTable, options);
}
使用 HTML 工具提示
此範例是以啟用 HTML 工具提示的前一個方式為基礎。請注意,圖表選項中新增了 tooltip.isHtml: true。
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string', 'Year');
dataTable.addColumn('number', 'Sales');
// A column for custom tooltip content
dataTable.addColumn({type: 'string', role: 'tooltip'});
dataTable.addRows([
['2010', 600,'$600K in our first year!'],
['2011', 1500, 'Sunspot activity made this our best year ever!'],
['2012', 800, '$800K in 2012.'],
['2013', 1000, '$1M in sales last year.']
]);
var options = {
tooltip: {isHtml: true},
legend: 'none'
};
var chart = new google.visualization.ColumnChart(document.getElementById('col_chart_html_tooltip'));
chart.draw(dataTable, options);
}
這個做法看起來沒什麼差異,但現在我們可以自訂 HTML。
自訂 HTML 內容
上述範例都涵蓋純文字內容的工具提示,也具備 HTML 工具提示真正的強大威力。不過,您可以使用 HTML 標記自訂工具提示。如要啟用這項功能,您必須執行下列兩項操作:
-
在圖表選項中指定
tooltip.isHtml: true。這會指示圖表在 HTML (而非 SVG) 中繪製工具提示。 -
使用
html自訂屬性,即可標記資料表中的所有資料欄或特定儲存格。含有工具提示角色和 HTML 屬性的表格欄如下:
dataTable.addColumn({'type': 'string', 'role': 'tooltip', 'p': {'html': true}})注意:這個方法「不」適用於泡泡圖呈現方式。泡泡圖 HTML 工具提示的內容無法自訂。
重要事項:請確認工具提示中的 HTML 來自可信任的來源。
如果自訂 HTML 內容包含任何使用者原創內容,逸出該內容至關重要。否則,您的精美視覺化內容可能會遭受 XSS 攻擊。
自訂 HTML 內容可以很簡單,像是加入 <img> 標記或將一些文字設為粗體一樣:
自訂 HTML 內容也可以包含動態產生的內容。我們在這裡新增工具提示,其中包含每個類別值動態產生的資料表。由於工具提示會附加在資料列值上,因此只要將遊標懸停在任何長條上,就會顯示 HTML 工具提示。
這個範例說明如何將自訂 HTML 工具提示附加至網域資料欄。(在先前的範例中,它附加至資料欄)。如要啟用網域軸的工具提示,請設定 focusTarget: 'category' 選項。
function drawChart() {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string', 'Country');
// Use custom HTML content for the domain tooltip.
dataTable.addColumn({'type': 'string', 'role': 'tooltip', 'p': {'html': true}});
dataTable.addColumn('number', 'Gold');
dataTable.addColumn('number', 'Silver');
dataTable.addColumn('number', 'Bronze');
dataTable.addRows([
['USA', createCustomHTMLContent('https://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg', 46, 29, 29), 46, 29, 29],
['China', createCustomHTMLContent('https://upload.wikimedia.org/wikipedia/commons/f/fa/Flag_of_the_People%27s_Republic_of_China.svg', 38, 27, 23), 38, 27, 23],
['UK', createCustomHTMLContent('https://upload.wikimedia.org/wikipedia/commons/a/ae/Flag_of_the_United_Kingdom.svg', 29, 17, 19), 29, 17, 19]
]);
var options = {
title: 'London Olympics Medals',
colors: ['#FFD700', '#C0C0C0', '#8C7853'],
// This line makes the entire category's tooltip active.
focusTarget: 'category',
// Use an HTML tooltip.
tooltip: { isHtml: true }
};
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('custom_html_content_div')).draw(dataTable, options);
}
function createCustomHTMLContent(flagURL, totalGold, totalSilver, totalBronze) {
return '<div style="padding:5px 5px 5px 5px;">' +
'<img src="' + flagURL + '" style="width:75px;height:50px"><br/>' +
'<table class="medals_layout">' + '<tr>' +
'<td><img src="https://upload.wikimedia.org/wikipedia/commons/1/15/Gold_medal.svg" style="width:25px;height:25px"/></td>' +
'<td><b>' + totalGold + '</b></td>' + '</tr>' + '<tr>' +
'<td><img src="https://upload.wikimedia.org/wikipedia/commons/0/03/Silver_medal.svg" style="width:25px;height:25px"/></td>' +
'<td><b>' + totalSilver + '</b></td>' + '</tr>' + '<tr>' +
'<td><img src="https://upload.wikimedia.org/wikipedia/commons/5/52/Bronze_medal.svg" style="width:25px;height:25px"/></td>' +
'<td><b>' + totalBronze + '</b></td>' + '</tr>' + '</table>' + '</div>';
}
旋轉工具提示
Google 圖表中的工具提示可以透過 CSS 旋轉。在下圖中,工具提示會透過這個內嵌 CSS,於圖表 div 之前立即順時針旋轉 30°:
<style>div.google-visualization-tooltip { transform: rotate(30deg); }</style>
請注意,這僅適用於 HTML 工具提示,也就是提供 isHtml: true 選項的工具提示。
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Fixations'],
['2015', 80],
['2016', 90],
['2017', 100],
['2018', 90],
['2019', 80],
]);
var options = {
tooltip: { isHtml: true }, // CSS styling affects only HTML tooltips.
legend: { position: 'none' },
bar: { groupWidth: '90%' },
colors: ['#A61D4C']
};
var chart = new google.visualization.ColumnChart(document.getElementById('tooltip_rotated'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!-- The next line rotates HTML tooltips by 30 degrees clockwise. -->
<style>div.google-visualization-tooltip { transform: rotate(30deg); }</style>
<div id="tooltip_rotated" style="width: 400px; height: 400px;"></div>
</body>
</html>
在工具提示中加入圖表
HTML 工具提示可包含大部分您需要的 HTML 內容,即使是 Google 圖表也不例外。透過工具提示中的圖表,當使用者將遊標懸停在資料元素上時,即可取得額外資訊,這是一種快速提供概略詳細資料的方法,還能讓使用者在需要時進一步查看。
下方的柱狀圖顯示多項大型體育賽事的最新觀眾人數,每個事件的工具提示都代表過去十年內平均觀眾人數的折線圖。
有幾點要注意首先,您必須為要顯示在工具提示中的每組資料繪製可列印的圖表。其次,每個工具提示圖表都需要一個「已就緒」的事件處理常式,我們透過 addListener 呼叫該處理常式,即可建立可列印的圖表。
重要事項:工具提示圖表「必須」繪製在主要圖表之前。 這是擷取圖片並新增至主要圖表資料表的必要步驟。
// Draws your charts to pull the PNGs for your tooltips.
function drawTooltipCharts() {
var data = new google.visualization.arrayToDataTable(tooltipData);
var view = new google.visualization.DataView(data);
// For each row of primary data, draw a chart of its tooltip data.
for (var i = 0; i < primaryData.length; i++) {
// Set the view for each event's data
view.setColumns([0, i + 1]);
var hiddenDiv = document.getElementById('hidden_div');
var tooltipChart = new google.visualization.LineChart(hiddenDiv);
google.visualization.events.addListener(tooltipChart, 'ready', function() {
// Get the PNG of the chart and set is as the src of an img tag.
var tooltipImg = '<img src="' + tooltipChart.getImageURI() + '">';
// Add the new tooltip image to your data rows.
primaryData[i][2] = tooltipImg;
});
tooltipChart.draw(view, tooltipOptions);
}
drawPrimaryChart();
}
function drawPrimaryChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Event');
data.addColumn('number', 'Highest Recent Viewership');
// Add a new column for your tooltips.
data.addColumn({
type: 'string',
label: 'Tooltip Chart',
role: 'tooltip',
'p': {'html': true}
});
// Add your data (with the newly added tooltipImg).
data.addRows(primaryData);
var visibleDiv = document.getElementById('visible_div');
var primaryChart = new google.visualization.ColumnChart(visibleDiv);
primaryChart.draw(data, primaryOptions);
}
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawTooltipCharts);
// Set up data for visible chart.
var primaryData = [
['NBA Finals', 22.4],
['NFL Super Bowl', 111.3],
['MLB World Series', 19.2],
['UEFA Champions League Final', 1.9],
['NHL Stanley Cup Finals', 6.4],
['Wimbledon Men\'s Championship', 2.4]
];
// Set up data for your tooltips.
var tooltipData = [
['Year', 'NBA Finals', 'NFL Super Bowl', 'MLB World Series',
'UEFA Champions League Final', 'NHL Stanley Cup Finals',
'Wimbledon Men\'s Championship'],
['2005', 12.5, 98.7, 25.3, 0.6, 3.3, 2.8],
['2006', 13.0, 90.7, 17.1, 0.8, 2.8, 3.4],
['2007', 9.3, 93.0, 15.8, 0.9, 1.8, 3.8],
['2008', 14.9, 97.5, 17.1, 1.3, 4.4, 5.1],
['2009', 14.3, 98.7, 13.6, 2.1, 4.9, 5.7],
['2010', 18.2, 106.5, 19.4, 2.2, 5.2, 2.3],
['2011', 17.4, 111.0, 14.3, 4.2, 4.6, 2.7],
['2012', 16.8, 111.3, 16.6, 2.0, 2.9, 3.9],
['2013', 16.6, 108.7, 12.7, 1.4, 5.8, 2.5],
['2014', 15.7, 111.3, 15.0, 1.9, 4.7, 2.4]
];
var primaryOptions = {
title: 'Highest U.S. Viewership for Most Recent Event (in millions)',
legend: 'none',
tooltip: {isHtml: true} // This MUST be set to true for your chart to show.
};
var tooltipOptions = {
title: 'U.S. Viewership Over The Last 10 Years (in millions)',
legend: 'none'
};
// Draws your charts to pull the PNGs for your tooltips.
function drawTooltipCharts() {
var data = new google.visualization.arrayToDataTable(tooltipData);
var view = new google.visualization.DataView(data);
// For each row of primary data, draw a chart of its tooltip data.
for (var i = 0; i < primaryData.length; i++) {
// Set the view for each event's data
view.setColumns([0, i + 1]);
var hiddenDiv = document.getElementById('hidden_div');
var tooltipChart = new google.visualization.LineChart(hiddenDiv);
google.visualization.events.addListener(tooltipChart, 'ready', function() {
// Get the PNG of the chart and set is as the src of an img tag.
var tooltipImg = '<img src="' + tooltipChart.getImageURI() + '">';
// Add the new tooltip image to your data rows.
primaryData[i][2] = tooltipImg;
});
tooltipChart.draw(view, tooltipOptions);
}
drawPrimaryChart();
}
function drawPrimaryChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Event');
data.addColumn('number', 'Highest Recent Viewership');
// Add a new column for your tooltips.
data.addColumn({
type: 'string',
label: 'Tooltip Chart',
role: 'tooltip',
'p': {'html': true}
});
// Add your data (with the newly added tooltipImg).
data.addRows(primaryData);
var visibleDiv = document.getElementById('visible_div');
var primaryChart = new google.visualization.ColumnChart(visibleDiv);
primaryChart.draw(data, primaryOptions);
}
</script>
</head>
<body>
<div id="hidden_div" style="display:none"></div>
<div id="visible_div" style="height:300px"></div>
</body>
</html>
工具提示動作
工具提示也可以包含 JavaScript 定義的動作。以下提供一個工具提示,其中包含一個動作,當使用者按一下「See sample Book」時,會彈出對話方塊:
使用者選取圓餅圖的樣式時,會觸發 tooltip 選項,進而執行 setAction 中定義的程式碼:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Genre', 'Percentage of my books'],
['Science Fiction', 217],
['General Science', 203],
['Computer Science', 175],
['History', 155],
['Economics/Political Science', 98],
['General Fiction', 72],
['Fantasy', 51],
['Law', 29]
]);
var chart = new google.visualization.PieChart(
document.getElementById('tooltip_action'));
var options = { tooltip: { trigger: 'selection' }};
chart.setAction({
id: 'sample',
text: 'See sample book',
action: function() {
selection = chart.getSelection();
switch (selection[0].row) {
case 0: alert('Ender\'s Game'); break;
case 1: alert('Feynman Lectures on Physics'); break;
case 2: alert('Numerical Recipes in JavaScript'); break;
case 3: alert('Truman'); break;
case 4: alert('Freakonomics'); break;
case 5: alert('The Mezzanine'); break;
case 6: alert('The Color of Magic'); break;
case 7: alert('The Law of Superheroes'); break;
}
}
});
chart.draw(data, options);
}
動作可以是 visible、enabled、同時包含兩者,或兩者皆非。在系統算繪 Google 圖表時,系統只會顯示工具提示動作,且只有在啟用後才會顯示可點選的選項。(已停用,但可見的動作會顯示為灰色)。
visible 和 enabled 應為傳回 true 或 false 值的函式。這些函式可以依附元素 ID 和使用者選擇,讓您微調動作的顯示設定和可點擊屬性。
工具提示可在 focus 和 selection 上觸發。不過,搭配工具提示動作時,建議使用 selection。這樣工具提示就會保留,讓使用者可以更輕鬆地選取動作。
這些動作不是快訊,當然不是快訊,而是可透過 JavaScript 執行的任何操作。讓我們新增兩項操作:一個用來放大圓餅圖的楔形調整架,另一個則用來縮小圓餅圖。
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Genre', 'Percentage of my books'],
['Science Fiction', 217],
['General Science', 203],
['Computer Science', 175],
['History', 155],
['Economics & Political Science', 98],
['General Fiction', 72],
['Fantasy', 51],
['Law', 29]
]);
var chart = new google.visualization.PieChart(
document.getElementById('tooltip_action_2'));
var options = { tooltip: { trigger: 'selection' }};
chart.setAction({
id: 'increase',
text: 'Read 20 more books',
action: function() {
data.setCell(chart.getSelection()[0].row, 1,
data.getValue(chart.getSelection()[0].row, 1) + 20);
chart.draw(data, options);
}
});
chart.setAction({
id: 'decrease',
text: 'Read 20 fewer books',
action: function() {
data.setCell(chart.getSelection()[0].row, 1,
data.getValue(chart.getSelection()[0].row, 1) - 20);
chart.draw(data, options);
}
});
chart.draw(data, options);
}
為資料加上註解
您可以使用 annotationText (而非 tooltip) 做為欄角色,將文字直接疊加到 Google 圖表。(將滑鼠遊標懸停在註解上,即可查看工具提示)。
function drawChart() {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string', 'Year');
dataTable.addColumn('number', 'USA');
dataTable.addColumn({type: 'string', role: 'annotation'});
dataTable.addColumn({type: 'string', role: 'annotationText', p: {html:true}});
dataTable.addColumn('number', 'China');
dataTable.addColumn('number', 'UK');
dataTable.addRows([
['2000', 94, '', '', 58, 28],
['2004', 101, '', '', 63, 30],
['2008', 110, 'An all time high!', '<img width=100px src="https://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg">', 100, 47],
['2012', 104, '', '', 88, 65]
]);
var options = { tooltip: {isHtml: true}};
var chart = new google.visualization.LineChart(document.getElementById('tt_6_annotation'));
chart.draw(dataTable, options);
}
支援的圖表
目前下列圖表類型支援 HTML 工具提示:- AreaChart
- BarChart
- CalendarChart
- CandlestickChart
- ColumnChart
- ComboChart
- LineChart
- PieChart
- 桑基圖
- ScatterChart
- 時程
如果您使用 annotationText 或 tooltip 角色,請參閱角色說明文件,瞭解日後的異動和避免日後的問題。