refactored plotting function