gramm data visualization toolbox

Quickly create publication-quality plots with a ggplot/seaborn like approach: automatic colors & subplots, stats, violin/box plots, etc.
Updated 13 Apr 2024

Editor's Note: This file was selected as MATLAB Central Pick of the Week


Open in MATLAB Online View gramm on File Exchange

Gramm is a powerful plotting toolbox which allows to quickly create complex, publication-quality figures in MATLAB, and is inspired by R's ggplot2 library by Hadley Wickham. As a reference to this inspiration, gramm stands for GRAMmar of graphics for MATLAB.

Table of contents

Why gramm

Gramm is a data visualization toolbox for MATLAB that allows to produce publication-quality plots from grouped data easily and flexibly. MATLAB can be used for complex data analysis using a high-level interface: it supports mixed-type tabular data via tables, provides statistical functions that accept these tables as arguments, and allows users to adopt a split-apply-combine approach (Wickham 2011) with rowfun(). However, the standard plotting functionality in MATLAB is mostly low-level, allowing to create axes in figure windows and draw geometric primitives (lines, points, patches) or simple statistical visualizations (histograms, boxplots) from numerical array data. Producing complex plots from grouped data thus requires iterating over the various groups in order to make successive statistical computations and low-level draw calls, all the while handling axis and color generation in order to visually separate data by groups. The corresponding code is often long, not easily reusable, and makes exploring alternative plot designs tedious.

Inspired by ggplot2 (Wickham 2009), the R implementation of "grammar of graphics" principles (Wilkinson 1999), gramm improves MATLAB's plotting functionality, allowing to generate complex figures using high-level object-oriented code. Gramm has been used in several publications in the field of neuroscience, from human psychophysics (Morel et al. 2017), to electrophysiology (Morel et al. 2016; Ferrea et al. 2017), human functional imaging (Wan et al. 2017) and animal training (Berger et al. 2017).

About gramm


  • Automatically within MATLAB : Open the Add-ons explorer, search for "gramm" and click Add !
  • Or by townloading the toolbox package : download the latest .mltbx file from the GitHub Releases and double-click the downloaded file to install.
  • Or manually : download the gramm toolbox from the MATLAB File exchange or GitHub ("Clone or download" button>download ZIP) or clone it, and add the folder containing the @gramm class folder to your MATLAB path (using the GUI or addpath())


  • gramm cheat sheet
  • Numerous coding examples and test cases in examples.m, exported for preview in html/examples.html
  • From MATLAB: doc gramm to find links to the documentation of each method.

Citing gramm

Gramm has been published in the Journal of Open Source Software. If you use gramm plots in a publication you can thus cite it using the following:

Morel, (2018). Gramm: grammar of graphics plotting in Matlab. Journal of Open Source Software, 3(23), 568,


Tested under MATLAB 2014b+ versions. With pre-2014b versions, gramm forces 'painters', renderer to avoid some graphic bugs, which deactivates transparencies (use non-transparent geoms, for example stat_summary('geom','lines')). The statistics toolbox is required for some methods: stat_glm(), some stat_summary() methods, stat_density(). The curve fitting toolbox is required for stat_fit().

Using gramm


The typical workflow to generate a figure with gramm is the following:

  • In a first step, provide gramm with the relevant data for the figure: X and Y variables, but also grouping variables that will determine color, subplot rows/columns, etc.
  • In the next steps, add graphical layers to your figure: raw data layers (directly plot data as points, lines...) or statistical layers (plot fits, histograms, densities, summaries with confidence intervals...). One instruction is enough to add each layer, and all layers offer many customization options.
  • In the last step, gramm draws the figure, and takes care of all the annoying parts: no need to loop over colors or subplots, colors and legends are generated automatically, axes limits are taken care of, etc.

For example, with gramm, 7 lines of code are enough to create the figure below from the carbig dataset. Here the figure represents the evolution of fuel economy of new cars in time, with number of cylinders indicated by color, and regions of origin separated across subplot columns: gramm example

load carbig.mat %Load example dataset about cars
origin_region=num2cell(org,2); %Convert origin data to a cellstr

% Create a gramm object, provide x (year of production) and y (fuel economy) data,
% color grouping data (number of cylinders) and select a subset of the data
g=gramm('x',Model_Year,'y',MPG,'color',Cylinders,'subset',Cylinders~=3 & Cylinders~=5)
% Subdivide the data in subplots horizontally by region of origin
% Plot raw data as points
% Plot linear fits of the data with associated confidence intervals
% Set appropriate names for legends
g.set_names('column','Origin','x','Year of production','y','Fuel economy (MPG)','color','# Cylinders')
%Set figure title
g.set_title('Fuel economy of new cars between 1970 and 1982')
% Do the actual drawing

Figure export

To export figures in a vector-based format, use the SVG or PDF option rather than EPS. SVG can be read by all vector editing softwares and causes less problems than EPS both for export and import (transparency support, text without cuts, etc.). gramm has a convenient export() method that can be called after draw() and maintains correct dimensions/aspect ratio.


  • Accepts X Y and Z data as arrays, matrices or cells of arrays

  • Accepts grouping data as arrays or cellstr.

  • Multiple ways of separating groups of data:

    • Colors, lightness, point markers, line styles, and point/line size ('color', 'lightness', 'marker', 'linestyle', 'size')
    • Subplots by row and/or columns, or wrapping columns (facet_grid() and facet_wrap()). Multiple options for consistent axis limits across facets, rows, columns, etc. (using 'scale' and 'space')
    • Separate figures (fig())
  • Multiple ways of directly plotting the data:

    • scatter plots (geom_point()) and jittered scatter plot (geom_jitter())
    • lines (geom_line())
    • pre-computed confidence intervals (geom_interval())
    • bars plots (geom_bar())
    • raster plots (geom_raster())
    • labels (geom_label())
    • point counts (geom_count())
    • swarm / beeswarm plots (geom_swarm())
  • Multiple ways of plotting statistics on the data:

    • y data summarized by x values (uniques or binned) with confidence intervals (stat_summary())
    • histograms and density plots of x values (stat_bin() and stat_density())
    • box and whisker plots (stat_boxplot())
    • violin plots (stat_violin())
    • quantile-quantile plots (stat_qq()) of x data distribution against theoretical distribution or y data distribution.
    • spline-smoothed y data with optional confidence interval (stat_smooth())
    • 2D binning (stat_bin2d())
    • GLM fits (stat_glm(), requires statistics toolbox)
    • Custom fits with user-provided anonymous function (stat_fit())
    • Ellipses of confidence (stat_ellipse())
  • When Z data is provided in the call to gramm(), geom_point(), geom_line() and geom_label() generate 3D plots

  • Subplots are created without too much empty space in between (and resize properly !)

  • Polar coordinates (set_polar())

  • Color data can also be displayed as a continous variable, not as a grouping factor (set_continuous_color())

  • X and Y axes can be flipped to get horizontal statistics visualizations (coord_flip())

  • Color generation can be customized in the LCH color space, or can use alternative colormaps (MATLAB's default, colorbrewer2), or provide a custom colormap (set_color_options())

  • Marker shapes and sizes can be customized with set_point_options()

  • Line styles and width can be customized with set_line_options()

  • Text elements aspect can be customized with set_text_options()

  • Parameters of stat_ functions (alpha level, N bootstraps) can be modified with set_stat_options()

  • The ordering of grouping variables can be changed between native, sorted, or custom (set_order_options)

  • Confidence intervals as shaded areas, error bars or thin lines

  • Set the width and dodging of graphical elements in geom_ functions, stat_bin(), stat_summary(), and stat_boxplot(), with 'width' and 'dodge' arguments

  • The member structure results contains the results of computations from stat_ plots as well as graphic handles for all plotted elements

  • Figure title (set_title())

  • Multiple gramm plots can be combined in the same figure by creating a matrix of gramm objects and calling the draw() method on the whole matrix. An overarching title can be added by calling set_title() on the whole matrix.

  • Different groupings can be used for different stat_ and geom_ layers with the update() method

  • MATLABs axes properties are acessible through the method axe_property()

  • Custom legend labels with set_names()

  • Plot reference line on the plots with geom_abline(), geom_vline(),geom_hline()

  • Plot reference polygons on the plots with geom_polygon()

  • Date ticks with set_datetick()

  • Gramm works best with table-like data: separate variables / structure fields / table columns for the variables of interest, with each variable having as many elements as observations.

Use cases and examples

The code for the following figures and many others is in examples.m.

Mapping groups of data to different visual properties

All the mappings presented below can be combined.

Relationship between categorical and continuous variables

Distribution of a continuous variable

Note that we by using Origin as a faceting variable, we visualize exactly the same quantities as in the figure above.

Relationship between two continous variables

2D densities

2D density

Repeated trajectories

Here the variable given as Y is a Nx1 cell of 1D arrays containing the individual trajectories. Color is given as a Nx1 cellstr.

Spike trains

This example highlights the potential use of gramm for neuroscientific data. Here X is a Nx1 cell containing spike trains collected over N trials. Color is given as a Nx1 cellstr. Using stat_bin() it is possible to construct peristimulus time histograms.

stat_bin() options

Histograms example

facet_grid() options

facet_grid() options

Custom layouts

Custom layouts

Text labels with geom_label()


Colormap customization

With set_color_options()

Colormaps example

Continuous colors

Continuous colors

Reordering of categorical variables

With set_order_options()


Superimposition of gramm objects on the same axes

By making calling the update() method after a first draw, the same axes can be reused for another gramm plot. Here this allows to plot the whole dataset in the background of each facet.

gramm superimposition


gramm was inspired and/or used code from:

Cite As

Morel, Pierre. “Gramm: Grammar of Graphics Plotting in Matlab.” The Journal of Open Source Software, vol. 3, no. 23, The Open Journal, Mar. 2018, p. 568, doi:10.21105/joss.00568.

View more styles
MATLAB Release Compatibility
Created with R2023b
Compatible with R2018a and later releases
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Versions that use the GitHub default branch cannot be downloaded

Version Published Release Notes

See release notes for this release on GitHub:


See release notes for this release on GitHub:


Switching to new github integration


Added full tab auto-complete for arguments and options with functionSignatures.json

Updated description

- Added JOSS paper and DOI information
- Fixed set_datetick() behavior

Preparation for JOSS submission

Added set_layout_options() allowing to fully customize figure layout in gramm

Corrected bug in geom_bar() when used with the 'stacked' option

- Overhaul of legend and colormap support
- Allows for non LCH luminance/color colormaps
- Added new built-in colormaps
- Added new legend options

Added toggles for row/column labels, improved handling of empty subsets

- Added more customization options to geom_bar
- Fixed automatic continuous colors
- Various fixes

Gramm now merges color and marker/size/linestyle legend if they are the same

- Added continuous color support to 3D lines and points
- Added colorbrewer license file

- Possibility to set ‘CLim’ in set_continuous_color() in order to force color limits.
- Fixed bug on continuous colors when a unique value was provided
- Documentation updates

Added geom_polygon() method to add custom polygons on plots

- Improved graphic fixes for old matlab versions
- Updated geom_abline() , geom_vline(), geom_hline() functions
- Bug fixes
- Added missing documentation

- Added export() method
- Added 'interpreter' to set_text_options()

Added coord_flip(), which can be used to generate horizontal box plots, violin plots, error bars, etc.

- Added the possibility to provide a custom function to stat_summary()
- Removed unnecessary computation when stat_smooth() was used with default options (2x speedup!)

- stat_smooth() now provides more smoothing algorithms, better documentation and more conservative CI estimates
- Enhancements and better documentation for set_order_options()
- Bug fixes in edge cases (empty elements in cells, etc.)

- Added fig() function to separate data across figures
- Improved copy() behavior

Corrected bug in stat_summary() polar interpolation when x data didn't start at zero radians. Added safety checks.

- Corrected absence of y ticks if single facet when using facet_wrap()
- Corrected behavior of stat_cornerhist() when ‘DataAspectRatio’ is set to [1 1 1] using axe_property()

Added 'alpha' option to geom_point(), geom_jitter() and geom_line()

- Added geom_label() to plot text
- Added additional examples
- Modified continuous color legend

- Added set_stat_options() to specify alpha level and N bootstrap samples in all stat_ functions
- Added 'viridis' colormap
- Default confidence interval in stat_summary is now corrected for normal distributions with small N
- Other improvements

Added customization options for text, lines and points:
- Added set_line_options(): style, size
- Added set_point_options(): markers, size
- Added set_text_options(): font, sizes
- Corrected bug with iscategorical() on old matlab versions

- Added corner histogram of x-y difference stat_cornerhist()
- Improved speed on large datasets with many non-unique x values

- Added notch option to stat_boxplot()
- Corrected bug in stat_ellipse() for 2014a and earlier versions

- Added stat_violin() to create violin plots
- BETA of stat_cornerhist to plot an histogram of the x-y difference in an inset axis (has an intermittent sizing bug).

Added functionality to edit legend axes

- Corrected rare error on y limit computation
- Simplified code in draw()
- Changed thumbnail

Corrected error with geom_line() and 3D data

- Represent user-provided confidence intervals with geom_interval()
- Improved dodging: now takes in account the number of colors per x values
- Dodging supported in additional geom_ methods
- Improved geom_bar() stacking

- Corrected errorbar thickness
- Improved update() behavior

- Added set_parent() method
- Improved dodging for categorical x
- Improved update() behavior

Updated description

- Full refactor from a single file to a @gramm class folder
- examples.m is now a proper how-to and can be published
- With the update() method, use different groupings for different layers
- Support for categorical variables in faceting

Corrected stat_summary() to prevent erroneous line/area interruptions

- Added 'space' option to facet_grid()
- Updated examples and Readme

- Improved legend layout
- Harmonized 'width' and 'dodge' arguments
- Improved stat_summary() behavior for missing elements
- Optimizations

- Changed Picture

- ‘z’ input data in gramm() creates 3D plots when using geom_point() or geom_line()
- Corrected bugs in box plot and corrected whisker length
- Added possibility to superimpose gramm plots
- Corrected support for categorical data

Added possibility to set a global title with set_title()

Description correction

Added simpler way to set ordering with set_order_options()

- Added set_order_options()
- Added ‘map’ option to set_color_options()
- Customization functions can be called on arrays of gramm objects
- Bug fixes

Added box and whiskers plots, Quantile-Quantile plots
Other modifications and corrections (see Github: )

Added cheat sheet, added geom_funline(), added 'dodge' option to stat_summary()

- Results from stat_ plots are now returned in the results member structure.
- Corrected bugs with pre 2014b versions

Changing manually the limits (using pan or zoom) of a facet in a gramm generated figure will now automatically change the scale of the other facets according to the ‘scale’ facet preferences

- Added stat_fit() for custom fits (requires curve fitting toolbox)
- Added more generic ‘fill’ options to stat_bin()
- stat_bin() and stat_density() now behave when using polar plots
- Added documentation
- Reduced clutter
- Added examples

Plenty of new features (separation by lightness, confidence ellipses, color options, geom_hline, geom_vline)

Bug corrrection

Enhancements and bug fixes for continuous colors, which can now be forced and customized using set_continuous_color()

Added ‘edges’ option for custom bins to stat_bin2d() and stat_bin()
Added ‘bar_color’ and ‘bar_spacing’ options, ‘overlaid_bar’ geom to stat_bin()
Now possible to set multiple properties at once in axe_property()
Corrected behavior of facet scaling

Greatly improved geom_raster() speed when used with option 'geom','line'

Additional usage examples

Corrected set_datetick() issue, corrected initialization of faceting variables

To view or report issues in this GitHub add-on, visit the GitHub Repository.
To view or report issues in this GitHub add-on, visit the GitHub Repository.