Dynamic Data Visualization in Laravel with Python's Matplotlib

In this tutorial, I’ll show you how to integrate Python’s powerful data visualization library, Matplotlib, with Laravel to create dynamic and interactive data visualizations. By using Python in Laravel, we can generate high-quality charts and graphs directly from our backend.

This guide will walk you through setting up the environment, running Python code from Laravel, and displaying Matplotlib charts in your Laravel views.

Dynamic Data Visualization in Laravel with Python's Matplotlib

Dynamic Data Visualization in Laravel with Python's Matplotlib

 

Step 1: Setting Up Python and Matplotlib

First, ensure you have Python installed. To check if Python is installed, run:

python --version

Next, install Matplotlib by running:

pip install matplotlib

You may also want to create a virtual environment to keep your project dependencies organized:

python -m venv laravel-matplotlib
source laravel-matplotlib/bin/activate  # On macOS/Linux

 

Step 2: Setting Up Laravel and Installing Dependencies

Create a new Laravel project (or use an existing one):

composer create-project --prefer-dist laravel/laravel laravel-matplotlib
cd laravel-matplotlib

In this setup, we’ll use the symfony/process package to execute Python scripts from Laravel:

composer require symfony/process

 

Step 3: Creating a Python Script to Generate the Chart

Create a directory within your Laravel project to store Python scripts. Inside, create a Python script named generate_chart.py:

mkdir -p python_scripts
touch python_scripts/generate_chart.py

Edit generate_chart.py with the following code to create a sample chart:

# python_scripts/generate_chart.py
import matplotlib.pyplot as plt
import sys

def generate_chart(data_points):
    plt.figure(figsize=(10, 6))
    plt.plot(data_points, color="blue", marker="o")
    plt.title("Sample Data Chart")
    plt.xlabel("X-axis")
    plt.ylabel("Y-axis")
    plt.grid(True)
    plt.savefig("storage/app/public/sample_chart.png")

if __name__ == "__main__":
    data_points = [float(x) for x in sys.argv[1].split(",")]
    generate_chart(data_points)

This script takes a list of data points as input, generates a line chart, and saves the output to Laravel’s storage/app/public folder.

 

Step 4: Creating a Laravel Controller to Handle Python Execution

In Laravel, create a controller to call this Python script and pass data points to it:

php artisan make:controller ChartController

Edit the ChartController.php to include the code below:

// app/Http/Controllers/ChartController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

class ChartController extends Controller
{
    public function generateChart(Request $request)
    {
        // Convert the request data to a comma-separated string
        $dataPoints = implode(",", $request->input('data_points'));

        // Define the Python script path
        $scriptPath = base_path('python_scripts/generate_chart.py');

        // Run the Python script using Symfony Process
        $process = new Process(["python3", $scriptPath, $dataPoints]);
        $process->run();

        // Check if the process was successful
        if (!$process->isSuccessful()) {
            throw new ProcessFailedException($process);
        }

        // Return the chart image as a response
        return response()->json(['chart_url' => asset('storage/sample_chart.png')]);
    }
}

This controller receives an array of data points, calls the Python script with those points, and then provides the generated chart’s URL.

 

Step 5: Setting Up a Route and View

Define a route to connect the generateChart function to your application. Add this line to routes/web.php

use App\Http\Controllers\ChartController;

Route::post('/generate-chart', [ChartController::class, 'generateChart'])->name('generate.chart');

Create a simple form in a Blade view to submit data points for chart generation:

<!-- resources/views/generate_chart.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Chart</title>
</head>
<body>
    <h1>Dynamic Data Visualization in Laravel with Matplotlib</h1>
    
    <form id="chartForm">
        <label for="data_points">Enter Data Points (comma-separated):</label>
        <input type="text" id="data_points" name="data_points" required>
        <button type="submit">Generate Chart</button>
    </form>
    
    <div id="chartDisplay">
        <!-- The chart image will appear here -->
    </div>
    
    <script>
        document.getElementById('chartForm').addEventListener('submit', function (e) {
            e.preventDefault();
            
            let dataPoints = document.getElementById('data_points').value;

            fetch('{{ route("generate.chart") }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify({ data_points: dataPoints.split(',') })
            })
            .then(response => response.json())
            .then(data => {
                if (data.chart_url) {
                    document.getElementById('chartDisplay').innerHTML = `<img src="${data.chart_url}" alt="Generated Chart">`;
                }
            })
            .catch(error => console.error('Error:', error));
        });
    </script>
</body>
</html>

 

Step 6: Testing the Application

Start the Laravel development server:

Start the Laravel development server

Enter some comma-separated data points, like 1,2,3,4,5,6,7, and click "Generate Chart." After a few seconds, the generated chart should appear on the page

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS