Improve the legend function