Refactoring legend positioning function