I tried running this code but didn't get the error. Initially I didn't even get the legend. I had to manually force it to appear by writing the the legend('show') command at the end of the above code. May be some of the options in the documentation link below may help
https://www.mathworks.com/help/matlab/ref/legend.html