如何在Google Charts堆叠条形图点击事件中获取键名?
Add Click Event to Get Key Name in Google Charts Stacked Bar Chart
Got it! To capture the corresponding key name (the value from the first DATA column, like PCX, PCG, etc.) when clicking on your stacked percentage bar chart, you can leverage Google Charts' built-in select event listener. Here's how to update your code:
google.charts.load('current', { packages: ['corechart', 'bar'] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['DATA', 'L', 'P'], ['PCX', 18, 21],['PCG', 131, 34],['PCO', 9, 3],['PGD', 441, 269],['PAH', 1, 1],['POD', 8, 5],['PCT', 80, 180],['PDD', 1, 7],['PZZ', 3, 8],['PKK', 461, 580],['PBI', 494, 248],['PKI', 2, 5],['PKL', 5, 1] ]); var options = { isStacked: 'percent', legend: { position: 'top' }, chartArea: { left: 40 /* keep your existing settings here */ } }; // Create the chart instance (replace with your actual container ID) var chart = new google.visualization.BarChart(document.getElementById('your-chart-container-id')); // Add click event listener to capture key names google.visualization.events.addListener(chart, 'select', function() { var selection = chart.getSelection(); // Only proceed if an element is actually clicked if (selection.length > 0) { var rowIndex = selection[0].row; // Pull the key name from the first column (index 0) of the selected row var keyName = data.getValue(rowIndex, 0); // Use the key name however you need—log it, update UI, etc. console.log('Clicked key name:', keyName); // Example: Show an alert with the key name // alert('You clicked on: ' + keyName); } }); // Render the chart chart.draw(data, options); }
Key Breakdown:
- Chart Instance: We explicitly create a
BarChartinstance (don't forget to replace'your-chart-container-id'with the ID of the HTML element where your chart lives). - Select Event Handler: The
google.visualization.events.addListenerhooks into the chart's click/select event. - Retrieve Selection:
chart.getSelection()returns an array of selected elements. For bar charts, each entry includes therowindex of the clicked bar segment. - Fetch Key Name: Using
data.getValue(rowIndex, 0), we grab the value from the first column of the selected row—this is your target key name.
You can tweak the code inside the event handler to use keyName for any action you need, like updating a display panel or triggering further data processing.
内容的提问来源于stack exchange,提问作者Maestro Vladimir
相关产品推荐
相关产品推荐

