CSV (Comma-Separated Values) files store structured data, making them useful for analysis. Converting CSV data into bar charts helps in better visualization and decision-making.
Ensure your CSV file is properly formatted with headers. Example:
Category,Sales
Electronics,5000
Clothing,3000
Furniture,4000
Groceries,7000
Since JavaScript works better 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 visualize the data as a bar chart.
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="barChart"></canvas>
<script>
fetch("data.json")
.then(response => response.json())
.then(data => {
let labels = data.map(item => item.Category);
let values = data.map(item => item.Sales);
new Chart(document.getElementById("barChart"), {
type: "bar",
data: {
labels: labels,
datasets: [{
label: "Sales Data",
data: values,
backgroundColor: "blue"
}]
}
});
});
</script>
Modify the chart by changing colors, labels, and data options in the Chart.js configuration.
Users can download the chart as an image by adding a button:
<button onclick="downloadChart()">Download Chart</button>
<script>
function downloadChart() {
let canvas = document.getElementById("barChart");
let link = document.createElement("a");
link.href = canvas.toDataURL("image/png");
link.download = "bar_chart.png";
link.click();
}
</script>
By following these steps, you can easily convert CSV data into bar charts for better visualization. Using Chart.js, you can make interactive charts and export them for further use.