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.
Ensure the CSV file is structured correctly. Example:
Category,Value
Electronics,5000
Clothing,3000
Furniture,4000
Groceries,7000
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!")
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>
Open the HTML file in a browser to see the pie chart. Modify colors and sizes as needed.
By converting CSV data into a pie chart, users can visually analyze proportions efficiently. Chart.js makes this process simple and interactive.