Advertisement




Visualizing data using pie charts makes it easier to analyze proportions and distributions. This article explains how to convert CSV data into a pie chart.

Step 1: Prepare the CSV File

Ensure the CSV file is structured correctly. Example:

Category,Value
Electronics,5000
Clothing,3000
Furniture,4000
Groceries,7000
    

Step 2: Convert CSV to JSON

Since JavaScript works efficiently with JSON, convert CSV to JSON using Python:

import csv
import json

csv_file = "data.csv"
json_file = "data.json"

data = []
with open(csv_file, "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        data.append(row)

with open(json_file, "w") as file:
    json.dump(data, file, indent=4)

print("CSV converted to JSON successfully!")
    

Step 3: Create a Pie Chart Using Chart.js

Use Chart.js to generate a pie chart dynamically.

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="pieChart"></canvas>
<script>
fetch("data.json")
    .then(response => response.json())
    .then(data => {
        let labels = data.map(item => item.Category);
        let values = data.map(item => item.Value);

        new Chart(document.getElementById("pieChart"), {
            type: "pie",
            data: {
                labels: labels,
                datasets: [{
                    label: "Category Distribution",
                    data: values,
                    backgroundColor: ["red", "blue", "green", "yellow"]
                }]
            }
        });
    });
</script>
    

Step 4: Test and Optimize

Open the HTML file in a browser to see the pie chart. Modify colors and sizes as needed.

Conclusion

By converting CSV data into a pie chart, users can visually analyze proportions efficiently. Chart.js makes this process simple and interactive.