Refactor plotting code to a function