Transform raw API data into beautiful, interactive charts! This template teaches you how to visualize data using Chart.js, one of the most popular charting libraries for web applications.
By completing this activity, you will:
Integrate Chart.js library into web applications
Transform API responses into chart-ready data formats
Create line charts, bar charts, and doughnut charts
Handle real-time data updates and visualization
Implement responsive chart layouts that adapt to screen sizes
IMPORTANT: This template includes WORKING CHARTS! You can see them immediately:
Navigate to this folder in your terminal/command prompt
Start a local server (choose one):
bash
python3 -m http.server 8002
python -m http.server 8002
npx http-server -p 8002
Open your browser to: http://localhost:8002
Click the buttons - charts appear immediately!
"Load Weather Data" shows a line chart with temperature trends
"Load Stock Data" displays a bar chart with stock prices
"Load User Analytics" creates doughnut and radar charts
"Clear All Charts" resets the dashboard
65% of the code is implemented for you:
โ
Line chart with weather data (fully working)
โ
Bar chart with stock prices (fully working)
โ
Doughnut chart with device distribution (fully working)
โ
Responsive chart layouts (fully working)
โ ๏ธ Real-time chart updates (TODO for you)
โ ๏ธ Chart customization options (TODO for you)
โ ๏ธ Advanced features (TODO for creativity)
First, test the working charts to see how data transforms into visualizations
Experiment with the buttons to understand the chart lifecycle
Then complete the TODO sections to add real-time updates
Finally, customize and enhance with your own creative features
Implement the startRealTimeUpdates() function to automatically refresh weather data.
Requirements:
Update the line chart every 5 seconds with new temperature data
Show visual indicator when chart is updating
Stop updates when "Clear All Charts" is clicked
Success Criteria:
Chart animates smoothly with each update
Temperature values change realistically (+/-2 degrees)
User can start/stop real-time updates
Console logs each update timestamp
Hint: Use setInterval() and modify the existing weather data slightly for each update.
Add a color picker to customize chart appearance.
Requirements:
Create color input controls for each chart type
Update chart colors dynamically when user picks new colors
Save color preferences to localStorage
Restore saved colors on page load
Success Criteria:
Each chart can have its own color scheme
Colors persist after page refresh
Reset button restores default colors
Color changes update smoothly without full chart redraw
Implement sorting functionality for the stock price bar chart.
Requirements:
Add buttons: "Sort A-Z", "Sort Z-A", "Sort by Price"
Update chart data based on selected sort order
Animate transitions between sort orders
Display current sort method
Success Criteria:
All three sort methods work correctly
Chart updates smoothly with animation
Labels and data stay synchronized
Active sort button is highlighted
Add interactive filtering to the device distribution doughnut chart.
Requirements:
Click on legend items to hide/show segments
Display only devices ``with >15``% market share
Show/hide small segments (<5% share)
Update percentages when segments are hidden
Success Criteria:
Clicking legend toggles segment visibility
Percentages recalculate correctly
Chart redraws with smooth animation
At least one segment always remains visible
Implement chart export functionality to save charts as PNG images.
Requirements:
Add "Download Chart" button for each chart
Use Chart.js toBase64Image() method
Generate filename with chart type and timestamp
Trigger browser download automatically
Success Criteria:
Downloads work in all modern browsers
Image quality matches screen display
Filename format: chart-[type]-[timestamp].png
Transparent background option available
One. Line Chart (Weather Data)
Purpose: Show trends over time
Best for: Temperature, stock prices, website traffic
Features: Filled areas, multiple datasets, smooth curves
2. Bar Chart (Stock Data)
Purpose: Compare values across categories
Best for: Sales figures, survey results, comparisons
Features: Colorful bars, hover interactions, sorting
3. Doughnut Chart (Device Distribution)
Purpose: Show proportions and percentages
Best for: Market share, demographics, resource allocation
Features: Interactive segments, legend, percentage labels
javascript
const ctx = document .getElementById ('myChart' ).getContext ('2d' );
const myChart = new Chart (ctx, {
type : 'line' ,
data : {
labels : ['Jan' , 'Feb' , 'Mar' ],
datasets : [{
label : 'Sales' ,
data : [12 , 19 , 3 ],
borderColor : '#4CAF50' ,
backgroundColor : 'rgba(76, 175, 80, 0.1)'
}]
},
options : {
responsive : true ,
scales : { y : { beginAtZero : true } }
}
});
myChart.data .datasets [0 ].data = [15 , 22 , 8 ];
myChart.update ();
javascript
function transformWeatherData (apiResponse ) {
return {
labels : apiResponse.dates ,
datasets : [{
label : 'Temperature (ยฐF)' ,
data : apiResponse.temperatures ,
borderColor : '#FF6384' ,
fill : true ,
tension : 0.4
}]
};
}
Responsive grid layout that adapts from 2 columns to 1 on mobile
Loading states with animated spinners during data fetch
Chart legends with clickable items for filtering
Hover tooltips showing exact values for each data point
Mock API functions simulating real weather/stock/analytics APIs
Error handling with fallback data when APIs fail
Data validation ensuring chart data is properly formatted
Memory cleanup destroying old charts before creating new ones
Clear TODO sections marked with comments for easy identification
Helper functions for data transformation and formatting
Detailed comments explaining Chart.js configuration options
Console logging for debugging and learning
Open Developer Tools (F12 in most browsers)
Check Console tab for Chart.js errors
Use Network tab to verify API calls (even if mocked)
Inspect Elements to see canvas rendering
Add console.log() before chart.update() to debug data
Issue: Chart not displaying
Solution: Ensure canvas element has width/height and Chart.js CDN is loaded
Issue: Chart looks pixelated
Solution: Chart.js handles retina displays automatically - check canvas resolution
Issue: Updates not animating
Solution: Call chart.update() not chart.render() - update triggers animations
Issue: "Cannot read property 'data' of null"
Solution: Check if chart was destroyed - recreate chart instance if needed
Issue: Colors not changing
Solution: Update datasets[0].backgroundColor then call chart.update()
Ready for more? Try these bonus features:
Chart themes: Create light/dark theme toggle for all charts
Data range selector: Filter line chart to show last 7, 14, or 30 days
Zoom controls: Add zoom in/out buttons for detailed data inspection
Print styles: Create CSS for chart printing
Mixed chart types: Combine line and bar data in same chart
Annotation plugins: Add vertical lines marking important events
Multiple axes: Show temperature in both Fahrenheit and Celsius
Data comparison: Overlay current vs. previous period data
Voice commands: Use Web Speech API to control charts
Real API integration: Connect to OpenWeatherMap or Alpha Vantage
Chart animations: Create custom animation sequences on load
Dashboard builder: Let users arrange and customize chart layouts
Canvas API: How Chart.js renders visualizations
Data Structures: Organizing data for optimal charting
Animation Timing: requestAnimationFrame and smooth updates
Memory Management: Destroying charts to prevent leaks
OpenWeatherMap: Free weather data API
Alpha Vantage: Stock market data API (free tier)
JSONPlaceholder: Mock API for testing
News API: Real-time news data for trending charts
Your project is complete when:
โ
All 5 TODO functions are implemented
โ
Charts update dynamically with new data
โ
Real-time updates work smoothly
โ
Color customization persists
โ
Export functionality generates valid images
โ
Code is clean with proper comments
โ
All features work on mobile devices
Once you complete this project, you'll have:
Mastered Chart.js fundamentals for data visualization
Learned how to transform API data into visual formats
Created interactive, responsive charts
Built a portfolio-ready dashboard application
Gained skills applicable to analytics dashboards and reporting tools
This visualization knowledge complements your API integration skills perfectly - you can now fetch data AND present it beautifully!
Need Help?
Check the browser console for Chart.js-specific errors
Review the working chart examples to understand the pattern
Test each TODO independently before combining features
Use Chart.js documentation for configuration options
Examine the canvas element in DevTools to debug rendering
Next Steps: Practice with Activity 8 (Caching) to learn data persistence patterns that complement visualization workflows.
Happy visualizing! ๐โจ