Improved code, with sub-functions to create plot on device of choice