Refactored plotting code, moved to separate function