Refactor plotting code into functions