Moved plotting code to its own function