Visualization Examples

Interactive Charts with Chart.js

Explore how to create dynamic and interactive charts using the popular Chart.js library. This example demonstrates a simple bar chart that can be updated.

Bar Chart Example


// Sample data
let chartData = {
    labels: ['January', 'February', 'March', 'April', 'May'],
    datasets: [{
        label: 'Monthly Sales',
        data: [65, 59, 80, 81, 56],
        backgroundColor: 'rgba(54, 162, 235, 0.6)',
        borderColor: 'rgba(54, 162, 235, 1)',
        borderWidth: 1
    }]
};

// Get the canvas element
const ctx = document.getElementById('myBarChart').getContext('2d');

// Create the chart
const myBarChart = new Chart(ctx, {
    type: 'bar',
    data: chartData,
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'top',
            },
            title: {
                display: true,
                text: 'Monthly Sales Data'
            }
        },
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});

// Example of updating the chart (e.g., after fetching new data)
function updateChart() {
    chartData.datasets[0].data = [70, 62, 85, 78, 60]; // New data
    chartData.datasets[0].backgroundColor = 'rgba(255, 99, 132, 0.6)';
    myBarChart.update();
}

// You could call updateChart() on a button click or after an API call.
// For demonstration, let's add a button to trigger it.
document.getElementById('updateChartBtn').addEventListener('click', updateChart);
                

Data Visualization with D3.js

D3.js is a powerful JavaScript library for manipulating documents based on data. It's used for creating dynamic, interactive data visualizations in web browsers. This example shows a basic SVG circle.

SVG Circle with D3


// Get the container element
const svgContainer = d3.select("#d3CircleContainer");

// Append an SVG element
const svg = svgContainer.append("svg")
    .attr("width", 400)
    .attr("height", 200);

// Append a circle element
svg.append("circle")
    .attr("cx", 100)
    .attr("cy", 100)
    .attr("r", 50)
    .attr("fill", "teal");

// You can add more complex shapes, text, and interactions using D3.
// This is a very basic illustration.
                

Geospatial Visualization with Leaflet

Leaflet is a leading open-source JavaScript library for mobile-friendly interactive maps. This example displays a simple map with a marker.

Interactive Map with Leaflet


// Initialize the map
const map = L.map('leafletMapContainer').setView([51.505, -0.09], 13);

// Add a tile layer (OpenStreetMap is a common choice)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
}).addTo(map);

// Add a marker
L.marker([51.5, -0.09]).addTo(map)
    .bindPopup('A sample marker.')
    .openPopup();

// You can add polygons, lines, popups, and layers to the map.