A comprehensive guide to using the se.alipsa.matrix.gg package for creating ggplot2-style visualizations in Groovy.
- Introduction
- Quick Start
- Core Concepts
- Quick Plot (qplot)
- Typed Aes Setters
- Column References with cols
- Available Components
- Examples
- Differences from R's ggplot2
- Output Formats
The se.alipsa.matrix.gg package provides a ggplot2-style API for creating data visualizations in Groovy.
The API is designed to be nearly identical to R's ggplot2 library, making it easy to port R plotting code to Groovy with minimal modifications.
Implementation note: The gg API is a thin compatibility wrapper over the Charm engine. All gg functions delegate to Charm, producing the same
PlotSpecmodel and rendering through the same SVG pipeline. The full gg public API is preserved and will continue to work. For new code that does not need ggplot2 compatibility, consider using the Charm DSL directly.
- Familiar ggplot2 syntax and semantics
- Works with Matrix data structures
- Extensive geom (geometric object) support
- Complete theming system
- Faceting for multi-panel plots
- Statistical transformations
- Multiple output formats (SVG, PNG, JavaFX)
@Grab('se.alipsa.matrix:matrix-core:3.9.0')
@Grab('se.alipsa.matrix:matrix-charts:0.6.0')
@Grab('se.alipsa.matrix:matrix-ggplot:0.6.0')
@Grab('se.alipsa.matrix:matrix-datasets:2.2.1')
@Grab('se.alipsa.matrix:matrix-stats:2.5.3')
import static se.alipsa.matrix.gg.GgPlot.*
import se.alipsa.matrix.datasets.Datasetdef mpg = Dataset.mpg()
def chart = ggplot(mpg, aes('cty', 'hwy')) +
geom_point() +
labs(title: 'City vs Highway MPG', x: 'City MPG', y: 'Highway MPG')
write(chart, new File('my_plot.svg'))The API is nearly identical to R's ggplot2. Here's a comparison:
R code:
library(ggplot2)
chart <- ggplot(mpg, aes(cty, hwy)) +
geom_point() +
coord_fixed()
ggsave("my_plot.svg", plot = chart)Groovy equivalent:
import static se.alipsa.matrix.gg.GgPlot.*
import se.alipsa.matrix.datasets.Dataset
def chart = ggplot(Dataset.mpg(), aes('cty', 'hwy')) +
geom_point() +
coord_fixed()
ggsave("my_plot.svg", plot: chart)Key differences:
- Use a Matrix instead of a data.frame
- You can use either quoted map-based
aes(...)or closure-basedaes { ... }with unquoted column names
The gg package follows the "grammar of graphics" approach, where plots are built by layering components:
ggplot(data, aes(x, y)) + // Data and aesthetics
geom_point() + // Geometric objects
scale_x_log10() + // Scales
coord_fixed() + // Coordinate systems
facet_wrap('category') + // Faceting
theme_minimal() + // Themes
labs(title: 'My Plot') // LabelsAesthetics map data columns to visual properties:
// Map-based style (always valid)
aes('x_column', 'y_column')
aes(x: 'x_column', y: 'y_column', color: 'category')
// Closure-based style (unquoted column names)
aes { x = x_column; y = y_column; color = category }
// Grouping and wrappers
aes { x = x_col; y = y_col; group = cut_width(displ, 1) }
aes { x = mpg; color = I('red') }
aes { x = factor(cyl); y = mpg }Closure-based aes uses Groovy dynamic property lookup (propertyMissing) so bare names become
column name strings (mpg -> 'mpg'). Use quotes for column names with spaces/special characters:
aes { x = 'Sepal Length'; y = 'Petal Width' }Closure aes is DELEGATE_ONLY, which directs property and method resolution to the aes
delegate instead of the closure owner. This does not change normal Groovy lexical scoping, so
in-scope variables with the same names can still be captured; avoid name collisions between local
variables and column names.
Wrappers and expressions are supported in both styles:
I(...)for constantsfactor(...)for categorical mappingexpr { ... }for computed valuesafter_stat(...)andafter_scale(...)for computed/scaled referencescut_width(...)for fixed-width binning
Common aesthetics:
x,y- Positioncolor/colour- Color of points, lines, bordersfill- Fill color for areassize- Size of points or line widthshape- Point shapealpha- Transparency (0-1)linetype- Line type (solid, dashed, dotted, etc.)group- Grouping variable
qplot() is a convenience API for fast exploratory plotting with geom inference.
Supported overloads:
qplot(Map params)qplot(Matrix data, Closure configure)qplot(Map params, Matrix data, Closure configure)qplot(Matrix data, Map params, Closure configure)(same behavior, alternate argument order)
def mtcars = Dataset.mtcars()
// Map-based
qplot(data: mtcars, x: 'mpg', y: 'wt', color: 'cyl')
qplot(data: mtcars, x: 'mpg', bins: 15)
qplot(data: mtcars, x: 'gear')
// Closure-based
qplot(mtcars) { x = mpg; y = wt; color = cyl }
qplot([geom: 'line', title: 'MPG vs Weight'], mtcars) { x = mpg; y = wt }Geom inference rules:
- Explicit
geomparameter wins. x+ypresent and NOT (xdiscrete +ynumeric) ->geom_point()x+ypresent andxdiscrete +ynumeric ->geom_col()- Only
xpresent andxnumeric ->geom_histogram() - Only
xpresent andxnon-numeric/discrete ->geom_bar()
Common qplot parameters:
- Required:
data,x - Optional aesthetics:
y,color/colour/col,fill,size,shape,alpha,linetype - Optional behavior:
geom,bins - Optional labels:
title,xlab,ylab
Aes includes typed setter overloads to improve IDE hints while keeping wrappers fully supported.
For example, IDEs can show setX(String) as the common path while still offering alternatives.
def mapping = new Aes()
mapping.x = 'mpg'
mapping.y = 'wt'
mapping.color = factor('cyl')
mapping.size = I(2.5)Supported typed values include:
Stringcolumn namesIdentity,Factor,Expression,AfterStat,AfterScale,CutWidthClosure(for computed expressions in existing APIs)
cols(Matrix) returns a validating proxy for unquoted property-style column references.
def c = cols(mtcars)
ggplot(mtcars, aes(x: c.mpg, y: c.wt)) + geom_point()Unknown properties throw an IllegalArgumentException listing available columns, which helps
catch typos early.
Note: c.mpg relies on dynamic property resolution. It works in dynamic/untyped contexts
(scripts/tests or @CompileDynamic). In @CompileStatic code, use quoted column names.
Geoms determine how data is displayed. You can layer multiple geoms:
ggplot(data, aes('x', 'y')) +
geom_point() + // Add points
geom_smooth(method: 'lm') + // Add regression line
geom_line() // Add line connecting pointsScales control how data values map to visual properties:
// Transform scales
ggplot(data, aes('x', 'y')) +
geom_point() +
scale_x_log10() + // Log10 transform for x-axis
scale_y_sqrt() // Square root transform for y-axis
// Color scales
ggplot(data, aes('x', 'y', color: 'category')) +
geom_point() +
scale_color_viridis_d() // Discrete viridis colors
// Manual scales
ggplot(data, aes('x', 'y', color: 'group')) +
geom_point() +
scale_color_manual(values: ['red', 'blue', 'green'])Coordinate systems control the plot's coordinate space:
coord_cartesian() // Default Cartesian coordinates
coord_fixed() // Fixed aspect ratio (1:1)
coord_fixed(ratio: 2) // Custom aspect ratio
coord_flip() // Flip x and y axes
coord_polar() // Polar coordinatesFaceting creates multi-panel plots based on categorical variables:
// Wrap facets (single variable)
ggplot(mpg, aes('cty', 'hwy')) +
geom_point() +
facet_wrap('class')
// Grid facets (two variables)
ggplot(mpg, aes('cty', 'hwy')) +
geom_point() +
facet_grid('year ~ drv') // rows ~ columnsThemes control the overall appearance:
// Built-in themes
theme_grey() // Default theme
theme_minimal() // Minimal theme
theme_bw() // Black and white theme
theme_classic() // Classic theme
theme_dark() // Dark theme
theme_light() // Light theme
theme_void() // Empty theme
// Customize theme elements
ggplot(data, aes('x', 'y')) +
geom_point() +
theme_minimal() +
theme(
'legend.position': 'top',
'axis.line': element_line(linewidth: 0.75),
'axis.line.x.bottom': element_line(colour: 'blue')
)geom_point()- Scatter plotsgeom_line()- Line plotsgeom_path()- Connected paths (ordered by data)geom_step()- Step plotsgeom_bar()- Bar charts (counts)geom_col()- Column charts (values)geom_area()- Area plotsgeom_polygon()- Polygonsgeom_rect()- Rectanglesgeom_tile()- Tiles/heatmapsgeom_text()- Text labelsgeom_label()- Text labels with background
geom_histogram()- Histogramsgeom_freqpoly()- Frequency polygonsgeom_density()- Density plotsgeom_boxplot()- Box plotsgeom_violin()- Violin plotsgeom_dotplot()- Dot plotsgeom_count()- Count overlapping pointsgeom_bin2d()- 2D binned heatmapgeom_hex()- Hexagonal binninggeom_smooth()- Smoothed conditional meansgeom_quantile()- Quantile regression
geom_ribbon()- Ribbons (confidence bands)geom_pointrange()- Points with error barsgeom_linerange()- Line rangesgeom_errorbar()- Error barsgeom_errorbarh()- Horizontal error barsgeom_crossbar()- Crossbars
geom_contour()- Contour linesgeom_contour_filled()- Filled contoursgeom_density2d()- 2D density contoursgeom_density2d_filled()- Filled 2D density
geom_abline()- Diagonal reference linesgeom_hline()- Horizontal reference linesgeom_vline()- Vertical reference linesgeom_segment()- Line segmentsgeom_curve()- Curved linesgeom_spoke()- Spokes (angle + radius)
geom_qq()- Q-Q plotsgeom_qq_line()- Q-Q reference linegeom_rug()- Rug plots (marginal ticks)geom_jitter()- Jittered points
geom_raster()- Raster imagesgeom_map()- Map datageom_sf()- Simple features (spatial)geom_sf_label()- SF labelsgeom_sf_text()- SF textgeom_parallel()- Parallel coordinatesgeom_function()- Function plotsgeom_mag()- Magnitude plotsgeom_logticks()- Logarithmic tick marksgeom_blank()- Blank layer (for limits)geom_custom()- Custom geoms
scale_x_continuous()/scale_y_continuous()scale_x_discrete()/scale_y_discrete()scale_x_log10()/scale_y_log10()scale_x_sqrt()/scale_y_sqrt()scale_x_reverse()/scale_y_reverse()scale_x_date()/scale_y_date()scale_x_datetime()/scale_y_datetime()scale_x_time()/scale_y_time()scale_x_binned()/scale_y_binned()
scale_color_continuous()/scale_colour_continuous()scale_color_discrete()/scale_colour_discrete()scale_color_gradient()/scale_colour_gradient()scale_color_gradient2()/scale_colour_gradient2()scale_color_gradientn()/scale_colour_gradientn()scale_color_hue()/scale_colour_hue()scale_color_grey()/scale_colour_grey()scale_color_brewer()/scale_colour_brewer()scale_color_distiller()/scale_colour_distiller()scale_color_fermenter()/scale_colour_fermenter()scale_color_viridis_d()/scale_colour_viridis_d()scale_color_viridis_c()/scale_colour_viridis_c()scale_color_steps()/scale_colour_steps()scale_color_identity()/scale_colour_identity()scale_color_manual()/scale_colour_manual()
scale_fill_continuous(),scale_fill_discrete()scale_fill_gradient(),scale_fill_gradient2(),scale_fill_gradientn()scale_fill_hue(),scale_fill_grey()scale_fill_brewer(),scale_fill_distiller(),scale_fill_fermenter()scale_fill_viridis_d(),scale_fill_viridis_c()scale_fill_steps(),scale_fill_identity(),scale_fill_manual()
scale_size(),scale_size_binned(),scale_size_area()scale_shape(),scale_shape_binned(),scale_shape_manual(),scale_shape_identity()scale_linetype(),scale_linetype_manual(),scale_linetype_identity()scale_alpha(),scale_alpha_binned(),scale_alpha_manual(),scale_alpha_identity()scale_radius()
coord_cartesian()- Standard Cartesian (default)coord_fixed()- Fixed aspect ratiocoord_flip()- Flip x/y axescoord_polar()- Polar coordinatescoord_map()- Map projectionscoord_sf()- Simple features (spatial)coord_trans()- Transformed coordinates
facet_wrap()- Wrap panels into rows/columnsfacet_grid()- Grid of panels by variables
theme_grey()- Default grey themetheme_bw()- Black and white themetheme_minimal()- Minimal themetheme_classic()- Classic theme (no gridlines)theme_dark()- Dark themetheme_light()- Light themetheme_void()- Empty themetheme()- Custom theme modifications
labs()- Set labels for title, subtitle, axes, legendsxlab()/ylab()- X/Y axis labelsggtitle()- Plot title and subtitleannotate()- Add annotationsannotation_logticks()- Log scale tick marksannotation_custom()- Custom annotationsannotation_raster()- Raster annotationsannotation_map()- Map annotations
guides()- Set guide (legend) propertiesguide_legend()- Legend guideguide_colorbar()/guide_colourbar()- Continuous color barguide_bins()- Binned guideguide_colorsteps()/guide_coloursteps()- Color stepsguide_axis()- Axis guideguide_none()- Remove guide
lims()- Set limits for multiple axesxlim()/ylim()- Set x/y limitsexpand_limits()- Expand limits to include valuesexpansion()- Control axis expansion
vars()- Quote variables for facetingafter_stat()- Reference computed statisticsafter_scale()- Reference scaled valuescut_width()- Bin continuous variable by widthposition_nudge()- Nudge position adjustmentexpr()- Define expressionsI()- Use value "as is" (identity)cols()- Validate column names via property-style access
import static se.alipsa.matrix.gg.GgPlot.*
import se.alipsa.matrix.datasets.Dataset
def mpg = Dataset.mpg()
def chart = ggplot(mpg, aes('cty', 'hwy')) +
geom_point() +
labs(title: 'City vs Highway MPG', x: 'City MPG', y: 'Highway MPG')
write(chart, new File('scatter.svg'))def chart = ggplot(mpg, aes('cty', 'hwy', colour: 'class')) +
geom_point() +
scale_colour_viridis_d() +
labs(title: 'MPG by Vehicle Class')
write(chart, new File('colored_scatter.svg'))def chart = ggplot(mpg, aes('cty', 'hwy')) +
geom_point() +
geom_smooth(method: 'lm') +
labs(title: 'City vs Highway MPG with Trend Line')
write(chart, new File('regression.svg'))def chart = ggplot(mpg, aes('cty', 'hwy')) +
geom_boxplot(aes(group: cut_width('displ', 1))) +
labs(title: 'Highway MPG by Engine Displacement')
write(chart, new File('boxplot.svg'))def chart = ggplot(mpg, aes('cty', 'hwy')) +
geom_point() +
facet_grid('year ~ drv') +
labs(title: 'MPG by Year and Drive Type')
write(chart, new File('facets.svg'))def chart = ggplot(mpg, aes('cty', 'hwy', colour: 'class')) +
geom_point() +
theme_minimal() +
theme(
'legend.position': 'top',
'axis.line': element_line(linewidth: 0.75),
'axis.line.x.bottom': element_line(colour: 'blue')
) +
labs(title: 'Customized Theme Example')
write(chart, new File('custom_theme.svg'))import se.alipsa.matrix.core.Matrix
def data = Matrix.builder().data(
x: [1, 2, 3, 4],
y: [10, 12, 9, 14]
).types(Integer, Integer).build()
def chart = ggplot(data, aes('x', 'y')) +
geom_point() +
annotate('text', x: 2, y: 12, label: 'Peak') +
annotate('rect', xmin: 1, xmax: 3, ymin: 9, ymax: 13, alpha: 0.15) +
annotate('segment', x: 1, xend: 3, y: 10, yend: 10, color: 'red')
write(chart, new File('annotations.svg'))def data = Matrix.builder().data(
x: [1, 10, 100, 1000],
y: [1, 4, 9, 16]
).types(Integer, Integer).build()
def chart = ggplot(data, aes('x', 'y')) +
geom_point() +
scale_x_log10() +
scale_y_sqrt() +
labs(title: 'Log-sqrt Transformed Scales')
write(chart, new File('transforms.svg'))import java.time.LocalDate
def dates = Matrix.builder().data(
date: [LocalDate.parse('2024-01-01'), LocalDate.parse('2024-02-01'), LocalDate.parse('2024-03-01')],
value: [10, 12, 15]
).types(LocalDate, Integer).build()
def chart = ggplot(dates, aes('date', 'value')) +
geom_line() +
geom_point() +
scale_x_date() +
labs(title: 'Time Series Data')
write(chart, new File('timeseries.svg'))def grid = Matrix.builder().data(
x: [1, 2, 3, 1, 2, 3, 1, 2, 3],
y: [1, 1, 1, 2, 2, 2, 3, 3, 3],
value: [5, 10, 15, 8, 12, 18, 3, 7, 20]
).types(Integer, Integer, Integer).build()
def chart = ggplot(grid, aes('x', 'y', fill: 'value')) +
geom_tile() +
scale_fill_viridis_c() +
labs(title: 'Heatmap Example')
write(chart, new File('heatmap.svg'))import se.alipsa.matrix.datasets.Dataset
import static se.alipsa.matrix.gg.GgPlot.*
def penguins = Dataset.penguins()
def chart = ggplot(
data: penguins,
mapping: aes(x: 'flipper_length_mm', y: 'body_mass_g')
) +
geom_point(aes(color: 'species', shape: 'species')) +
geom_smooth(method: 'lm') +
labs(
title: 'Body mass and flipper length',
subtitle: 'Dimensions for Adelie, Chinstrap, and Gentoo Penguins',
x: 'Flipper length (mm)',
y: 'Body mass (g)',
color: 'Species',
shape: 'Species'
) +
theme_minimal()
write(chart, new File('penguins.svg'))While the API is designed to be as close as possible to R's ggplot2, there are some differences due to language constraints:
R uses non-standard evaluation, while Groovy supports two styles:
- Map/positional style with quoted column names
- Closure style with unquoted column names
In practice, these are equivalent:
# R
aes(mpg, wt, color = cyl)// Groovy map-based
aes('mpg', 'wt', color: 'cyl')
// Groovy closure-based
aes { x = mpg; y = wt; color = cyl }Use quotes for column names containing spaces/special characters in either style.
Use Groovy's Map syntax for named arguments:
# R
geom_point(size = 3, alpha = 0.5)// Groovy
geom_point(size: 3, alpha: 0.5)Use Matrix instead of data.frame:
# R
df <- data.frame(x = 1:10, y = rnorm(10))// Groovy
import se.alipsa.matrix.core.Matrix
def data = Matrix.builder().data(
x: 1..10,
y: [/* values */]
).build()Use write() or ggsave():
// R
ggsave("plot.svg", plot = chart)
// Groovy
write(chart, new File('plot.svg'))
// or
ggsave('plot.svg', chart)Import the GgPlot class statically:
import static se.alipsa.matrix.gg.GgPlot.*Use TRUE/FALSE or T/F constants from GgPlot:
import static se.alipsa.matrix.gg.GgPlot.*
facet_wrap('var', scales: 'free') // Use string 'free'
// TRUE, FALSE, T, F are available as constantsFacet options may precede or follow the facet variable:
facet_wrap('var', ncol: 2)
facet_wrap(facets: 'var', ncol: 2)scales: 'free', 'free_x', and 'free_y' are accepted but currently share fixed panel
scales; a warning is logged.
layer_data(chart, i) returns the i-th layer's data after stat and position adjustment, and
ggplot_build(chart) returns one Matrix per layer. Both use the same Charm pipeline as
rendering and calculate facet panels independently. The columns follow ggplot2 naming, including
PANEL, colour, and stat outputs such as density, binStart, and count.
import static se.alipsa.matrix.gg.GgPlot.*
def chart = ggplot(mtcars, aes(x: 'mpg')) + geom_histogram(bins: 10)
Matrix bins = layer_data(chart)
List<Matrix> all = ggplot_build(chart)import static se.alipsa.matrix.gg.GgPlot.*
def chart = ggplot(data, aes('x', 'y')) + geom_point()
// Write directly to file
write(chart, new File('plot.svg'))
// Or use ggsave
ggsave(chart, 'plot.svg')import static se.alipsa.matrix.gg.GgPlot.*
import se.alipsa.matrix.chartexport.ChartToPng
def chart = ggplot(data, aes('x', 'y')) + geom_point()
ggsave(chart, 'plot.png')import static se.alipsa.matrix.gg.GgPlot.*
import se.alipsa.matrix.chartexport.ChartToJpeg
def chart = ggplot(data, aes('x', 'y')) + geom_point()
ggsave(chart, 'plot.jpeg', quality: 0.95) // quality: 0.0-1.0import static se.alipsa.matrix.gg.GgPlot.*
import se.alipsa.matrix.chartexport.ChartToJfx
import org.girod.javafx.svgimage.SVGImage
def chart = ggplot(data, aes('x', 'y')) + geom_point()
SVGImage svgImage = ChartToJfx.export(chart)
// Use svgImage in your JavaFX applicationimport static se.alipsa.matrix.gg.GgPlot.*
import se.alipsa.matrix.chartexport.ChartToSwing
import se.alipsa.matrix.chartexport.SvgPanel
def chart = ggplot(data, aes('x', 'y')) + geom_point()
SvgPanel panel = ChartToSwing.export(chart)
// Add panel to your Swing container// Save multiple charts to one SVG file
ggsave('combined.svg', chart1, chart2, chart3)- Examples: See the
matrix-charts/examples/gg/directory for more examples - API Documentation: JavaDoc
- Matrix Core: See matrix-core documentation for working with Matrix data structures
- Matrix Stats: Statistical functions for use with
geom_smooth()and other stat geoms
def base = ggplot(data, aes('x', 'y'))
def withPoints = base + geom_point()
def final = withPoints + theme_minimal()def commonAes = aes('flipper_length', 'body_mass', color: 'species')
def plot1 = ggplot(penguins, commonAes) + geom_point()
def plot2 = ggplot(penguins, commonAes) + geom_boxplot()// For limits
+ lims(x: [0, 100], y: [0, 50])
// For expansion
+ expand_limits(x: 0, y: [0, 100])
// For custom CSS
+ css_attributes(stroke: 'blue', 'stroke-width': 2)// This puts smooth line on top
ggplot(data, aes('x', 'y')) +
geom_point() +
geom_smooth()
// This puts points on top (usually preferred)
ggplot(data, aes('x', 'y')) +
geom_smooth() +
geom_point()// Prepare data with Matrix operations
def data = Matrix.builder().data(csvFile).build()
.replaceAll('NA', null)
.convert(age: Integer, salary: Double)
.subset { row -> row.salary > 50000 }
def chart = ggplot(data, aes('age', 'salary')) + geom_point()