0

I'm trying to display a plot that is generated with plotly in python, inside my laravel application.

When I execute python3.8 ../storage/app/public/rcs/line-chart.py command in my terminal from the public directory of my laravel project, the plot is displayed. However, when I send a request to my laravel application to execute the same command using symfony process component, nothing is displayed.

Here is the controller responsible for executing the command and generating the data:

<?php

namespace App\Http\Controllers;

use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

class FooController extends Controller
{
    public function bar()
    {
        $process = new Process(['python3.8', '../storage/app/public/line-chart.py']);

        try {
            $process->mustRun();
            return $process->getOutput();
        } catch (ProcessFailedException $exception) {
            return $exception->getMessage();
        }
    
    }
}

The plot is generated kind of like this:

import plotly.express as px

df = px.data.gapminder().query("continent=='Oceania'")
fig = px.line(df, x="year", y="lifeExp", color='country')
fig.show()

PS: Besides using plotly for javascript is there any better way than using symfony process component to achieve the desired result?

gp_sflover
  • 3,460
  • 5
  • 38
  • 48
Farzin
  • 359
  • 1
  • 4
  • 21

1 Answers1

0

Okay apparently one way is to save the plot as an HTML file and then display it as a view in laravel. But I'm not marking this as an answer in hope that someone else posts a better answer.

So this is how it works:

import plotly.express as px

df = px.data.gapminder().query("continent=='Oceania'")
fig = px.line(df, x="year", y="lifeExp", color='country')
fig.showwrite_html('/paht/to/output/file')

And then in the controller:

<?php

namespace App\Http\Controllers;

use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

class FooController extends Controller
{
    public function bar()
    {
        $process = new Process(['python3.8', '../storage/app/public/line-chart.py']);

        try {
            $process->mustRun();
            return view('/paht/to/output/file');
        } catch (ProcessFailedException $exception) {
            return $exception->getMessage();
        }
    
    }
}


Farzin
  • 359
  • 1
  • 4
  • 21