How can the issue of repeated legends and incorrect display in saved files be resolved when using jpgraph in PHP?

The issue of repeated legends and incorrect display in saved files when using jpgraph in PHP can be resolved by ensuring that the legends are only added once and that the graph is properly rendered before saving the file. This can be done by checking if the legend has already been added before adding it and by calling the Stroke() method before saving the file.

// Check if legend has already been added
if (!$graph->legend->HasLegend()) {
    $graph->legend->SetLayout(LEGEND_HOR);
    $graph->legend->Pos(0.5, 0.98, 'center', 'bottom');
    $graph->legend->SetColumns(2);
    $graph->Add($lineplot);
}

// Display the graph
$graph->Stroke('output.png');