This notebook was adapted from thePython Data Science Handbook()by Jake VanderPlas; the content is availableon GitHub().Visualization with MatplotlibMatplotlib is a multi-platform data visualization library built on NumPy arrays.General Matplotlib TipsImporting MatplotlibJust as we use thenpshorthand for NumPy, we will use some standard shorthands for Matplotlib imports:In :Thepltinterface is what we will use most often.Setting StylesWe will use theplt.styledirective to choose appropriate aesthetic styles for our figures. Here we will set theclassicstyle, which ensures that the plots we create use the classic Matplotlib style:In :show()or Noshow()? How to Display Your PlotsThe best use of Matplotlib differs depending on how you are using it; roughly, the three applicable contexts areusing Matplotlib in a script, in an IPython terminal, or in an IPython notebook.Plotting from a scriptIf you are using Matplotlib from within a script, the functionplt.show()is your friend.plt.show()starts anevent loop, looks for all currently active figure objects, and opens one or more interactive windows that displayyour figure or figures.So, for example, you may have a file calledmyplot.pycontaining the following:importmatplotlibasmplimportmatplotlib.pyplotaspltplt.style.use('classic')
# ------- file: myplot.py ------importmatplotlib.pyplotaspltimportnumpyasnpx = np.linspace(0,10,100)plt.plot(x, np.sin(x))plt.plot(x, np.cos(x))plt.show()You can then run this script from the command-line prompt, which will result in a window opening with yourfigure displayed:$ python myplot.pyTheplt.show()command does a lot under the hood, as it must interact with your system's interactivegraphical backend. The details of this operation can vary greatly from system to system and even installation toinstallation, but matplotlib does its best to hide all these details from you.One thing to be aware of: theplt.show()command should be usedonly onceper Python session, and ismost often seen at the very end of the script. Multipleshow()commands can lead to unpredictable backend-dependent behavior, and should mostly be avoided.Plotting from an IPython shellIt can be very convenient to use Matplotlib interactively within an IPython shell. IPython is built to work well withMatplotlib if you specify Matplotlib mode. To enable this mode, you can use the%matplotlibmagic commandafter startingipython:In :%matplotlibUsing matplotlib backend: TkAggIn :importmatplotlib.pyplotaspltAt this point, anypltplot command will cause a figure window to open, and further commands can be run toupdate the plot. Some changes (such as modifying properties of lines that are already drawn) will not drawautomatically: to force an update, useplt.draw(). Usingplt.show()in Matplotlib mode is not required.