CSV Data Analyzer

Advertisement




Convert CSV File to Bar Charts

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.

Step 1: Prepare Your CSV File

Ensure your CSV file is properly formatted with headers. Example:

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

Step 2: Convert CSV to JSON

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!")
    

Step 3: Create a Bar Chart Using Chart.js

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>
    

Step 4: Customize the Bar Chart

Modify the chart by changing colors, labels, and data options in the Chart.js configuration.

Step 5: Export the Chart

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>
    

Conclusion

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.