MPL Plotter is a Matplotlib based Python plotting library built with the goal of delivering publication-quality plots concisely.

Overview

MPL Plotter

alt text

MPL Plotter is a Matplotlib based Python plotting library built with the goal of delivering publication-quality plots concisely. The full API documentation is available here. Read on to get started.

alt text

Table of Contents

1. Introduction

2. Install

3. Map of the library

4. Getting started

4.1 2D

4.2 3D

5. comparison and panes

5.1 comparison

5.2 panes

6. Presets

6.1 Standard presets

6.2 Custom presets_

7. Matplotlib compatibility

7.1 Retrieving axes, figures

7.2 Using Matplotlib's axis tiling

1. Introduction

Making plots for technical documents can be a time sink. MPL Plotter aims to reduce that overhead by allowing you to effortlessly and concisely

  • Generate publication quality plots with a single call
  • Plot curve comparisons
  • Create figures with many plots

It is opinionated but built with flexibility in mind, which means that

  • No default can't be changed
  • Any and all further customization with Matplotlib is compatible. From ticks to legends to extra axes to whatever suits your needs

There's two ways to use MPL Plotter (plus any Matplotlib before or after):

It does the job for me and I expand it when it can't. Hope you find some use in it!

2. Install

pip install mpl_plotter

All dependencies will be checked for and installed automatically. They can be found in setup.py under install_requires.

Linux

PyQt5 may fail to install in Linux, prompting the following error:

FileNotFoundError: [Errno 2] No such file or directory: '/tmp/pip-build-4d8suz7p/PyQt5/setup.py'

To solve this, make sure pip is up to date and install PyQt5 5.14.0. Check this StackOverflow answer for further reference.

pip3 install --upgrade pip
pip3 install pyqt5==5.14.0

3. Map of the library

This is the map of the library for import reference.

module method directory
module method dir/
  • mpl_plotter
    • figure
    • get_available_fonts
    • two_d
      • line
      • scatter
      • heatmap
      • quiver
      • streamline
      • fill_area
      • comparison
      • panes
      • floating_text
    • three_d
      • line
      • scatter
      • surface
      • floating_text
    • presets
      • publication
        • two_d
        • three_d
      • precision
        • two_d
        • three_d
      • custom
        • two_d
        • three_d
        • generate_preset_2d
        • generate_preset_3d
      • data/
        • publication
        • precision
    • color
      • schemes
        • colorscheme_one
        • custom
      • functions
        • complementary
        • delta
        • mapstack

4. Getting started

In this section we'll go from the the most basic plot to a fairly customized version in 2 and 3 dimensions. The line demo scripts can be found in _demo/scripts/line_demos/.

4.1 2D

For this example I'll use the 2D line class. Except for plot-specific arguments (line width etc. in this case), you can use the same inputs in this example with any of the other 2D plotting classes. Check the API reference for all general and specific arguments, or call help( ) in your shell to access the docstrings.

As follows from the map above, the import to use the 2D line class is:

from mpl_plotter.two_d import line

And the following is the most basic MPL Plotter call, which will generate the image below (no input, and sin wave respectively).

line(show=True) x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
line(x=x, y=y, show=True)
alt text alt text

Two important features are apparent:

  1. MPL Plotter provides mock plots for every plotting class, so you can get straight into action and see what each does
  2. MPL Plotter is somewhat "opinionated" and sets up quite a few parameters by default. This is based purely on my preference. You may not agree and you're more than welcome to play around with them!

Two more examples (results in the table below):

  1. We can add some customization to make our line look a bit better:

     line(show=True, demo_pad_plot=True, spines_removed=None)
    

    Our line has now some margins to breathe while the ticks are placed at the maximum and minimums of our curve, and no spines are removed.

  2. Lastly, an example using some of the parameters you can change:

     line(norm=True, line_width=4,
          aspect=1,
          show=True, demo_pad_plot=True,
          x_label="x", x_label_size=30, x_label_pad=-0.05,
          y_label="$\Psi$", y_label_size=30, y_label_rotation=0, y_label_pad=20,
          title="Custom Line", title_font="Pump Triline", title_size=40, title_color="orange",
          tick_color="darkgrey", workspace_color="darkred", tick_ndecimals=4,
          x_tick_number=12, y_tick_number=12,
          x_tick_rotation=35,
          color_bar=True, cb_tick_number=5, cb_pad=0.05,
          grid=True, grid_color="grey")
    
1 2
alt text alt text

4.2 3D

Same applies in 3D.

Examples
alt text alt text alt text

5. Curve comparisons and multiple pane plots

from mpl_plotter.two_d import comparison, panes

5.1 comparison

Plot any number of curves in a single plot. Axis limits will be set to the maximum and minimum of all your curves. No data will be left out, among other niceties.

As to inputs: inputs must match (2 xs and 3 ys won't work), BUT the following inputs are all valid:

x y result notes
array array 1
array [array, array] 2 Both ys share x
[array, array] [array, array] 2 Each y has an x
[n*[array]] [n*[array]] n Each y has an x

As to using different plotting functions for different curves:

  • You can specify a plotting function for each curve in the plot, a custom one for all curves, or not specify any (defaulting to lines). How? Read below (or check the code block below that). This is nice as it allows to concisely combine lines, scatter plots, and any other of the MPL Plotter plotting classes in a single.

As any and all other arguments:

  • Singular arguments: the regular MPL Plotter plotting class arguments. Apply to all curves in the plot.
  • Plural arguments: pass a list of arguments, one for each curve. The result is as you'd imagine.
from mpl_plotter.two_d import comparison, line, scatter
        
def f(x, y, **kwargs):
    line(x, y,
         line_width=2,
         **kwargs)
def g(x, y, **kwargs):
    scatter(x, y,
            marker="D",
            point_size=10,
            **kwargs)
def h(x, y, **kwargs):
    scatter(x, y,
            marker="s",
            point_size=5,
            **kwargs)

comparison([x, x, x],
           [u, v, w],
           [f, g, h],
           plot_labels=["sin", "cos", "tan"],
           zorders=[1, 2, 3],
           colors=['C1', 'C2', 'C3'],
           alphas=[0.5, 0.5, 1],
           x_custom_tick_labels=[0, r"$\frac{\pi}{8}$", r"$\frac{\pi}{4}$"],
           show=show, backend=backend
           )

alt text

5.2 panes

The panes function allows for the plotting of a series of graphs in side-by-side panes. It uses the comparison function under the hood, so the same input guidelines apply. Inputs obviously change.

As to inputs: again inputs must match (again 2 xs and 3 ys won't work), BUT the following inputs are all valid:

x y result notes
array array 11
array [array, array] 12 Both ys share x
[n*[array]] [n*[array]] 1n Each y has an x
array [array, array] 21 Both ys share x
[array, array] [array, array] 21 Each y has an x
array [n*[array], n*[array]] 2n All curves in all (2) panes share a single x
[array, array] [n*[array], n*[array]] 2n All curves in each pane share an x
[n*[array], n*[array]] [n*[array], n*[array]] 2n All curves in all (2) panes have their own x
[n*[array], ... up to m] [n*[array], ... up to m] mn All curves in all panes have their own x

Code

The following plots one curve per pane (3 in total):

panes(x,                   # Horizontal vector
      [u, v, y],           # List of curves to be plotted
      ["u", "v", "y"],     # List of vertical axis labels
      ["a", "b", "c"]      # List of legend labels 
      )

alt text

And the following plots an arbitrary number of curves per pane. As you can see, you just need to input n lists of m curves (where m=2 in the example below), and you will get a plot with n panes, with m curves in each.

    panes(x,                               # Horizontal vector
          [[u, uu], [v, vv], [y, yy]],     # List of pairs of curves to be compared
          ["u", "v", "y"],                 # List of vertical axis labels
          ["a", "b"]                       # List of legend labels
          )

alt text

Demo

alt text

And same goes for n panes with a number m of curves in each!

alt text

6. Presets

TL;DR: Take a parameter dictionary and forget about function inputs.

6.1 Standard presets

Standard presets are available to remove overhead. They're tailored for my use cases but may be useful anyway.

alt text alt text alt text alt text alt text alt text alt text alt text
alt text alt text alt text alt text alt text alt text alt text alt text

Publication

It is a common mistake to make a figure for a paper with unreadable labels. This preset tries to solve that, generating plots optimized to be printed on a small format, in side-by-side plots or embedded in a column of text.

from mpl_plotter.presets.precision import two_d
from mpl_plotter.color.schemes import one           # Custom colorscheme

x = np.linspace(0, 4, 1000)
y = np.exp(x)
z = abs(np.sin(x)*np.exp(x))

two_d.line(x, z, aspect=0.05, color=one()[-2], show=True)

alt text

Precision

Made to plot functions large on the screen, with equal x and y scales to avoid skewing the variables, and many ticks to visually inspect a signal.

from mpl_plotter.presets.precision import two_d

two_d.line(x, z, aspect=0.05, color=one()[-2], show=True)

alt text

6.2 Custom presets

Example workflow follows.

2D alt text alt text alt text alt text alt text alt text
3D alt text alt text alt text alt text alt text
  1. Use a preset creation function (generate_preset_2d or generate_preset_3d) to create a preset

     from mpl_plotter.presets.custom import generate_preset_2d
     
     generate_preset_2d(preset_dest="presets", preset_name="MYPRESET", disable_warning=True, overwrite=True)
    

    A MYPRESET.py file will be created in a new (or not) presets/ directory within your project's root directory.

    • If no preset_dest is provided, MYPRESET.py will be saved in your root directory.
    • If no preset_name is provided, the preset will be saved as preset_2d.py.
    • By setting disable_warning=True, console output reminding you of the risk of rewriting your preset will be suppressed.
    • By setting overwrite=True, every time your run the preset creation function, it will overwrite the previously created preset with the same name (rather inconvenient, but who knows when it can come in handy).

    This file has a preset dictionary inside, with all editable parameters inside it, and commented out. Eg:

     preset = { 
         # Basic 
         # "plot_label": None, 
         # Backend 
         # "backend": "Qt5Agg", 
         # Fonts 
         # "font": "serif",
         ...
     }
    

    By uncommenting certain lines, those parameters will be read and used to shape your plots.

  2. Modify MYPRESET.py according to your needs.

  3. Import mpl_plotter.presets.custom.two_d (or three_d if working with a 3D preset) and initiate it with MYPRESET

    my_preset_scatter = my_plot_family.scatter ">
     from mpl_plotter.presets.custom import two_d
     
     my_preset_plot_family = two_d(preset_dir="presets", preset_name="MYPRESET")
     
     my_preset_line = my_plot_family.line
     
     # You can create further plotting classes spawning from my_preset_plot_family:
     # Eg        --->        my_preset_scatter = my_plot_family.scatter
    
  4. Call a plotting function child of two_d, setting any extra parameters appropriately (plot title, etc.)

     my_preset_line(show=True, demo_pad_plot=True, color="blue", title="TITLE", title_size=200, aspect=1)
    

    The result of this example, its 3D version, and demos for all other available 2D and 3D plots can be seen in the table at the beginning of the section.

  5. Make as many plots as you wish.

7. Matplotlib compatibility

7.1 Retrieving axes, figures

The axis and figure on which each class draws are instance attributes. To retrieve them and continue modifications using standard Matplotlib:

from mpl_plotter.two_d import line

my_plot = line()
ax, fig = my_plot.ax, my_plot.fig

With the axis and figure, most Matplotlib functions out there can be used to further modify your plots.

7.2 Using Matplotlib's axis tiling

Matplotlib allows for subplot composition using subplot2grid. This can be used in combination with MPL Plotter:

Importantly:

  • The auxiliary function figure (from mpl_plotter.setup import figure) sets up a figure in a chosen backend. This is convenient, as if the figure is created with plt.figure(), only the default non-interactive Matplotlib backend will be available, unless matplotlib.use( ) is specified before importing pyplot.

    regular non-interactive matplotlib output fig = figure(figsize=(10, 10), backend=backend) ax0 = plt.subplot2grid((2, 2), (0, 0), rowspan=1, aspect=1, fig=fig) ax1 = plt.subplot2grid((2, 2), (1, 0), rowspan=1, aspect=1, fig=fig) ax2 = plt.subplot2grid((2, 2), (0, 1), rowspan=1, aspect=1, fig=fig) ax3 = plt.subplot2grid((2, 2), (1, 1), rowspan=1, aspect=12, fig=fig) axes = [ax0, ax1, ax2, ax3] plots = [line, quiver, streamline, fill_area] for i in range(len(plots)): plots[i](fig=fig, ax=axes[i], backend=backend ) plt.show() ">
      backend = "Qt5Agg"  # None -> regular non-interactive matplotlib output
      
      fig = figure(figsize=(10, 10), backend=backend)
      
      ax0 = plt.subplot2grid((2, 2), (0, 0), rowspan=1, aspect=1, fig=fig)
      ax1 = plt.subplot2grid((2, 2), (1, 0), rowspan=1, aspect=1, fig=fig)
      ax2 = plt.subplot2grid((2, 2), (0, 1), rowspan=1, aspect=1, fig=fig)
      ax3 = plt.subplot2grid((2, 2), (1, 1), rowspan=1, aspect=12, fig=fig)
      
      axes = [ax0, ax1, ax2, ax3]
      plots = [line, quiver, streamline, fill_area]
      
      for i in range(len(plots)):
          plots[i](fig=fig, ax=axes[i],
                   backend=backend
                   )
      
      plt.show()
    

alt text


Back to top

You might also like...
The plottify package is makes matplotlib plots more legible
The plottify package is makes matplotlib plots more legible

plottify The plottify package is makes matplotlib plots more legible. It's a thin wrapper around matplotlib that automatically adjusts font sizes, sca

matplotlib: plotting with Python
matplotlib: plotting with Python

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Check out our home page for more inform

matplotlib: plotting with Python
matplotlib: plotting with Python

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Check out our home page for more inform

Function Plotter: a simple application with GUI to plot mathematical functions
Function Plotter: a simple application with GUI to plot mathematical functions

Function-Plotter Function Plotter is a simple application with GUI to plot mathe

A Python-based non-fungible token (NFT) generator built using Samilla and Matplotlib
A Python-based non-fungible token (NFT) generator built using Samilla and Matplotlib

PyNFT A Pythonic NF (non-fungible token) generator built using Samilla and Matplotlib Use python pynft.py [amount] The intention behind this generato

A high-level plotting API for pandas, dask, xarray, and networkx built on HoloViews
A high-level plotting API for pandas, dask, xarray, and networkx built on HoloViews

hvPlot A high-level plotting API for the PyData ecosystem built on HoloViews. Build Status Coverage Latest dev release Latest release Docs What is it?

A high-level plotting API for pandas, dask, xarray, and networkx built on HoloViews
A high-level plotting API for pandas, dask, xarray, and networkx built on HoloViews

hvPlot A high-level plotting API for the PyData ecosystem built on HoloViews. Build Status Coverage Latest dev release Latest release Docs What is it?

🎨 Python Echarts Plotting Library
🎨 Python Echarts Plotting Library

pyecharts Python ❤️ ECharts = pyecharts English README 📣 简介 Apache ECharts (incubating) 是一个由百度开源的数据可视化,凭借着良好的交互性,精巧的图表设计,得到了众多开发者的认可。而 Python 是一门富有表达

🎨 Python Echarts Plotting Library
🎨 Python Echarts Plotting Library

pyecharts Python ❤️ ECharts = pyecharts English README 📣 简介 Apache ECharts (incubating) 是一个由百度开源的数据可视化,凭借着良好的交互性,精巧的图表设计,得到了众多开发者的认可。而 Python 是一门富有表达

Comments
  • Alexandria Package not Found while doing pip install

    Alexandria Package not Found while doing pip install

    I installed the library using pip (python 3.6.9) but while doing the import using from mpl_plotter.two_d import line I get the following error:

    ModuleNotFoundError                       Traceback (most recent call last)
    <ipython-input-24-3ba9be32d00b> in <module>()
    ----> 1 from mpl_plotter.two_d import line
    
    /home/svyas/.local/lib/python3.6/site-packages/mpl_plotter/two_d.py in <module>()
         13 
         14 from mpl_plotter.methods.mock_data import MockData
    ---> 15 from Alexandria.general.console import print_color
         16 from Alexandria.constructs.array import span, ensure_ndarray
         17 
    
    ModuleNotFoundError: No module named 'Alexandria'
    

    Either Alexandria should be installed via requirements automatically while installing via pip if it is a necessary library for using mpl_plotter or removed if it is not necessary?

    opened by vyas-shubham 4
  • Create MANIFEST.in

    Create MANIFEST.in

    This will bundle in LICENSE into the sdist archive on PyPI. Context: I'm trying to get this package onto conda-forge and they require license file to be included in the source code distribution.

    opened by thewchan 2
Releases(v5.5.0)
  • v5.5.0(Oct 31, 2022)

    Contour plotting method

    Unifying matplotlib's contour, contourf and plt.clabel methods.

    Other improvements

    • Default color_rules for the heatmap and surface plotters
    • Mock data methods refactored
    Source code(tar.gz)
    Source code(zip)
  • v5.4.0(Oct 8, 2022)

  • v5.3.0(Sep 14, 2022)

    • Reimplemented and improved the color bar method, adding full support for floating colorbars and generalizing it to 2 and 3D plots
    • Resolved a series of bugs in the 3D plotting methods and improved the code base
    • Increased test coverage
    Source code(tar.gz)
    Source code(zip)
  • v5.2.0(Jul 16, 2022)

  • v5.1.3(Jul 13, 2022)

  • v5.1.2(Jul 10, 2022)

  • v5.1.1(Jun 20, 2022)

  • v5.1.0(Jun 19, 2022)

  • 5.0.1(Jun 13, 2022)

  • 5.0(Jun 7, 2022)

  • 4.2.post1(Jun 6, 2022)

  • 4.2(May 25, 2022)

  • v4.1.0.post7(Nov 9, 2021)

  • v4.1.0.post6(Nov 4, 2021)

  • v4.1.0.post5(Nov 4, 2021)

  • v4.1.0.post4(Oct 27, 2021)

  • v4.1.0.post3(Oct 17, 2021)

    General:

    • Improved control over tick number.

    Comparison:

    • Added support for multiple x arrays

    Panes

    • Added support for multiple x arrays and lists of arrays
    • Added figure as input
    • Added control over plt.subplots_adjust axis positioning parameters (top, bottom, left, right, wspace, hspace)

    Scatter plots:

    • Marker class: retrieve all available Matplotlib scatter markers by index (sorted by personal preference), solid or hollow
    Source code(tar.gz)
    Source code(zip)
  • v4.1.0.post2(Oct 13, 2021)

  • v4.1.0.post1(Oct 12, 2021)

  • v4.1.0(Oct 11, 2021)

    Major rewrite of the comparison and panes functions to generalize their use to plots with:

    • Multiple panels
    • Multiple curves in each panel

    where the curves may share an x or have their own, and where plural arguments may be passed to the functions to be applied to all panels or curves.

    Source code(tar.gz)
    Source code(zip)
  • v4.1.0.pre(Oct 11, 2021)

  • v4.0.5(Sep 12, 2021)

  • v4.0.4(Sep 9, 2021)

    Package install

    Python-Alexandria required minimum version (2.0.0) specified in setup.py to ensure that pip install mpl_plotter --upgrade upgrades Python-Alexandria if a lower version is currently installed.

    Source code(tar.gz)
    Source code(zip)
  • v4.0.3(Sep 3, 2021)

  • v4.0.2(Aug 30, 2021)

  • v4.0.1(Aug 30, 2021)

  • v4.0.0(Aug 14, 2021)

    Large improvements, including breaking changes.

    Functionality

    • Library structure improved
      • Many refactorings. Please check the library map in the README for reference.
      • Code cleaned and documented to have better maintainability.
    • Comparison method improved
    • Pane plots improved

    Documentation

    • Automatic documentation with pdoc3 implemented
    • API reference website up
    • General improvements

    Development

    • CONTRIBUTING.md
    Source code(tar.gz)
    Source code(zip)
  • v3.9.2(May 25, 2021)

    New functionality:

    • Panes
      • Comparison function ready for standalone use
      • All library plot parameters passable to pane functions without conflicts
    • Single coordinate plots Bug fixes
    • Custom canvas no coordinate customization improved
    Source code(tar.gz)
    Source code(zip)
  • v3.8.8(May 18, 2021)

    New features:

    • Presets available and in working order for all available plots. Demos included in the README

    Improvements:

    • 3D plots
      • Tick label positioning, rotation
    • Install:
      • Requirements fixed. Automatic install of all dependencies should be smooth now.
      • requirements.txt included to ensure user's dependencies are up to date with repo dependencies
    Source code(tar.gz)
    Source code(zip)
  • v3.8.5(May 16, 2021)

    Project health:

    • Tests improved. Coverage.py calculation automated and coverage badge included in README. Improvements:
    • aspect: Aspect ratio now working as expected.
    • pane_fill: Pane fill for 3D plots works as intended.
    • Organization and redability improvements in the 3D plotting code. Extra functionality:
    • Available fonts utility: call get_available_fonts to see a printed, numbered list of all the fonts available for Matplotlib in your machine.
    • scale: Scale parameter added to allow defining a scale between the y and x axis.
    • blend_edges: Blend spine color into 3D plot pane fill color.
    Source code(tar.gz)
    Source code(zip)
Owner
Antonio López Rivera
Learning to make stuff.
Antonio López Rivera
Functions for easily making publication-quality figures with matplotlib.

Data-viz utils ?? Functions for data visualization in matplotlib ?? API Can be installed using pip install dvu and then imported with import dvu. You

Chandan Singh 16 Sep 15, 2022
NorthPitch is a python soccer plotting library that sits on top of Matplotlib

NorthPitch is a python soccer plotting library that sits on top of Matplotlib.

Devin Pleuler 30 Feb 22, 2022
:small_red_triangle: Ternary plotting library for python with matplotlib

python-ternary This is a plotting library for use with matplotlib to make ternary plots plots in the two dimensional simplex projected onto a two dime

Marc 611 Dec 29, 2022
:small_red_triangle: Ternary plotting library for python with matplotlib

python-ternary This is a plotting library for use with matplotlib to make ternary plots plots in the two dimensional simplex projected onto a two dime

Marc 391 Feb 17, 2021
A Python library for plotting hockey rinks with Matplotlib.

Hockey Rink A Python library for plotting hockey rinks with Matplotlib. Installation pip install hockey_rink Current Rinks The following shows the cus

null 24 Jan 2, 2023
A python package for animating plots build on matplotlib.

animatplot A python package for making interactive as well as animated plots with matplotlib. Requires Python >= 3.5 Matplotlib >= 2.2 (because slider

Tyler Makaro 394 Dec 18, 2022
A python package for animating plots build on matplotlib.

animatplot A python package for making interactive as well as animated plots with matplotlib. Requires Python >= 3.5 Matplotlib >= 2.2 (because slider

Tyler Makaro 356 Feb 16, 2021
Easily convert matplotlib plots from Python into interactive Leaflet web maps.

mplleaflet mplleaflet is a Python library that converts a matplotlib plot into a webpage containing a pannable, zoomable Leaflet map. It can also embe

Jacob Wasserman 502 Dec 28, 2022
Painlessly create beautiful matplotlib plots.

Announcement Thank you to everyone who has used prettyplotlib and made it what it is today! Unfortunately, I no longer have the bandwidth to maintain

Olga Botvinnik 1.6k Jan 6, 2023
This package creates clean and beautiful matplotlib plots that work on light and dark backgrounds

This package creates clean and beautiful matplotlib plots that work on light and dark backgrounds. Inspired by the work of Edward Tufte.

Nico Schlömer 205 Jan 7, 2023