phpgraphicsjpgraph

How to reverse the Y axis with JPgraph


In JPgraph there is no obvious way to have the yaxis ticks move from lowest at the top to highest at the bottom (reveresed axis).

This question has been asked (here) [https://groups.google.com/g/jpgraph/c/23gu1IA0e9c] but provides no answer and the discussion is closed to answers.

I add an answer to my own question below so that others struggling with this issue can find it in the future.


Solution

  • The solution described here and comes from the the manual, but is not very easy to find via google.

    The trick is to:

    1. Make the desired series its own negative (so the highest numer is the lowest and the lowest is the highest).
    2. Use a callback function to rewrite the y axis labels to the negative of the internal data's values (i.e. revert them to their original values).

    The code below comes from this example in the JPgraph package, with some additional annotation on my part.

    <?php // content="text/plain; charset=utf-8"
    require_once ('jpgraph/jpgraph.php');
    require_once ('jpgraph/jpgraph_line.php');
    
    //*******************************************
    // This is the call back which will return the negative of the internal value used in the graph 
    // Step 2. above.
    //************************************
     
    
    function _cb_negate($aVal) {
        return round(-$aVal);
    }
     
    // A fake depth curve
    $ydata = array(0,1,4,5,8,9,10,14,16,16,16,18,20,20,20,22,22.5,22,19,19,15,15,15,15,10,10,10,6,5,5,5,4,4,2,1,0);
     
    
    //****************************************
    // This is the preparation bit (my step 1)
    //  Take the original data and make it equal to its negative
    //****************************************
    
    
    $n = count($ydata);
    for($i=0; $i<$n; ++$i) {
        $ydata[$i] = round(-$ydata[$i]);
    }
     
    // Basic graph setup
    $graph = new Graph(400,300);
    $graph->SetScale("linlin");
    $graph->img->SetMargin(50,50,60,40);    
    $graph->SetMarginColor('darkblue');
    $graph->SetColor('darkblue');
    $graph->SetAxisStyle(AXSTYLE_BOXOUT);
    $graph->SetBackgroundImage("blueblack400x300grad.png",1);
    //$graph->SetBackgroundImage("lightbluedarkblue400x300grad.png",1);
     
    $graph->title->Set("Depth curve. Dive #2");
    $graph->title->SetFont(FF_FONT1,FS_BOLD);
    $graph->title->SetColor("white");
     
    $graph->subtitle->Set("(Negated Y-axis)");
    $graph->subtitle->SetFont(FF_FONT1,FS_NORMAL);
    $graph->subtitle->SetColor("white");
     
    // Setup axis
    $graph->yaxis->SetLabelFormatCallback("_cb_negate");
    $graph->xaxis->SetColor("lightblue","white");
    $graph->yaxis->SetColor("lightblue","white");
    $graph->ygrid->SetColor("blue");
     
     
    $lp1 = new LinePlot($ydata);
    $lp1->SetColor("yellow");
    $lp1->SetWeight(2);
     
     
    $graph->Add($lp1);
    $graph->Stroke();
    ?>