Fixed issue with piecewise function and updated legend generation code