I solved this by catching various cases:
// I first set the margin when all scores are positive
$margin=10;
// I calculate the width between the top score and the bottom score to use in calulating the margins in the cases below
if ( abs(max($datay))+abs(min($datay)) == 0 ) {
$spreadRatio = 0;
} else {
$spreadRatio = abs(min($datay))/(abs(max($datay))+abs(min($datay)));
}
// if the maximum score is positive and the minimum score is negative then apply a combination of the chart width times the chart gap between top score and bottom score
if (min($datay)<0) {
$margin=$spreadRatio * ($width-$left-$right)+10;
}
// if all scores are negative then margin is just the space to the left of the chart
if (max($datay)<0) {
$margin=($width-$left-$right)+10;
}