phpjpgraph

Add an horizontal line or a band to jpGraph


I'm trying to add a simple horizontal line (or a band) to my graph and for some reasons, it doesn't show anything.

I used the lines:

$graph->AddLine(new PlotLine(HORIZONTAL,0,"black",2));

or

$graph->AddBand(new PlotBand(HORIZONTAL,BAND_RDIAG,0, "max", "red", 2));

...as shown here https://jpgraph.net/download/manuals/classref/Graph.html

Is there anything else I should do? Is there a specific place where I should put it? I put them just after the $graph->Add($lineplot);

Thanks for your help


Solution

  • First of all, you need to include (require) the jpgraph_plotline.php file, such as:

    require_once ('jpgraph-4.2.5/src/jpgraph_plotline.php');
    

    Then, before the line $graph->Stroke();, add the code for plotting the line, such as:

    // Create a line to add as markers
    $l1 = new PlotLine(HORIZONTAL, 5, 'green:1.5', 10);
     // Add lines to the plot
    $graph->AddLine($l1);
    

    So, the whole code will be like:

    <?php 
    require_once ('jpgraph-4.2.5/src/jpgraph.php');
    require_once ('jpgraph-4.2.5/src/jpgraph_line.php');
    require_once ('jpgraph-4.2.5/src/jpgraph_plotline.php');
    
    $datay1 = array(20,15,23,15);
    $datay2 = array(12,9,42,8);
    $datay3 = array(5,17,32,24);
    
    // Setup the graph
    $graph = new Graph(300,250);
    $graph->SetScale("textlin");
    $graph->title->Set('StackOverflow.com');
    $graph->SetBox(false);
    $graph->SetMargin(40,20,36,63);
    
    // Create the first line
    $p1 = new LinePlot($datay1);
    $graph->Add($p1);
    $p1->SetColor("#6495ED");
    $p1->SetLegend('Line 1');
    
    // Create the second line
    $p2 = new LinePlot($datay2);
    $graph->Add($p2);
    $p2->SetColor("#B22222");
    $p2->SetLegend('Line 2');
    
    // Create the third line
    $p3 = new LinePlot($datay3);
    $graph->Add($p3);
    $p3->SetColor("#FF1493");
    $p3->SetLegend('Line 3');
    
    // Create a line to add as markers
    $l1 = new PlotLine(HORIZONTAL, 5, 'green:1.5', 10);
     // Add lines to the plot
    $graph->AddLine($l1);
    
    // Output the result
    $graph->Stroke();
    ?>
    

    In this way, the plot line will be added on the line chart (as below - a green line at y position 5, width :10)

    enter image description here

    Just do the same for PlotBand, if you wish.

    Enjoy...