Integrate charts & ML predictions in your web app with our step-by-step guide. Boost engagement and data insights today!

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
// Import Flask module for web routing and JSON support
from flask import Flask, request, jsonify
app = Flask(**name**)
// Assume you have a pre-trained ML model loaded, e.g., from a pickle file
// For demonstration, we simulate a prediction function
def get_prediction(input_data):
// Simulate a prediction logic
prediction = sum(input_data) / len(input_data) // e.g., calculating an average
return prediction
// Define a route for predictions
@app.route('/predict', methods=['POST'])
def predict():
data = request.get\_json()
// Extract relevant data from the request JSON
input\_data = data.get('values', [])
if not input\_data:
return jsonify({'error': 'No input data provided'}), 400
prediction = get_prediction(input_data)
// Return the prediction in JSON format
return jsonify({'prediction': prediction})
// Run the Flask application
if **name** == '**main**':
app.run(debug=True)
// JavaScript code to fetch ML prediction from the API
const inputValues = [10, 20, 30, 40]; // example input for the ML model
fetch('http://localhost:5000/predict', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ values: inputValues })
})
.then(response => response.json())
.then(data => {
// Extract prediction result from the response
const prediction = data.prediction;
// After receiving the prediction, feed it into the chart for visualization
updateChart(prediction);
})
.catch(error => {
console.error('Error fetching prediction:', error);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ML Prediction Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<canvas id="predictionChart" width="400" height="200"></canvas>
<script src="chart-script.js"></script>
</body>
</html>
// Assuming this code is in 'chart-script.js'
// Initialize the chart with dummy data
const ctx = document.getElementById('predictionChart').getContext('2d');
const predictionChart = new Chart(ctx, {
type: 'line', // or 'bar', 'pie', etc. depending on your requirements
data: {
labels: ['Initial'], // X-axis labels (could represent time or categories)
datasets: [{
label: 'ML Prediction',
data: [0], // initial placeholder data
backgroundColor: 'rgba(54, 162, 235, 0.2)', // transparency for the fill
borderColor: 'rgba(54, 162, 235, 1)', // chart line color
borderWidth: 1
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true // ensure the y-axis starts at 0
}
}
}
});
// Function to update the chart with the new prediction
function updateChart(prediction) {
// Push new label and data point to reflect the updated prediction
predictionChart.data.labels.push('New Prediction');
predictionChart.data.datasets[0].data.push(prediction);
// Re-render the chart to display updated data
predictionChart.update();
}
// Function to fetch prediction and update the chart periodically
function fetchAndUpdate() {
fetch('http://localhost:5000/predict', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ values: [/_ dynamic or static input values _/] })
})
.then(response => response.json())
.then(data => {
const prediction = data.prediction;
updateChart(prediction);
})
.catch(error => {
console.error('Error during polling:', error);
});
}
// Poll API every 5000 milliseconds (5 seconds)
setInterval(fetchAndUpdate, 5000);
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â