How to achieve click list linkage pie chart in Echarts?
To achieve the linking between a list and a pie chart, you must first prepare the data for both the list and the pie chart. Next, using Echarts’ event listening mechanism, retrieve the selected item’s data from the list’s click event, update the pie chart’s data, and finally, re-render the pie chart.
Here is a simple example code:
HTML section:
<div id="list">
<ul>
<li data-value="30">选项1</li>
<li data-value="50">选项2</li>
<li data-value="20">选项3</li>
</ul>
</div>
<div id="chart" style="width: 400px; height: 400px;"></div>
JavaScript section:
// 初始化饼图的数据
var pieData = [
{ value: 30, name: '选项1' },
{ value: 50, name: '选项2' },
{ value: 20, name: '选项3' }
];
// 初始化饼图的配置
var pieOptions = {
series: [
{
type: 'pie',
data: pieData
}
]
};
// 绑定列表的点击事件
document.getElementById('list').addEventListener('click', function(e) {
var li = e.target;
if (li.tagName === 'LI') {
var value = li.getAttribute('data-value');
// 更新饼图的数据
pieData = [
{ value: value, name: '选项1' },
{ value: 100 - value, name: '其他选项' }
];
// 重新渲染饼图
echarts.init(document.getElementById('chart')).setOption(pieOptions);
}
});
In the code above, stores the corresponding value by adding a custom attribute data-value to each option in the list. In the click event of the list, gets the value of the clicked option, then updates the data in the pie chart according to that value, and finally, re-renders the pie chart.