factored out the plotting part of the code