Visualization with Matplotlib
Visualization with Matplotlib
Introduction
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.
Matplotlib makes easy things easy and hard things possible.
- Create
- Develop publication quality plots with just a few lines of code
- Use interactive figures that can zoom, pan, update…
- Customize
- Take full control of line styles, font properties, axes properties…
- Export and embed to a number of file formats and interactive environments
- Extend
- Explore tailored functionality provided by third party packages
- Learn more about Matplotlib through the many external learning resources
Installation
1 | pip install -U Matplotlib pandas pycairo scipy wxPython |
Plotting
1 | import matplotlib.pyplot as plt |
Saving Figures to File
1 | # rsvg-convert -d 300 -p 300 -f pdf -a --keep-image-data -o my_figure_3.pdf my_figure.svg |
Matplotlib Backends
Matplotlib is a plotting library. It relies on some backend to actually render the plots.
If you omit the default backend parameter, the first working backend from the following list is used:
1 | MacOSX Qt5Agg Gtk3Agg TkAgg WxAgg Agg |
To get backends that are interactive or integrate into your operating system GUI, you need to know what OS you’re running and what kind of backends have been compiled into your matplotlib library.
There’s no easy way to find out what backends are available to be used, instead you can only really find out either by trial and error, or if you have access to the compilation logs.
However you can find out what backend the matplotlib library is currently set to and you can find out the string keys that point to different backends.
This will show you what the default backend of matplotlib has been set to. If you don’t have any confounding environment variables nor a matplotlibrc file.
1 | import matplotlib.pyplot as plt |
The list of backend string keys can be acquired with:
1 | import matplotlib.rcsetup as rcsetup |
You can then try to switch to it. These are the ways to do this:
The first is to use it just before importing pyplot.
1 | import matplotlib as mpl |
The best way is to use an environment variable:
1 | MPLBACKEND=Qt4Agg python -c 'import matplotlib.pyplot as plt; print(plt.get_backend())' |
Improve the resolution
Change the dpi settings
1 | import matplotlib as mpl |
Change the image format to a vector format
1 | import matplotlib as mpl |