How to read a CSV file with ECharts to create a pie chart?

When using ECharts to create a pie chart, you can retrieve data by reading a CSV file. The following example demonstrates how to use ECharts and the jQuery library to read a CSV file and draw a pie chart.

First, make sure you have imported the ECharts and jQuery libraries.

<script src="https://cdn.jsdelivr.net/npm/echarts@5.0.1/dist/echarts.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Next, create an empty

element to serve as the container for the pie chart.

<div id="pieChart" style="width: 600px; height: 400px;"></div>

Next, read a CSV file and manipulate data in JavaScript.

$(document).ready(function() {
  $.get('data.csv', function(csvData) {
    // 将 CSV 数据转换为数组
    var lines = csvData.split('\n');
    var data = [];
    for (var i = 0; i < lines.length; i++) {
      var values = lines[i].split(',');
      data.push({
        name: values[0],
        value: values[1]
      });
    }

    // 绘制饼图
    var myChart = echarts.init(document.getElementById('pieChart'));
    var option = {
      series: [{
        type: 'pie',
        radius: '60%',
        data: data
      }]
    };
    myChart.setOption(option);
  });
});

In the above code, we first use jQuery’s $.get method to read the content of a CSV file named data.csv. Then, we convert the CSV data into an array and set names and values for each data item. Finally, we use ECharts’ setOption method to draw a pie chart with the transformed array as data.

Please make sure to replace data.csv in the example with the actual CSV file path. Additionally, you can also adjust the style and configuration of the pie chart as needed.

For more information and configuration about ECharts, please refer to the official documentation: https://echarts.apache.org/en/index.html

广告
Closing in 10 seconds
bannerAds