Plotting (dv.plotting)¶
Plot types. Every class follows the two-phase pattern: data and computation parameters at construction, styling and rendering in plot().
Imported as diive.plotting, reached as dv.plotting after import diive as dv.
PLOTTING: PUBLIC NAMESPACE FOR THE PLOT CLASSES¶
Public namespace dv.plotting: the plot classes and FormatStyle.
The plot classes follow a two-phase pattern: data and computation parameters go
to __init__, styling goes to plot(ax=None, ...). Title, labels, font
sizes, grid and legend are set with a FormatStyle passed as format_style
(polar plots use only some of its fields, see their plot()).
Part of the diive library: https://github.com/holukas/diive
- class diive.plotting.FormatStyle(title=None, xlabel=None, ylabel=None, zlabel=None, xunits=None, yunits=None, title_fontsize=None, axlabel_fontsize=None, ticks_fontsize=None, legend_fontsize=None, title_fontweight='bold', axlabel_fontweight='normal', text_color=None, chrome_color=None, facecolor=None, grid_color=None, spine_linewidth=None, ticks_direction='in', ticks_length=None, ticks_width=None, show_grid=True, show_legend=True, legend_loc='best', legend_ncol=1, show_zeroline=True)[source]¶
Bases:
objectShared, reusable formatting for any diive plot.
Holds only the cross-cutting chrome common to every plot type (title, labels, units, font sizes, colours, grid, legend, zero line). Per-plot rendering choices (line width, marker, colormap, …) stay as arguments on each
plot()method — they are not the same across plot types.All
Nonefont-size/colour fields resolve to the standard values inLightThemewhenapply()runs, so an unmodifiedFormatStyle()reproduces the diive house style.Text content (
title/xlabel/ylabel/zlabel) left at None means “let the plot decide” — the caller passes its own auto value (e.g. the series name) as thedefault_*argument ofapply().- Parameters:
title (
str|None) – Plot title. None -> caller’s default;""-> no title.xlabel (
str|None) – X-axis label. None -> caller’s default.ylabel (
str|None) – Y-axis label. None -> caller’s default.zlabel (
str|None) – Colorbar / z-axis label (only used by plots that have one).xunits (
str|None) – Units appended to the x-axis label, e.g."(°C)".title_fontsize (
float|None) – Title font size. None ->theme.FONTSIZE_TITLE.axlabel_fontsize (
float|None) – Axis-label font size. None ->theme.FONTSIZE_AXLABEL.ticks_fontsize (
float|None) – Tick-label font size. None ->theme.FONTSIZE_TICKS.legend_fontsize (
float|None) – Legend font size. None ->theme.FONTSIZE_LEGEND.title_fontweight (
str) – Font weight for the title (default'bold').axlabel_fontweight (
str) – Font weight for the axis labels (default'normal').text_color (
str|None) – Colour of title + axis labels. None ->theme.COLOR_TEXT.chrome_color (
str|None) – Colour of ticks + spines. None ->theme.COLOR_CHROME.facecolor (
str|None) – Axes background colour. None ->theme.COLOR_FACE.grid_color (
str|None) – Gridline colour. None ->theme.COLOR_LINE_GRID.spine_linewidth (
float|None) – Spine line width. None ->theme.LINEWIDTH_SPINES.ticks_direction (
str) – Tick direction,'in'(default) /'out'/'inout'.ticks_length (
float|None) – Tick length. None ->theme.TICKS_LENGTH.ticks_width (
float|None) – Tick width. None ->theme.TICKS_WIDTH.show_grid (
bool) – Draw the grid (default True).show_legend (
bool) – Draw a legend when the axes has labelled artists (default True).legend_loc (
int|str) – Legend location (matplotlibloc, default'best').legend_ncol (
int) – Number of legend columns (default 1).show_zeroline (
bool) – Draw a horizontal line at y=0 when the data straddles zero (default True; only drawn whenapply()is given the data).
- merged(**overrides)[source]¶
Return a copy with the given non-None fields overridden.
Used by
plot()methods to adjust a caller-supplied style without mutating it, e.g. to suppress the title on the applied copy (title="") or to set the y-axis units from a constructor argument. Keys set to None are ignored, so they never clobber a value already on the style.- Return type:
- apply(ax, default_title=None, default_xlabel=None, default_ylabel=None, zeroline_data=None)[source]¶
Apply this style to a matplotlib axes.
Resolves every None field to its
LightThemedefault, then sets the facecolor, ticks, spines, axis labels (with units), title, grid, optional zero line, and legend using the sharedplotfuncshelpers.- Parameters:
ax – The matplotlib axes to format.
default_title (
str) – Title to use whenself.titleis None (e.g. the series name).self.title == ""suppresses it.default_xlabel (
str) – X-label to use whenself.xlabelis None.default_ylabel (
str) – Y-label to use whenself.ylabelis None.zeroline_data (
Series|DataFrame) – Data used to decide whether to draw the y=0 line (only drawn whenshow_zerolineand the data straddles zero).
- Return type:
- __init__(title=None, xlabel=None, ylabel=None, zlabel=None, xunits=None, yunits=None, title_fontsize=None, axlabel_fontsize=None, ticks_fontsize=None, legend_fontsize=None, title_fontweight='bold', axlabel_fontweight='normal', text_color=None, chrome_color=None, facecolor=None, grid_color=None, spine_linewidth=None, ticks_direction='in', ticks_length=None, ticks_width=None, show_grid=True, show_legend=True, legend_loc='best', legend_ncol=1, show_zeroline=True)¶
- Parameters:
title (str | None)
xlabel (str | None)
ylabel (str | None)
zlabel (str | None)
xunits (str | None)
yunits (str | None)
title_fontsize (float | None)
axlabel_fontsize (float | None)
ticks_fontsize (float | None)
legend_fontsize (float | None)
title_fontweight (str)
axlabel_fontweight (str)
text_color (str | None)
chrome_color (str | None)
facecolor (str | None)
grid_color (str | None)
spine_linewidth (float | None)
ticks_direction (str)
ticks_length (float | None)
ticks_width (float | None)
show_grid (bool)
show_legend (bool)
legend_ncol (int)
show_zeroline (bool)
- Return type:
None
- class diive.plotting.CompoundExtremesPlot(x, y, category, category_styles=None, category_order=None, labels=None, threshold_x=2.0, threshold_y=-2.0)[source]¶
Bases:
objectQuadrant scatter of compound extremes. See
__init__().- Parameters:
- __init__(x, y, category, category_styles=None, category_order=None, labels=None, threshold_x=2.0, threshold_y=-2.0)[source]¶
Scatter of var1 vs var2 z-scores, coloured by extreme category.
Two-phase design: pass data and classification here, style and render in
plot().- Parameters:
x (
Series) – var1 z-scores (e.g. VPD), used for the x-axis.y (
Series) – var2 z-scores (e.g. soil water content), used for the y-axis.category (
Series) – Category per period — either CompoundExtremes codes (‘none’/’var1’/’var2’/’compound’) or arbitrary group labels. Aligned to x/y by index.category_styles (
dict) – Optional {key: {‘color’:, ‘marker’:, ‘label’:}} override. Missing entries fall back to the defaults (for code keys) or a palette. ‘label’ sets the legend text (default: the key, or the code’s role).category_order (
list) – Draw/legend order of categories (default: the standard none -> var1 -> var2 -> compound order, then any extra keys).labels (
Series) – Optional per-point annotations (e.g. ‘2022-08’), aligned by index.threshold_x (
float) – x-position of the vertical dashed threshold line (None to skip).threshold_y (
float) – y-position of the horizontal dashed threshold line (None to skip).
See also
- CompoundExtremesPlot.from_compound_extremesbuild directly from a
CompoundExtremesinstance.
examples/visualization/plot_compound_extremes.py : worked examples.
- classmethod from_compound_extremes(ce, annotate_labels=True)[source]¶
Build the plot straight from a fitted
CompoundExtremes.Pulls the z-score columns, category codes, per-category labels, period annotations, and threshold positions (signed by each variable’s extreme direction) from the analysis instance.
- Parameters:
ce – A fitted
CompoundExtremesinstance.annotate_labels (
bool) – Carry the period names (‘2022-08’, …) for annotation.
- plot(ax=None, format_style=None, figsize=(9, 8), figdpi=100, markersize=55, alpha=0.9, edgecolor='none', annotate=True, annotate_categories=None, annotate_fontsize=8.0, annotate_offset=(4.0, 2.0), threshold_color='#9E9E9E', legend=True, legend_title='Extreme', showplot=False)[source]¶
Render the quadrant scatter (Phase 2).
- Parameters:
ax – Target matplotlib axes. If None, a new figure is created.
format_style (
FormatStyle) – SharedFormatStylefor chrome (title/labels/fonts/grid/legend). Axis labels default to the z-score column names.figsize (
tuple) – Figure size in inches when ax is None.figdpi (
int) – Figure DPI when ax is None.markersize (
float) – Marker area (matplotlibs).alpha (
float) – Marker opacity.edgecolor (
str) – Marker edge colour (default ‘none’).annotate (
bool) – Annotate points with their labels (e.g. period names).annotate_categories (
list) – Restrict annotation to these category keys (default: every category except ‘none’, so only extremes are labelled).annotate_fontsize (
float) – Annotation font size.annotate_offset (
tuple) – (dx, dy) point offset for annotation text.threshold_color (
str) – Colour of the dashed threshold lines.legend (
bool) – Draw the category legend.FormatStyle(show_legend=False)also hides it.legend_title (
str) – Legend title.showplot (
bool) – Callfig.show()when a new figure was created.
- class diive.plotting.LongtermAnomaliesYear(series, reference_start_year, reference_end_year, series_label=None, series_units=None)[source]¶
Bases:
objectCalculate and plot long-term anomaly for a variable, per year, compared to a reference period.
Visualizes yearly anomalies as red/blue bars (above/below reference mean), with reference period mean ± standard deviation band for context.
Two-phase design: separate data preparation (__init__) from rendering (plot). Phase 1 creates the plotter with data; Phase 2 renders with styling options.
- Parameters:
series (
Series) – Time series for anomalies with one value per year (pandas Series with year index)reference_start_year (
int) – First year of the reference period (int)reference_end_year (
int) – Last year of the reference period (int)series_label (
str) – Description label for the variable (displayed in the title and the y-axis label)series_units (
str) – Units string for the variable (displayed on y-axis, e.g., ‘(°C)’)
- Methods:
plot – Render anomaly bar chart with styling options
Example
See examples/visualization/plot_other_plots.py for complete example.
- __init__(series, reference_start_year, reference_end_year, series_label=None, series_units=None)[source]¶
Prepare long-term anomaly data for plotting.
- Parameters:
series (
Series) – Data to plot (pandas Series with year index)reference_start_year (
int) – First year of reference period for anomaly calculationreference_end_year (
int) – Last year of reference period for anomaly calculationseries_label (
str) – Label for the variable (used in the plot title and y-axis label)series_units (
str) – Units string (e.g., ‘(°C)’, appended to y-axis label)
See also
plot : Render the anomaly chart with matplotlib styling options
- property anomalies_df: DataFrame¶
Results frame (copy), with the data column back under the caller’s Series name.
- plot(ax=None, format_style=None)[source]¶
Render long-term anomaly bar chart with matplotlib styling (Phase 2 of two-phase design).
Chrome (title, labels, units, font sizes, colours, grid, ticks, spines, zero line) comes from a shared
FormatStyleso it looks and is configured the same way as every other diive plot. The red/blue above/below bar colouring is data encoding and stays here. Can be called multiple times on the same object to draw on different axes with different styling; calling it again on an axes it already drew on replaces that rendering rather than stacking a second one on top of it.- Parameters:
ax – Matplotlib axes to plot on. If None, creates new figure and displays it
format_style (
FormatStyle) – AFormatStyledescribing the chrome. When None the diive house style is used.
- Returns:
None (displays plot if ax=None, otherwise renders on provided axes)
Example
>>> import diive as dv, pandas as pd, matplotlib.pyplot as plt >>> annual = pd.Series([5.1, 5.4, 6.0, 6.3], index=[2021, 2022, 2023, 2024], name='TA') >>> anomaly = dv.plotting.LongtermAnomaliesYear(annual, 2021, 2022) >>> anomaly.plot(ax=plt.subplots()[1], format_style=dv.plotting.FormatStyle(title='TA'))
- get()[source]¶
Return the axes this plot was rendered on.
- Raises:
RuntimeError – If called before plot(). There is no axes until phase 2 has run, and the bare AttributeError this used to raise named an internal attribute rather than the step that was skipped.
- class diive.plotting.Cumulative(df, units=None, start_year=None, end_year=None)[source]¶
Bases:
objectPlot cumulative sums across all data.
Visualizes cumulative sums for each column in the input DataFrame with values displayed at the end of each series.
- Parameters:
See also
examples/visualization/plot_cumulative_basic.py — Cumulative plots with multiple scenarios examples/flux/lowres/flux_uncertainty.py — Cumulative uncertainty visualization
- __init__(df, units=None, start_year=None, end_year=None)[source]¶
Compute cumulative sums per column. See the class docstring for parameters.
- plot(ax=None, format_style=None, showplot=True, digits_after_comma=0, show_title=True, fill=False)[source]¶
Plot the cumulative sum of each column, with the final total in each legend label.
- Parameters:
ax – Matplotlib axes to draw on; a standalone figure is created if None.
format_style (
FormatStyle) – Shared chrome (labels/fonts/grid/legend). None = house style. The title is generated from the date range, soformat_style.titlehas no effect (useshow_titleto hide it). The constructor’sunits, when given, overrideformat_style.yunits.showplot (
bool) – If True and a new figure was created, show it.digits_after_comma (
int) – Decimal places for the end-of-series total in each legend label.show_title (
bool) – If True, draw the auto-generated title.fill (
bool) – If True, shade the area between each curve and zero.
- Returns:
The matplotlib axes the curves were drawn on.
- class diive.plotting.CumulativeYear(series, series_units=None, yearly_end_date=None, start_year=None, end_year=None, show_reference=False, excl_years_from_reference=None, highlight_year=None, highlight_year_color=None)[source]¶
Bases:
objectPlot yearly cumulative sums with reference mean and standard deviation.
Visualizes cumulative sums for each year with optional reference period mean and ±1 standard deviation band for comparison.
See also
examples/visualization/plot_cumulative_basic.py — Yearly cumulative plots with reference bands
- Parameters:
- __init__(series, series_units=None, yearly_end_date=None, start_year=None, end_year=None, show_reference=False, excl_years_from_reference=None, highlight_year=None, highlight_year_color=None)[source]¶
Compute the cumulative sum of each year by day of year.
- Parameters:
series (
Series) – Time series to accumulate. Missing values (NaN) and infinite values (+inf, -inf) are left out.series_units (
str) – Units shown on the y-axis label, LaTeX format is supported.yearly_end_date (
str) – Calculate cumulatives up to this date, given as string, e.g. “08-11” means that cumulatives for each year are calculated until 11 August of each year.start_year (
int) – First year to show. None uses the first year in the data.end_year (
int) – Last year to show. None uses the last year in the data.show_reference (
bool) – If True, plot the mean cumulative across years and a band of ±1 standard deviation around it.excl_years_from_reference (
list) – Years left out of the reference mean and SD.highlight_year (
int) – Year drawn with a wider line in the highlight colour.highlight_year_color (
str) – Deprecated. Pass this styling option to plot() instead.
- plot(ax=None, format_style=None, showplot=True, digits_after_comma=2, highlight_year_color=None)[source]¶
Plot one cumulative-sum curve per year on a shared day-of-year axis.
Without a single finite value to accumulate, the axes stay empty and show the note “no finite values”.
- Parameters:
ax – Matplotlib axes to draw on; a standalone figure is created if None.
format_style (
FormatStyle) – Shared chrome (labels/fonts/grid/legend). None = house style. The title is generated from the years and the last day of year, soformat_style.titlehas no effect. The constructor’sseries_units, when given, overrideformat_style.yunits.showplot (
bool) – If True and a new figure was created, show it.digits_after_comma (
int) – Decimal places for the end-of-year total in each legend label.highlight_year_color (
str) – Colour for the highlighted year; defaults to red.
- Returns:
The matplotlib axes the curves were drawn on.
- class diive.plotting.DielCycle(series)[source]¶
Bases:
objectPlot the diel (24-hour) cycle of a time series. See
__init__()andplot().- Parameters:
series (Series)
- __init__(series)[source]¶
Plot diel cycles of time series.
- Parameters:
series (
Series) – Time series with datetime index. The index must contain date and time info.
See also
examples/visualization/plot_dielcycle.py — Diurnal cycle analysis and visualization
- get_data()[source]¶
Return the diel-cycle aggregates DataFrame (raises if
plot()not yet run).- Return type:
- property diel_cycles_df¶
Return dataframe containing diel cycle aggregates.
- plot(ax=None, format_style=None, color=None, agg='mean', band='sd', each_month=False, cmap=None, marker=False, markersize=4, linewidth=2, ylim=None, show_xticklabels=True, show_xlabel=True, mean=None, std=None, **kwargs)[source]¶
Plot the diel (24-hour) cycle, optionally one curve per month.
Chrome (title, labels, units, font sizes, colours, grid, legend, zero line) comes from a shared
FormatStyle.- Parameters:
ax (
Axes) – Matplotlib axes to draw on. If None, a new figure is created and shown.format_style (
FormatStyle) – AFormatStyledescribing the chrome. When None the diive house style is used.color (
str) – Colour of every curve. None picks the colours automatically (fromcmapor the diive 12-month palette).agg (
Literal['mean','median','min','max','p25','p75']) – Central aggregation drawn as the curve:'mean','median','min','max','p25'or'p75'(25th/75th percentile).band (
Literal['none','sd','se','iqr','minmax']) – Uncertainty band drawn around the curve:'sd'(±1 standard deviation),'se'(±1 standard error),'iqr'(25th-75th percentile),'minmax'(per-time-of-day range), or'none'.each_month (
bool) – One curve per month (seasonal pattern) instead of a single curve over all data.cmap (
str) – Colormap name to draw the per-month colours from (each_monthonly).Noneuses the diive 12-month palette.marker (
bool) – Draw a marker at each time-of-day point.markersize (
float) – Marker size (whenmarkeris True).linewidth (
float) – Line width of the curves.ylim (
list) – Y-axis limits as[min, max]. None scales to the data.show_xticklabels (
bool) – Show the hour labels on the x-axis.show_xlabel (
bool) – Show the x-axis label.mean (
bool) – Deprecated. Kept for back-compat; ignored (useagg).std (
bool) – Deprecated. Kept for back-compat;Falsemaps toband='none'.**kwargs – Passed on to matplotlib’s
ax.plotfor each curve.
- class diive.plotting.HeatmapDateTime(series, ax_orientation='vertical', verbose=False)[source]¶
Bases:
HeatmapBaseHeatmap of a time series arranged as a date × time-of-day grid.
The series is pivoted so that every unique date forms one row and every unique time-of-day forms one column (or the transpose in
'horizontal'orientation). Each cell color represents the measured value at that date/time combination; NaN cells are filled withcolor_bad.The time-of-day axis is stored internally as float hours (e.g.
0.5for 00:30,6.0for 06:00) becausepcolormeshrequires numeric coordinates.Public name:
dv.plotting.HeatmapDateTime(series, ...)See also
examples/visualization/plot_heatmap_datetime_basic.py — DateTime heatmap variations (vertical/horizontal) examples/gapfilling/gapfill_interpolate_generous.py — Heatmap in gap-filling context examples/gapfilling/gapfill_randomforest.py — Heatmap for model output visualization
- __init__(series, ax_orientation='vertical', verbose=False)[source]¶
Prepare time series data for heatmap plotting (Phase 1 of two-phase design).
- Parameters:
series (
Series) – Pandas Series with aDatetimeIndex(or compatible datetime-like index following diive’s timestamp naming convention). Any temporal resolution is supported; the series will be sanitized and regularised automatically.ax_orientation (
str) – Layout of the axes.'vertical'(default) — dates on y-axis, hours on x-axis.'horizontal'— dates on x-axis, hours on y-axis.verbose (
bool) – Print progress and diagnostic messages. Defaults to False.
See also
plot : Render the heatmap with matplotlib styling options
- plot(ax=None, fig=None, figsize=None, figdpi=72, ax_orientation=None, format_style=None, vmin=None, vmax=None, cmap='RdYlBu_r', zlabel=None, cb_digits_after_comma=2, cb_labelsize=None, cb_extend='neither', minticks=3, maxticks=10, color_bad='grey', show_colormap=True, show_less_xticklabels=False, show_values=False, show_values_fontsize=None, show_values_n_dec_places=0, show_values_max_cells=2000, as_image=False)[source]¶
Render HeatmapDateTime with matplotlib styling (Phase 2 of two-phase design).
All styling and presentation parameters go here. Can be called multiple times on the same HeatmapDateTime object to plot on different axes with different styling.
- Parameters:
ax – Matplotlib axes to plot on. If None, creates new figure and displays it
fig – Existing matplotlib Figure. If None and ax is None, creates new figure
figsize (
tuple) – Figure size as (width, height) in inches. Only used when ax is Nonefigdpi (
int) – Figure DPI. Only used when ax is None. Defaults to 72ax_orientation (
str) – Layout of axes. If None, uses the value from __init__(). The grid is built in __init__, so set the orientation there. A different value here raises a ValueError.format_style (
FormatStyle) – Shared chrome (title/labels/fonts/ticks/spines/grid) viaFormatStyle. None = heatmap default (no grid, black spines, outward ticks). A passed style replaces that default as a whole. The colorbar stayscb_*/zlabel-controlled.vmin (
float) – Minimum color value (auto from data if None)vmax (
float) – Maximum color value (auto from data if None)cmap (
str) – Colormap name (default: ‘RdYlBu_r’)zlabel (
str) – Colorbar label (e.g., ‘°C’, ‘µmol m⁻²s⁻¹’)cb_digits_after_comma (
int|str) – Decimal places on colorbar labels (default: 2), or ‘auto’ to pick them from the data rangecb_labelsize (
float) – Font size for colorbar tick labelscb_extend (
str) – Colorbar extension arrows (‘neither’, ‘both’, ‘min’, ‘max’)minticks (
int) – Minimum major ticks on date axis (default: 3)maxticks (
int) – Maximum major ticks on date axis (default: 10)color_bad (
str) – Color for NaN cells (default: ‘grey’)show_colormap (
bool) – Whether to show colorbar (default: True)show_less_xticklabels (
bool) – Hide every second x-tick label (default: False)show_values (
bool) – Overlay numeric values on cells (default: False)show_values_fontsize (
float) – Font size for value overlay textshow_values_n_dec_places (
int) – Decimal places for value overlay (default: 0)show_values_max_cells (
int|None) – Largest grid the overlay is drawn on; above it the overlay is skipped with a warning (default:SHOW_VALUES_MAX_CELLS). One year of half-hourly data is 17 520 cells, where one label per cell is unreadable and slows down every later redraw. Raise it, or pass None for no limit, to label such a grid anyway.as_image (
bool) – Draw the grid as one image (imshow) instead of one quad per cell (pcolormesh, the default). A long record then draws and redraws many times faster, which matters in an interactive window that is panned or zoomed. It looks the same; where one pixel covers several days, the two methods can show a different one of those days. The heatmap’s artist is then anAxesImageinstead of aQuadMesh. Falls back to the mesh if the grid is not evenly spaced. Defaults to False.
- Returns:
None (displays plot if ax=None, otherwise renders on provided axes)
- export_borderless_heatmap(outpath)¶
Exports borderless heatmap images for use as textures or heightmaps in 3-D software.
Generates four 300 dpi PNG files — two greyscale heightmaps (normal and reversed) and two colour textures (
jetnormal and reversed). Each image is rendered without any axes, ticks, labels, or borders so it can be loaded directly into Blender or similar tools.Output filenames follow the pattern
heatmap_{plottype}_{series_name}.pngwhereplottypeis one ofheightmap_bw,heightmap_bw_r,texture_color,texture_color_r.Note
This method is experimental and may change in future versions.
- Parameters:
outpath (
str) – Directory where the PNG files are saved. Created automatically if it does not exist.
- format(ax_xlabel_txt, ax_ylabel_txt, plot, shown_freq=None)¶
Applies title, colorbar, axis labels, tick formatting, and spine styling.
Title logic:
If
format_style.titleis set it is used as-is (""hides the title).Otherwise, if
shown_freqis given, the title is auto-generated as"{series.name} ({shown_freq})".Otherwise no title is shown.
- Parameters:
ax_xlabel_txt (str) – Label for the x-axis.
ax_ylabel_txt (str) – Label for the y-axis.
plot (matplotlib.collections.QuadMesh) – Mesh object returned by
plot_pcolormesh(), used to create the colorbar.shown_freq (
str) – Frequency or aggregation descriptor appended to the auto-generated title (e.g.'30min','mean, MS'). Pass None to omit.
- get_ax()¶
Returns the Matplotlib Axes object where the plot was generated.
- Returns:
The Axes object containing the heatmap.
- Return type:
- get_plot_data()¶
Returns the pivot DataFrame used to plot the heatmap.
This DataFrame contains the reshaped data (self.plotdf) that forms the grid of values for the heatmap.
- Returns:
The DataFrame used for plotting.
- Return type:
- plot_image()¶
Renders
self.x,self.y,self.zas an image (imshow).The same cells as
plot_pcolormesh(), drawn as one image instead of one quad per cell, which makes drawing a large grid many times cheaper (ten years of half-hourly data are 175 000 cells). Only a regular grid can be an image, soxandymust be evenly spaced cell boundaries;datetime.dateboundaries are converted to date numbers and the axis is set up as a date axis, aspcolormeshdoes.On screen the two agree: where one pixel covers several cells, each method shows one of them and they can pick a different one.
- Returns:
The image, or None when the grid is not evenly spaced (nothing is drawn then).
- Return type:
matplotlib.image.AxesImage or None
- plot_pcolormesh(shading=None)¶
Renders
self.x,self.y,self.zas apcolormeshplot.Calls
set_cmap()first to copy the colormap and mask NaN values inzso they are rendered incolor_badinstead of the nearest valid colour. The masked array is passed directly topcolormesh— not the original unmaskedself.z— so missing cells are always visible.- Parameters:
shading (
str) – Shading algorithm passed topcolormesh.'flat'assigns the cell colour from the value at the lower-left corner;'auto'/ None lets matplotlib choose based on whetherx/yare the same length aszor one longer (boundary mode). Defaults to None.- Returns:
The mesh object, which is needed by
format()to attach the colorbar.- Return type:
- static set_cmap(cmap, color_bad, z)¶
Prepares a colormap and masks invalid data values.
The colormap is copied before mutation because calling
set_badon a shared global colormap would affect every other plot that uses the same colormap in the same session (see matplotlib issue #17634).- Parameters:
- Returns:
cmap (matplotlib.colors.Colormap) — deep copy of the requested colormap with the bad-value colour applied.
z (np.ma.MaskedArray) — input array with NaN and ±inf entries masked so
pcolormeshrenders them incolor_bad.
- Return type:
- show()¶
Generates the heatmap plot with defaults and displays the figure.
This method calls the plot method (which should be implemented by subclasses) with all default styling options, then uses self.fig.show() to display the generated Matplotlib figure.
- show_vals_in_plot()¶
Overlays the numeric z-value on every heatmap cell.
Iterates over all
(i, j)cells ofself.zand callsax.textat the centre of each cell. NaN cells are skipped (rendered as an empty string).Cell-centre coordinates are computed differently depending on
self.heatmaptypebecause the axis dtypes differ:'xyz'/'datetime'— plain numeric midpoint(a + b) / 2.'yearmonth'— integer offsetx + 0.5(months/years are 1-indexed integers with unit cell width).'datetime_horizontal'— numeric midpoint on the float-hour y-axis;timedeltamidpoint on thedatetime.datex-axis.
Grids larger than
self.show_values_max_cells(set byplot(), defaultSHOW_VALUES_MAX_CELLS) are skipped with a warning: one text artist per cell is illegible at that size and stays on the axes, so it also slows down every later re-layout of the figure.- Raises:
NotImplementedError – If
self.heatmaptypeis not one of the supported values listed above.
Note
Overlaying values on a full-resolution
HeatmapDateTimewith thousands of cells produces an unreadable result. This method is most useful for coarse grids such asHeatmapYearMonth.
- class diive.plotting.HeatmapYearMonth(series, agg='mean', ranks=False, ax_orientation='vertical', verbose=False)[source]¶
Bases:
HeatmapBaseA class for plotting heatmaps of time series data aggregated by year and month.
This class extends HeatmapBase to visualize monthly aggregated time series data, where one axis represents years and the other represents months. It supports different aggregation methods and the display of ranks instead of raw values.
See also
examples/visualization/plot_heatmap_datetime_basic.py — Year/Month heatmap variations (rank, multi-panel, colormaps)
- __init__(series, agg='mean', ranks=False, ax_orientation='vertical', verbose=False)[source]¶
Prepare year-month aggregated data for heatmap plotting (Phase 1 of two-phase design).
- Parameters:
series (
Series) – Pandas Series with a datetime-like index representing the time series data.agg (
str) – Aggregation method (‘mean’, ‘sum’, ‘median’, ‘min’, ‘max’). Defaults to ‘mean’.ranks (
bool) – Convert data to ranks before plotting. Defaults to False.ax_orientation (
str) – Layout of axes (‘vertical’ or ‘horizontal’). Defaults to ‘vertical’.verbose (
bool) – Print progress and diagnostic messages. Defaults to False.
See also
plot : Render the heatmap with matplotlib styling options
- plot(ax=None, fig=None, figsize=None, figdpi=72, ax_orientation=None, format_style=None, vmin=None, vmax=None, cmap=None, zlabel=None, cb_digits_after_comma=2, cb_labelsize=None, cb_extend='neither', minticks=3, maxticks=10, color_bad='grey', show_colormap=True, show_less_xticklabels=False, show_values=False, show_values_fontsize=None, show_values_n_dec_places=0, show_values_max_cells=2000)[source]¶
Render HeatmapYearMonth with matplotlib styling (Phase 2 of two-phase design).
All styling and presentation parameters go here. Can be called multiple times on the same HeatmapYearMonth object to plot on different axes with different styling.
- Parameters:
ax – Matplotlib axes to plot on. If None, creates new figure and displays it
fig – Existing matplotlib Figure. If None and ax is None, creates new figure
figsize (
tuple) – Figure size as (width, height) in inches. Only used when ax is Nonefigdpi (
int) – Figure DPI. Only used when ax is None. Defaults to 72ax_orientation (
str) – Layout of axes. If None, uses the value from __init__(). The grid is built in __init__, so set the orientation there. A different value here raises a ValueError.format_style (
FormatStyle) – Shared chrome (title/labels/fonts/ticks/spines/grid) viaFormatStyle. None = heatmap default (no grid, black spines, outward ticks). A passed style replaces that default as a whole. The colorbar stayscb_*/zlabel-controlled.vmin (
float) – Minimum color value (auto from data if None)vmax (
float) – Maximum color value (auto from data if None)cmap (
str) – Colormap name (auto-selected if None: ‘RdYlBu’ for ranks, ‘RdYlBu_r’ for raw)zlabel (
str) – Colorbar labelcb_digits_after_comma (
int|str) – Decimal places on colorbar labels (default: 2), or ‘auto’ to pick them from the data rangecb_labelsize (
float) – Font size for colorbar tick labelscb_extend (
str) – Colorbar extension arrows (‘neither’, ‘both’, ‘min’, ‘max’)minticks (
int) – Not used here, the ticks are one per month and year (kept for signature parity with the other heatmaps)maxticks (
int) – Not used here, seemintickscolor_bad (
str) – Color for NaN cells (default: ‘grey’)show_colormap (
bool) – Whether to show colorbar (default: True)show_less_xticklabels (
bool) – Hide every second x-tick label (default: False)show_values (
bool) – Overlay numeric values on cells (default: False)show_values_fontsize (
float) – Font size for value overlay textshow_values_n_dec_places (
int) – Decimal places for value overlay (default: 0)show_values_max_cells (
int|None) – Largest grid the overlay is drawn on; above it the overlay is skipped with a warning (default:SHOW_VALUES_MAX_CELLS). A year x month grid holds 12 cells per year, so no realistic record comes near the limit.
- Returns:
None (displays plot if ax=None, otherwise renders on provided axes)
- export_borderless_heatmap(outpath)¶
Exports borderless heatmap images for use as textures or heightmaps in 3-D software.
Generates four 300 dpi PNG files — two greyscale heightmaps (normal and reversed) and two colour textures (
jetnormal and reversed). Each image is rendered without any axes, ticks, labels, or borders so it can be loaded directly into Blender or similar tools.Output filenames follow the pattern
heatmap_{plottype}_{series_name}.pngwhereplottypeis one ofheightmap_bw,heightmap_bw_r,texture_color,texture_color_r.Note
This method is experimental and may change in future versions.
- Parameters:
outpath (
str) – Directory where the PNG files are saved. Created automatically if it does not exist.
- format(ax_xlabel_txt, ax_ylabel_txt, plot, shown_freq=None)¶
Applies title, colorbar, axis labels, tick formatting, and spine styling.
Title logic:
If
format_style.titleis set it is used as-is (""hides the title).Otherwise, if
shown_freqis given, the title is auto-generated as"{series.name} ({shown_freq})".Otherwise no title is shown.
- Parameters:
ax_xlabel_txt (str) – Label for the x-axis.
ax_ylabel_txt (str) – Label for the y-axis.
plot (matplotlib.collections.QuadMesh) – Mesh object returned by
plot_pcolormesh(), used to create the colorbar.shown_freq (
str) – Frequency or aggregation descriptor appended to the auto-generated title (e.g.'30min','mean, MS'). Pass None to omit.
- get_ax()¶
Returns the Matplotlib Axes object where the plot was generated.
- Returns:
The Axes object containing the heatmap.
- Return type:
- get_plot_data()¶
Returns the pivot DataFrame used to plot the heatmap.
This DataFrame contains the reshaped data (self.plotdf) that forms the grid of values for the heatmap.
- Returns:
The DataFrame used for plotting.
- Return type:
- plot_image()¶
Renders
self.x,self.y,self.zas an image (imshow).The same cells as
plot_pcolormesh(), drawn as one image instead of one quad per cell, which makes drawing a large grid many times cheaper (ten years of half-hourly data are 175 000 cells). Only a regular grid can be an image, soxandymust be evenly spaced cell boundaries;datetime.dateboundaries are converted to date numbers and the axis is set up as a date axis, aspcolormeshdoes.On screen the two agree: where one pixel covers several cells, each method shows one of them and they can pick a different one.
- Returns:
The image, or None when the grid is not evenly spaced (nothing is drawn then).
- Return type:
matplotlib.image.AxesImage or None
- plot_pcolormesh(shading=None)¶
Renders
self.x,self.y,self.zas apcolormeshplot.Calls
set_cmap()first to copy the colormap and mask NaN values inzso they are rendered incolor_badinstead of the nearest valid colour. The masked array is passed directly topcolormesh— not the original unmaskedself.z— so missing cells are always visible.- Parameters:
shading (
str) – Shading algorithm passed topcolormesh.'flat'assigns the cell colour from the value at the lower-left corner;'auto'/ None lets matplotlib choose based on whetherx/yare the same length aszor one longer (boundary mode). Defaults to None.- Returns:
The mesh object, which is needed by
format()to attach the colorbar.- Return type:
- static set_cmap(cmap, color_bad, z)¶
Prepares a colormap and masks invalid data values.
The colormap is copied before mutation because calling
set_badon a shared global colormap would affect every other plot that uses the same colormap in the same session (see matplotlib issue #17634).- Parameters:
- Returns:
cmap (matplotlib.colors.Colormap) — deep copy of the requested colormap with the bad-value colour applied.
z (np.ma.MaskedArray) — input array with NaN and ±inf entries masked so
pcolormeshrenders them incolor_bad.
- Return type:
- show()¶
Generates the heatmap plot with defaults and displays the figure.
This method calls the plot method (which should be implemented by subclasses) with all default styling options, then uses self.fig.show() to display the generated Matplotlib figure.
- show_vals_in_plot()¶
Overlays the numeric z-value on every heatmap cell.
Iterates over all
(i, j)cells ofself.zand callsax.textat the centre of each cell. NaN cells are skipped (rendered as an empty string).Cell-centre coordinates are computed differently depending on
self.heatmaptypebecause the axis dtypes differ:'xyz'/'datetime'— plain numeric midpoint(a + b) / 2.'yearmonth'— integer offsetx + 0.5(months/years are 1-indexed integers with unit cell width).'datetime_horizontal'— numeric midpoint on the float-hour y-axis;timedeltamidpoint on thedatetime.datex-axis.
Grids larger than
self.show_values_max_cells(set byplot(), defaultSHOW_VALUES_MAX_CELLS) are skipped with a warning: one text artist per cell is illegible at that size and stays on the axes, so it also slows down every later re-layout of the figure.- Raises:
NotImplementedError – If
self.heatmaptypeis not one of the supported values listed above.
Note
Overlaying values on a full-resolution
HeatmapDateTimewith thousands of cells produces an unreadable result. This method is most useful for coarse grids such asHeatmapYearMonth.
- class diive.plotting.HeatmapXYZ(x, y, z, xlabel=None, ylabel=None, zlabel=None, xtickpos=None, xticklabels=None, ytickpos=None, yticklabels=None, verbose=False)[source]¶
Bases:
HeatmapBaseHeatmap built from three parallel Series: x coordinates, y coordinates, and z values.
Important: Input Series must be pre-aggregated, with exactly one value per unique (x, y) coordinate pair. The typical source is
GridAggregator.df_agg_long.The three Series are combined into a long-format DataFrame and pivoted into a 2-D grid (y rows × x columns) whose cells are colour-coded by the z value. Cell boundaries are computed automatically from the coordinate spacing so that
pcolormeshrenders each cell at the correct position.Example
See examples/visualization/plot_heatmap_xyz_basic.py for complete examples with GridAggregator integration and styling options.
>>> import diive as dv, pandas as pd, numpy as np >>> gx, gy = np.meshgrid(np.arange(5.), np.arange(4.)) >>> hm = dv.plotting.HeatmapXYZ(x=pd.Series(gx.ravel(), name='TA'), ... y=pd.Series(gy.ravel(), name='VPD'), z=pd.Series(np.arange(20.), name='NEE'))
See also
GridAggregator : Bin and aggregate data into pre-aggregated format HeatmapDateTime : For temporal heatmaps (date × time-of-day)
- Parameters:
- __init__(x, y, z, xlabel=None, ylabel=None, zlabel=None, xtickpos=None, xticklabels=None, ytickpos=None, yticklabels=None, verbose=False)[source]¶
Prepare 2D grid data for heatmap plotting (Phase 1 of two-phase design).
- Parameters:
x (
Series) – Series of x-coordinates (becomes column axis after pivoting). Must have a non-Nonename unique across x, y, z.y (
Series) – Series of y-coordinates (becomes row axis after pivoting). Must have a non-Nonename unique across x, y, z.z (
Series) – Series of cell values mapped to colour. Must have a non-Nonename unique across x, y, z.xlabel (
str) – Deprecated, pass it toplot()instead. x-axis label. If None, usesx.name.ylabel (
str) – Deprecated, pass it toplot()instead. y-axis label. If None, usesy.name.zlabel (
str) – Deprecated, pass it toplot()instead. Colorbar label. If None, usesz.name.xtickpos (
list) – Explicit x-axis tick positions (None = auto).xticklabels (
list) – Tick labels matching xtickpos (ignored if xtickpos is None).ytickpos (
list) – Explicit y-axis tick positions (None = auto).yticklabels (
list) – Tick labels matching ytickpos (ignored if ytickpos is None).verbose (
bool) – Print progress and diagnostic messages. Defaults to False.
- Raises:
ValueError – If x, y, or z has None name, non-unique names, or different lengths.
See also
plot : Render the heatmap with matplotlib styling options
- classmethod from_gridaggregator(gridagg, x_col, y_col, z_col, xlabel=None, ylabel=None, zlabel=None, **kwargs)[source]¶
Create HeatmapXYZ from GridAggregator output.
Convenience constructor that automatically extracts pre-aggregated data from
GridAggregator.df_agg_longand handles bin column naming conventions, eliminating the need for manual DataFrame extraction.- Parameters:
gridagg – GridAggregator instance with binned and aggregated output
x_col (
str) – Original x series name used when creating GridAggregator (e.g., ‘Tair_f’, not ‘BIN_Tair_f’). Will be automatically converted to the bin column name ‘BIN_Tair_f’.y_col (
str) – Original y series name used when creating GridAggregatorz_col (
str) – Original z series name used when creating GridAggregator. The aggregated z-values in df_agg_long keep the original name (noBIN_prefix).xlabel (
str) – x-axis label. When None, usesx_col.ylabel (
str) – y-axis label. When None, usesy_col.zlabel (
str) – Colorbar label. When None, usesz_col.**kwargs – Further keyword arguments accepted by
HeatmapXYZ.__init__(), i.e.xtickpos/xticklabels,ytickpos/yticklabelsandverbose. Rendering options (figsize,cmap,vmin/vmax,show_values, …) belong toplot(), not here — this is Phase 1.
- Return type:
- Returns:
HeatmapXYZ instance ready to plot.
- Raises:
AttributeError – If
gridagg.df_agg_longis not available.KeyError – If
x_col,y_col, orz_colnot found in df_agg_long.
Example
>>> import diive as dv, pandas as pd, numpy as np >>> ta, vpd, nee = (pd.Series(np.arange(100.), name=n) for n in ('TA', 'VPD', 'NEE')) >>> q = dv.analysis.GridAggregator(x=ta, y=vpd, z=nee, binning_type='quantiles', n_bins=5) >>> hm = dv.plotting.HeatmapXYZ.from_gridaggregator(q, 'TA', 'VPD', 'NEE')
- plot(ax=None, fig=None, figsize=None, figdpi=72, format_style=None, vmin=None, vmax=None, cmap='RdYlBu_r', cb_digits_after_comma=2, cb_labelsize=None, cb_extend='neither', color_bad='grey', show_colormap=True, show_values=False, show_values_fontsize=None, show_values_n_dec_places=0, xlabel=None, ylabel=None, zlabel=None)[source]¶
Render HeatmapXYZ with matplotlib styling (Phase 2 of two-phase design).
All styling and presentation parameters go here. Can be called multiple times on the same HeatmapXYZ object to plot on different axes with different styling.
- Parameters:
ax – Matplotlib axes to plot on. If None, creates new figure and displays it
fig – Existing matplotlib Figure. If None and ax is None, creates new figure
figsize (
tuple) – Figure size as (width, height) in inches. Only used when ax is Nonefigdpi (
int) – Figure DPI. Only used when ax is None. Defaults to 72format_style (
FormatStyle) – Shared chrome (title/labels/fonts/ticks/spines/grid) viaFormatStyle. None = heatmap default (no grid, black spines, outward ticks). A passed style replaces that default as a whole. Thexlabel/ylabelbelow are the defaults for the axis labels, andformat_style.xlabel/ylabeloverride them. The colorbar stayscb_*/zlabel-controlled.vmin (
float) – Minimum color value (auto from data if None)vmax (
float) – Maximum color value (auto from data if None)cmap (
str) – Colormap name (default: ‘RdYlBu_r’)cb_digits_after_comma (
int) – Decimal places on colorbar labels (default: 2), or ‘auto’ to pick them from the data rangecb_labelsize (
float) – Font size for colorbar tick labelscb_extend (
str) – Colorbar extension arrows (‘neither’, ‘both’, ‘min’, ‘max’)color_bad (
str) – Color for NaN cells (default: ‘grey’)show_colormap (
bool) – Whether to show colorbar (default: True)show_values (
bool) – Overlay numeric values on cells (default: False)show_values_fontsize (
float) – Font size for value overlay textshow_values_n_dec_places (
int) – Decimal places for value overlay (default: 0)xlabel (
str) – x-axis label. None uses the label from the constructor (x.nameby default).ylabel (
str) – y-axis label. None uses the label from the constructor (y.nameby default).zlabel (
str) – Colorbar label. None uses the label from the constructor (z.nameby default).
- Returns:
None (displays plot if ax=None, otherwise renders on provided axes)
- export_borderless_heatmap(outpath)¶
Exports borderless heatmap images for use as textures or heightmaps in 3-D software.
Generates four 300 dpi PNG files — two greyscale heightmaps (normal and reversed) and two colour textures (
jetnormal and reversed). Each image is rendered without any axes, ticks, labels, or borders so it can be loaded directly into Blender or similar tools.Output filenames follow the pattern
heatmap_{plottype}_{series_name}.pngwhereplottypeis one ofheightmap_bw,heightmap_bw_r,texture_color,texture_color_r.Note
This method is experimental and may change in future versions.
- Parameters:
outpath (
str) – Directory where the PNG files are saved. Created automatically if it does not exist.
- format(ax_xlabel_txt, ax_ylabel_txt, plot, shown_freq=None)¶
Applies title, colorbar, axis labels, tick formatting, and spine styling.
Title logic:
If
format_style.titleis set it is used as-is (""hides the title).Otherwise, if
shown_freqis given, the title is auto-generated as"{series.name} ({shown_freq})".Otherwise no title is shown.
- Parameters:
ax_xlabel_txt (str) – Label for the x-axis.
ax_ylabel_txt (str) – Label for the y-axis.
plot (matplotlib.collections.QuadMesh) – Mesh object returned by
plot_pcolormesh(), used to create the colorbar.shown_freq (
str) – Frequency or aggregation descriptor appended to the auto-generated title (e.g.'30min','mean, MS'). Pass None to omit.
- get_ax()¶
Returns the Matplotlib Axes object where the plot was generated.
- Returns:
The Axes object containing the heatmap.
- Return type:
- get_plot_data()¶
Returns the pivot DataFrame used to plot the heatmap.
This DataFrame contains the reshaped data (self.plotdf) that forms the grid of values for the heatmap.
- Returns:
The DataFrame used for plotting.
- Return type:
- plot_image()¶
Renders
self.x,self.y,self.zas an image (imshow).The same cells as
plot_pcolormesh(), drawn as one image instead of one quad per cell, which makes drawing a large grid many times cheaper (ten years of half-hourly data are 175 000 cells). Only a regular grid can be an image, soxandymust be evenly spaced cell boundaries;datetime.dateboundaries are converted to date numbers and the axis is set up as a date axis, aspcolormeshdoes.On screen the two agree: where one pixel covers several cells, each method shows one of them and they can pick a different one.
- Returns:
The image, or None when the grid is not evenly spaced (nothing is drawn then).
- Return type:
matplotlib.image.AxesImage or None
- plot_pcolormesh(shading=None)¶
Renders
self.x,self.y,self.zas apcolormeshplot.Calls
set_cmap()first to copy the colormap and mask NaN values inzso they are rendered incolor_badinstead of the nearest valid colour. The masked array is passed directly topcolormesh— not the original unmaskedself.z— so missing cells are always visible.- Parameters:
shading (
str) – Shading algorithm passed topcolormesh.'flat'assigns the cell colour from the value at the lower-left corner;'auto'/ None lets matplotlib choose based on whetherx/yare the same length aszor one longer (boundary mode). Defaults to None.- Returns:
The mesh object, which is needed by
format()to attach the colorbar.- Return type:
- static set_cmap(cmap, color_bad, z)¶
Prepares a colormap and masks invalid data values.
The colormap is copied before mutation because calling
set_badon a shared global colormap would affect every other plot that uses the same colormap in the same session (see matplotlib issue #17634).- Parameters:
- Returns:
cmap (matplotlib.colors.Colormap) — deep copy of the requested colormap with the bad-value colour applied.
z (np.ma.MaskedArray) — input array with NaN and ±inf entries masked so
pcolormeshrenders them incolor_bad.
- Return type:
- show()¶
Generates the heatmap plot with defaults and displays the figure.
This method calls the plot method (which should be implemented by subclasses) with all default styling options, then uses self.fig.show() to display the generated Matplotlib figure.
- show_vals_in_plot()¶
Overlays the numeric z-value on every heatmap cell.
Iterates over all
(i, j)cells ofself.zand callsax.textat the centre of each cell. NaN cells are skipped (rendered as an empty string).Cell-centre coordinates are computed differently depending on
self.heatmaptypebecause the axis dtypes differ:'xyz'/'datetime'— plain numeric midpoint(a + b) / 2.'yearmonth'— integer offsetx + 0.5(months/years are 1-indexed integers with unit cell width).'datetime_horizontal'— numeric midpoint on the float-hour y-axis;timedeltamidpoint on thedatetime.datex-axis.
Grids larger than
self.show_values_max_cells(set byplot(), defaultSHOW_VALUES_MAX_CELLS) are skipped with a warning: one text artist per cell is illegible at that size and stays on the axes, so it also slows down every later re-layout of the figure.- Raises:
NotImplementedError – If
self.heatmaptypeis not one of the supported values listed above.
Note
Overlaying values on a full-resolution
HeatmapDateTimewith thousands of cells produces an unreadable result. This method is most useful for coarse grids such asHeatmapYearMonth.
- class diive.plotting.HexbinPlot(x, y, z, gridsize=11, reduce_C_function=<function median>, normalize_axes=False, mincnt=1, extent=None, edgecolors=None, xlabel=None, ylabel=None, zlabel=None, verbose=False)[source]¶
Bases:
HeatmapBaseHexbin scatter plot aggregating z-values into 2D bins of driver variables.
Creates a hexagonal binning plot where flux values (z) are aggregated within bins defined by two driver variables (x, y). This pattern is useful for visualizing high-density scatter data and identifying relationships between drivers and fluxes.
Important: Input Series must have one value per observation (not pre-aggregated). X and Y axes must have no NaN values; Z may contain NaNs (ignored during aggregation).
Example
>>> import diive as dv, pandas as pd, numpy as np >>> ta, vpd, nee = (pd.Series(np.arange(100.), name=n) for n in ('TA', 'VPD', 'NEE')) >>> hm = dv.plotting.HexbinPlot(x=ta, y=vpd, z=nee, gridsize=11, normalize_axes=True) >>> hm.plot(zlabel='Net ecosystem exchange')
See also
examples/visualization/plot_hexbin_basic.py — Hexbin variations (percentile normalization, aggregation, overlay)
- Parameters:
- __init__(x, y, z, gridsize=11, reduce_C_function=<function median>, normalize_axes=False, mincnt=1, extent=None, edgecolors=None, xlabel=None, ylabel=None, zlabel=None, verbose=False)[source]¶
Prepare 2D scatter data for hexbin plotting (Phase 1 of two-phase design).
- Parameters:
x – pandas Series with driver variable (x-axis). Must have no NaN values
y – pandas Series with driver variable (y-axis). Must have no NaN values
z – pandas Series with flux values to aggregate (color scale). NaNs ignored. x, y and z are paired on their index; three Series carrying the same labels in a different order are re-aligned, not zipped by position. Identical indexes (the usual case: three columns of one dataframe) are used as they are
gridsize (
int) – Number of hexagons in the x direction (default 11, while matplotlib’s own default is 100)reduce_C_function – Aggregation function for z-values in each hexagon (default np.median). Can be np.mean, np.sum, etc.
normalize_axes (
bool) – If True, convert x/y to percentile ranks (0-100 scale) (default False, use original values)mincnt (
int) – Minimum number of data points a hexagon must hold to be drawn (default 1, i.e. only cells that actually contain data). Must be >= 1: matplotlib’s cutoff islen(values) >= mincnt, somincnt=0passes empty input toreduce_C_functionand is rejected here — see Raisesextent (
tuple) –(xmin, xmax, ymin, ymax)the hexagon grid is built over, in the units of the plotted x/y — percentile ranks whennormalize_axes=True. Default None derives the extent from this dataset’s own x/y range, so two subsets of one record (daytime vs nighttime, before vs after) get different hexagons and cell i is not the same region in both. Pass the same extent to every subset to compare them cell by celledgecolors (
str) – Deprecated, pass it toplot()instead. Hexagon edge color (default ‘none’)xlabel (
str) – Deprecated, pass it toplot()instead. Label for x-axis (auto-inferred from x.name if None)ylabel (
str) – Deprecated, pass it toplot()instead. Label for y-axis (auto-inferred from y.name if None)zlabel (
str) – Deprecated, pass it toplot()instead. Label for colorbar (auto-inferred from z.name if None)verbose (
bool) – Print progress and diagnostic messages (default False)
- Raises:
ValueError – If Series have mismatched lengths or no names
ValueError – If the three indexes differ and do not describe the same records, so aligning them would change the number of observations
ValueError – If x or y contain NaN values
ValueError – If mincnt < 1. An empty cell must render as empty, and no reducer makes
mincnt=0correct:np.sumreturns 0.0 so the empty cell is painted as a measured zero,np.max/np.minraise, andnp.mean/np.medianreturn NaN (dropped by matplotlib anyway) at the cost of one RuntimeWarning per empty cell
See also
plot : Render the hexbin plot with matplotlib styling options
- show_vals_in_plot()[source]¶
Overlay aggregated z-values on hexagon centers.
Extracts the hexagon centers from the plotted hexagons and places text annotations showing aggregated values.
- export_borderless_heatmap(outpath)¶
Exports borderless heatmap images for use as textures or heightmaps in 3-D software.
Generates four 300 dpi PNG files — two greyscale heightmaps (normal and reversed) and two colour textures (
jetnormal and reversed). Each image is rendered without any axes, ticks, labels, or borders so it can be loaded directly into Blender or similar tools.Output filenames follow the pattern
heatmap_{plottype}_{series_name}.pngwhereplottypeis one ofheightmap_bw,heightmap_bw_r,texture_color,texture_color_r.Note
This method is experimental and may change in future versions.
- Parameters:
outpath (
str) – Directory where the PNG files are saved. Created automatically if it does not exist.
- format(ax_xlabel_txt, ax_ylabel_txt, plot, shown_freq=None)¶
Applies title, colorbar, axis labels, tick formatting, and spine styling.
Title logic:
If
format_style.titleis set it is used as-is (""hides the title).Otherwise, if
shown_freqis given, the title is auto-generated as"{series.name} ({shown_freq})".Otherwise no title is shown.
- Parameters:
ax_xlabel_txt (str) – Label for the x-axis.
ax_ylabel_txt (str) – Label for the y-axis.
plot (matplotlib.collections.QuadMesh) – Mesh object returned by
plot_pcolormesh(), used to create the colorbar.shown_freq (
str) – Frequency or aggregation descriptor appended to the auto-generated title (e.g.'30min','mean, MS'). Pass None to omit.
- get_ax()¶
Returns the Matplotlib Axes object where the plot was generated.
- Returns:
The Axes object containing the heatmap.
- Return type:
- get_plot_data()¶
Returns the pivot DataFrame used to plot the heatmap.
This DataFrame contains the reshaped data (self.plotdf) that forms the grid of values for the heatmap.
- Returns:
The DataFrame used for plotting.
- Return type:
- plot_image()¶
Renders
self.x,self.y,self.zas an image (imshow).The same cells as
plot_pcolormesh(), drawn as one image instead of one quad per cell, which makes drawing a large grid many times cheaper (ten years of half-hourly data are 175 000 cells). Only a regular grid can be an image, soxandymust be evenly spaced cell boundaries;datetime.dateboundaries are converted to date numbers and the axis is set up as a date axis, aspcolormeshdoes.On screen the two agree: where one pixel covers several cells, each method shows one of them and they can pick a different one.
- Returns:
The image, or None when the grid is not evenly spaced (nothing is drawn then).
- Return type:
matplotlib.image.AxesImage or None
- plot_pcolormesh(shading=None)¶
Renders
self.x,self.y,self.zas apcolormeshplot.Calls
set_cmap()first to copy the colormap and mask NaN values inzso they are rendered incolor_badinstead of the nearest valid colour. The masked array is passed directly topcolormesh— not the original unmaskedself.z— so missing cells are always visible.- Parameters:
shading (
str) – Shading algorithm passed topcolormesh.'flat'assigns the cell colour from the value at the lower-left corner;'auto'/ None lets matplotlib choose based on whetherx/yare the same length aszor one longer (boundary mode). Defaults to None.- Returns:
The mesh object, which is needed by
format()to attach the colorbar.- Return type:
- static set_cmap(cmap, color_bad, z)¶
Prepares a colormap and masks invalid data values.
The colormap is copied before mutation because calling
set_badon a shared global colormap would affect every other plot that uses the same colormap in the same session (see matplotlib issue #17634).- Parameters:
- Returns:
cmap (matplotlib.colors.Colormap) — deep copy of the requested colormap with the bad-value colour applied.
z (np.ma.MaskedArray) — input array with NaN and ±inf entries masked so
pcolormeshrenders them incolor_bad.
- Return type:
- show()¶
Generates the heatmap plot with defaults and displays the figure.
This method calls the plot method (which should be implemented by subclasses) with all default styling options, then uses self.fig.show() to display the generated Matplotlib figure.
- plot(ax=None, fig=None, figsize=None, figdpi=72, format_style=None, vmin=None, vmax=None, cmap='RdYlBu_r', zlabel=None, xlabel=None, ylabel=None, edgecolors=None, cb_digits_after_comma=2, cb_labelsize=None, cb_extend=None, minticks=None, maxticks=None, color_bad='grey', show_colormap=True, show_less_xticklabels=False, show_values=False, show_values_fontsize=None, show_values_n_dec_places=0, show_values_color='black')[source]¶
Render HexbinPlot with matplotlib styling (Phase 2 of two-phase design).
All styling and presentation parameters go here. Can be called multiple times on the same HexbinPlot object to plot on different axes with different styling.
- Parameters:
ax – Matplotlib axes to plot on. If None, creates a new figure (not shown automatically)
fig – Existing matplotlib Figure. If None and ax is None, creates new figure
figsize (
tuple) – Figure size as (width, height) in inches. Only used when ax is Nonefigdpi (
int) – Figure DPI. Only used when ax is None (default 72)format_style (
FormatStyle) – Shared chrome (title/labels/fonts/ticks/spines/grid) viaFormatStyle. None = heatmap default (no grid, black spines, outward ticks). A passed style replaces that default as a whole. Thexlabel/ylabelbelow are the defaults for the axis labels, andformat_style.xlabel/ylabeloverride them. The colorbar stayscb_*/zlabel-controlled.vmin (
float) – Minimum color value (auto from data if None)vmax (
float) – Maximum color value (auto from data if None)cmap (
str) – Colormap name (default: ‘RdYlBu_r’)zlabel (
str) – Colorbar label (e.g., ‘°C’, ‘µmol m⁻²s⁻¹’). None uses the label from the constructor (z.nameby default)xlabel (
str) – x-axis label. None uses the label from the constructor (x.nameby default)ylabel (
str) – y-axis label. None uses the label from the constructor (y.nameby default)edgecolors (
str) – Hexagon edge color. None uses the constructor value, or ‘none’ (no edges)cb_digits_after_comma (
int) – Decimal places on colorbar labels (default 2), or ‘auto’ to pick them from the data rangecb_labelsize (
float) – Font size for colorbar tick labelscb_extend (
str) – Colorbar extension arrows (‘neither’, ‘both’, ‘min’, ‘max’). Default None derives them fromvmin/vmaxagainst the range of the aggregated hexagon values, which is what the colorbar mapsminticks (
int) – Minimum major ticks per axis. Default None keeps matplotlib’s own tick density, which adapts to the figure sizemaxticks (
int) – Maximum major ticks per axis (counted within the axis view). Default None keeps matplotlib’s own tick densitycolor_bad (
str) – Ignored by hexbin, kept for signature parity with the other heatmaps.ax.hexbindrops every cell whose aggregate is NaN (matplotlib’sgood_idxs = ~np.isnan(accum)), so a hexbin has no bad cells to colour — a missing cell is blank, notcolor_badshow_colormap (
bool) – Whether to show colorbar (default True)show_less_xticklabels (
bool) – Hide every second x-tick label (default False)show_values (
bool) – Overlay numeric values on hexagons (default False)show_values_fontsize (
float) – Font size for value overlay textshow_values_n_dec_places (
int) – Decimal places for value overlay (default 0)show_values_color (
str) – Text color for value overlay (default ‘black’)
- Returns:
None. The plot is drawn on
ax, or on a new figure when ax=None.
- class diive.plotting.HistogramPlot(series=None, method=None, n_bins=None, ignore_fringe_bins=False, s=None)[source]¶
Bases:
objectHistogram plot with optional z-score overlay and peak highlighting.
Visualize data distribution with optional z-score overlay and peak bin highlighting.
- Parameters:
series (
Series) – Series to plot. Missing values (NaN) and infinite values (+inf, -inf) are left out of the bins and the statistics.method – Name of the binning method, shown in the info box. With ‘n_bins’ the box also lists the bin count and the peak bin range. It does not change the binning.
n_bins (
int) – Number of bins for histogram. An int (or None for the matplotlib default) lets the edges follow this series’ own range; a sequence is used as the explicit bin edges. Passing the same sequence to two histograms is how a shared bin grid is pinned, so that bin i means the same interval in both (values outside the sequence are not binned).ignore_fringe_bins (
list) – List of two integers[i, j]: the first i and the last j bins are dropped from the plot. The edges are derived from the full series first, so the bins that remain are the same intervals the untrimmed histogram would have shown, and records falling into a dropped bin are not plotted. Default False (keep all bins).s (Series)
Call plot() to render with styling options (title, labels, display options).
See also
examples/visualization/plot_histogram_basic.py — Histogram variations with z-score overlays
- __init__(series=None, method=None, n_bins=None, ignore_fringe_bins=False, s=None)[source]¶
Set up the histogram. See the class docstring for parameters (
sis a deprecated alias forseries).
- plot(ax=None, format_style=None, highlight_peak=True, show_zscores=True, show_zscore_values=True, show_info=True, show_counts=True, show_title=True, show_kde=False, show_mean=False, show_median=False)[source]¶
Generate histogram plot with optional styling.
Chrome (title, x-label, grid, fonts, colours) comes from a shared
FormatStyleso it matches every other diive plot. The histogram-specific rendering (bar colour, peak highlight, z-score twiny axis, info/counts boxes and their toggles) stays here.- Parameters:
ax – Matplotlib axes (creates new if None)
format_style (
FormatStyle) – AFormatStyledescribing the chrome. When None the diive house style is used. Default title: “{series.name} (between {start_date} and {end_date})”.highlight_peak (
bool) – Highlight the bin with most counts (default: True)show_zscores (
bool) – Show z-score overlay on top axis (default: True)show_zscore_values (
bool) – Display z-score values and corresponding data values (default: True)show_info (
bool) – Show method and peak information text (default: True)show_counts (
bool) – Show count labels on each bar (default: True)show_title (
bool) – Display title (default: True)show_kde (
bool) – Overlay a Gaussian-KDE fit line, scaled to the counts (default: False)show_mean (
bool) – Draw a dashed vertical line at the mean (default: False)show_median (
bool) – Draw a dashed vertical line at the median (default: False)
When
show_kde/show_mean/show_medianare set, their artists are labelled with the numeric values so the shared legend (built byFormatStyle) doubles as a compact stats readout.
- class diive.plotting.RidgeLinePlot(series)[source]¶
Bases:
objectRidgeline plot: one kernel density curve per year, month or week, stacked vertically.
- The densities come from the kernel density estimator in scikit-learn, see here:
See also
examples/visualization/plot_ridgeline_basic.py — Ridge line plots with kernel density estimation
- Parameters:
series (Series)
- __init__(series)[source]¶
Set up a ridgeline plot for series (one stacked density per group/year). See
plot().Missing values (NaN) and infinite values (+inf, -inf) are dropped up front: the kernel density estimator rejects both, so any gappy series would otherwise raise. Dropping here (rather than per group) also means a group left without a single finite value gets no ridge at all, instead of failing at fit time. Without any finite value,
plot()draws one empty axes with the note “no finite values”.- Parameters:
series (Series)
- plot(xlim=None, ylim=None, hspace=-0.5, fig_width=8, fig_height=8, shade_percentile=0.5, show_mean_line=False, fig_dpi=72, showplot=True, ascending=False, how='weekly', kd_kwargs=None, fig=None, format_style=None)[source]¶
Render the ridgeline plot.
Each group (year, month or week) gets one density curve. The curves are coloured from
Spectral_rby the group mean, lowest mean first. The mean is printed at the right end of each curve.- Parameters:
xlim (
list) – X-axis limits[min, max], shared by all curves. None uses the data range.ylim (
list) – Y-axis (density) limits[min, max], shared by all curves. None uses 0 up to the highest density of all groups.hspace (
float) – Vertical space between the curves. Negative values make them overlap (default -0.5).fig_width (
float) – Width of a new figure in inches (default 8).fig_height (
float) – Height of a new figure in inches (default 8).shade_percentile (
float) – Quantile (0 to 1) of each group’s values. The area above it is shaded slightly darker (default 0.5, the median).show_mean_line (
bool) – Draw a vertical line at each group’s mean (default False).fig_dpi (
float) – DPI of a new figure (default 72).showplot (
bool) – Show the figure (default True).ascending (
bool) – Order of the groups from top to bottom. False (default) puts the highest group label (e.g. the latest year) at the top.how (
str) – Grouping:'yearly','monthly'or'weekly'(ISO week, default).kd_kwargs (
dict) – Keyword arguments for scikit-learn’sKernelDensity, e.g.{'bandwidth': 0.5, 'kernel': 'gaussian'}. None uses its defaults (Gaussian kernel, bandwidth 1.0).fig – Existing matplotlib
Figureto draw into (cleared first). When given, the plot builds its stacked-density grid on it instead of creating a new figure – e.g. for embedding in a GUI canvas. Thefig_width/fig_height/fig_dpiargs are then ignored. Passshowplot=Falsewith this.format_style (
FormatStyle) – AFormatStyledescribing the shared chrome. Only the parts that fit this stacked-density layout are honoured here: the bottom x-axis label (text/units, font, colour) and the figure title (text, font, colour). The per-ridge grid, spines, ticks and shading stay fixed.
- class diive.plotting.ShiftedDistributionPlot(series, ref_period, comp_period, zone_labels=None, zone_colors=None, verbose=False)[source]¶
Bases:
objectShifted distribution plot comparing two time periods.
Shows how a variable’s distribution has shifted between a reference period (gray hatched outline) and a comparison period (color-coded zones). Zone boundaries are computed from the reference period’s mean and standard deviation: cold/hot at ±1σ, extremely cold/hot at ±3σ.
- Parameters:
series (
Series) – Time-indexed Series with the variable to plot.ref_period (
tuple) – (start, end) date strings for the reference period.comp_period (
tuple) – (start, end) date strings for the comparison period.verbose (
bool) – Print the per-period report (sample size, mean, sd, retained fraction, zone breakpoints) on construction (default False). Records lost to missing values are warned about either way.zone_labels (list)
zone_colors (list)
Missing values are dropped per period before the density is fitted. How many each period lost is kept in the
n_*attributes, warned about when it is not zero, and stated on the figure itself:plot()appends the sample size to both legend labels, asn = 201 of 4018when records were dropped andn = 4018when none were. Without that a reference period that is 95% gaps draws a curve indistinguishable from a complete one — and its mean and sd set the zone breakpoints.Call plot() to render with styling options (including
zone_labelsandzone_colors).- Variables:
n_comp_records (n_ref_records /) – Records the period holds, gaps included.
n_comp_used (n_ref_used /) – Records the density (and, for the reference, the zone breakpoints) is built from.
n_comp_missing (n_ref_missing /) – Records the period lost to missing values.
- Parameters:
See also
examples/visualization/plot_shifted_distribution.py
- __init__(series, ref_period, comp_period, zone_labels=None, zone_colors=None, verbose=False)[source]¶
Fit the reference/comparison KDEs and zone breakpoints. See the class docstring for parameters (
zone_labels/zone_colorshere are deprecated — pass them toplot()).
- report()[source]¶
Print a Rich table of both periods’ sample size, mean and sd, plus the zone breakpoints.
- plot(ax=None, format_style=None, ref_label=None, comp_label=None, show_legend=True, show_title=True, show_xaxis=True, show_yaxis=True, figsize=(16, 7), zone_labels=None, zone_colors=None)[source]¶
Render the shifted distribution plot.
- Parameters:
ax – Matplotlib axes (creates new figure if None).
format_style (
FormatStyle) – AFormatStyledescribing the chrome (axis labels/font sizes/colours/ticks/grid). When None the diive house style is used with the grid off. PassFormatStyle(show_grid=True)to draw it. The y-label defaults to"Density". The title and the legend keep this plot’s own left-aligned placement, so thelegend_loc/legend_ncolfields of the style do not apply.ref_label (
str) – Legend label for reference period.comp_label (
str) – Legend label for comparison period. Both labels get the period’s sample size appended —n = 4018, orn = 201 of 4018when records were dropped as missing. This also applies to a caller-supplied label: the count is what tells a reader whether the curve rests on a full period or on a handful of records, and it must stay on the figure whoever names the periods. A period holding nothing keeps its: no datalabel instead.show_legend (
bool) – Show legend (default True).show_title (
bool) – Show title (default True).show_xaxis (
bool) – Show x-axis spine, ticks, and tick labels (default True).show_yaxis (
bool) – Show y-axis spine, ticks, and tick labels (default True).figsize (
tuple) – Figure size when ax is None.zone_labels (
list) – Exactly 5 zone labels from lowest to highest. Defaults to temperature labels. Any other length raisesValueError.zone_colors (
list) – Exactly 5 fill colors for the zones (lowest to highest).
Calling this again on the same axes replaces the previous rendering; calling it on a different axes leaves the earlier one drawn.
- class diive.plotting.ScatterXY(x, y, z=None, nbins=0, binagg='median')[source]¶
Bases:
objectScatter plot of x vs y with optional z colour-coding and bin aggregation. See
__init__().- __init__(x, y, z=None, nbins=0, binagg='median')[source]¶
Scatter plot with optional third variable as color and bin aggregation.
Visualize relationships between two variables (x, y) with optional color-coding by a third variable (z). Supports optional binning and aggregation for trend visualization with confidence intervals (median ± IQR or mean ± std).
- Parameters:
x (
Series) – Series for x-axisy (
Series) – Series for y-axisz (
Series) – Optional Series for color-coding scatter pointsnbins (
int) – Number of x-axis bins for aggregation (0 = no aggregation). The bins are quantiles of x, so each holds about the same number of points.binagg (
Literal['mean','median']) – Aggregation method for bins (‘mean’ or ‘median’, default: ‘median’)
- Features:
2-variable scatter: Basic x vs y plot
3-variable scatter: Color-code points by z variable with colorbar
Bin aggregation: Group data by x-axis bins and overlay trends
Confidence intervals: Show IQR (median) or std (mean) per bin
Call plot() to render it (limits, colormap, markers, with labels and title via
format_style).- Artists:
The points are the first PathCollection in
ax.collections, asax.scatterreturns it. Withoutzthe collection is a PathCollection subclass that draws all markers from one cached marker, which is much faster for large records; each marker then sits on the nearest pixel centre, up to half a pixel from its exact position. Withzit is a PathCollection subclass that, in raster output, leaves out the markers that opaque markers drawn after them cover completely; the image is unchanged.
See also
examples/visualization/plot_scatter_xy_basic.py — Scatter plot variations with 2D and 3D coloring
- plot(ax=None, format_style=None, xlim=None, ylim=None, cmap='viridis', show_colorbar=True, markersize=40, alpha=1.0, vmin=None, vmax=None)[source]¶
Generate plot with optional styling and formatting.
Renders scatter plot with all styling parameters. Can be called multiple times with different parameters/axes to explore different views of the same data.
Chrome (title, labels, units, font sizes, colours, grid, legend, zero line) comes from a shared
FormatStyleso it looks and is configured the same way as every other diive plot. The data-rendering arguments (cmap/markersize/alpha/vmin/vmax/colorbar, axis limits) stay here.- Parameters:
ax (
Axes) – Matplotlib axes to plot on (default: creates new figure if None)format_style (
FormatStyle) – AFormatStyledescribing the chrome (title/xlabel/ylabel/zlabel/xunits/yunits). When None the diive house style is used. The colorbar label reads fromformat_style.zlabel.xlim (
list) – X-axis limits as [min, max] (default: data min/max)ylim (
list) – Y-axis limits as [min, max] or ‘auto’ (default: data range)cmap (
str) – Colormap name for z variable (default: ‘viridis’) Examples: ‘plasma’, ‘viridis’, ‘coolwarm’, ‘RdYlBu’show_colorbar (
bool) – Display colorbar if z provided (default: True)markersize (
float) – Scatter point area in points^2 (default: 40)alpha (
float) – Scatter point opacity, 0-1 (default: 1.0)vmin (
float) – Lower bound of the z colour scale (default: data minimum)vmax (
float) – Upper bound of the z colour scale (default: data maximum)
Notes
Without xlim the x-axis spans the full data range (no quantile trimming)
ylim=’auto’ with nbins: uses binned data limits (IQR for median, ±1 SD for mean). Without bins it uses the 1st to 99th percentile of y.
Colorbar shown only if z is provided and show_colorbar=True
- class diive.plotting.DateTimeSurface(x_hours, y_days, z, dates, name)[source]¶
Bases:
objectNumeric grid of a time series as date x time-of-day.
- Variables:
x_hours (
ndarray) – 1-D float array of time-of-day in hours since midnight (e.g. 0.5 for 00:30), one entry per time-of-day column. Length T.y_days (
ndarray) – 1-D float array of days since the first date, one entry per date row. Length D. (Numeric so a 3-D backend can use it as a real axis; map back to calendar dates withdates.)z (
ndarray) – 2-D value array of shape (D, T); NaN where a timestamp is missing.dates (
ndarray) – 1-D array ofdatetime.datefor the D rows (for axis ticks).name (
str) – Name of the source series.
- Parameters:
- diive.plotting.datetime_surface_grid(series)[source]¶
Pivot a time series into a date x time-of-day value grid.
The index is sanitized (sorted, de-duplicated, regularised to a complete frequency grid) so the pivot forms a full rectangle — every date row has the same set of time-of-day columns, with NaN for missing records. It is then converted to the
TIMESTAMP_STARTconvention. This is the same preparation the 2-D heatmap uses (_setup_timestamp()), exposed as plain arrays for 3-D rendering: the surface and the heatmap of the same series therefore share cell for cell.- Parameters:
series (
Series) – Pandas Series with a diive-convention datetime index (TIMESTAMP_START/_MIDDLE/_END). Any sub-daily resolution is supported.- Return type:
- Returns:
A
DateTimeSurfacewith the numeric grid and date labels.
- class diive.plotting.TimeSeries(series, drop_gaps=False, color_series=None)[source]¶
Bases:
objectCreate time series plots with matplotlib (static) or Bokeh (interactive).
Two-phase design: separate data preparation (__init__) from rendering (plot). Phase 1 creates the plotter with data; Phase 2 renders with styling options.
- Methods:
plot – Render static matplotlib plot with styling options
plot_interactive – Render interactive Bokeh plot with zoom, pan, selection tools
plot_rangetool – Render interactive Bokeh plot with a RangeTool overview panel
- Parameters:
Example
See examples/visualization/plot_timeseries.py for matplotlib examples. See examples/visualization/plot_timeseries_interactive.py for Bokeh examples. See examples/visualization/plot_timeseries_rangetool.py for the RangeTool overview.
- __init__(series, drop_gaps=False, color_series=None)[source]¶
Prepare time series data for plotting.
- Parameters:
series (
Series) – Data to plot (pandas Series with datetime index)drop_gaps (
bool) – If True, drop missing values before plotting. Default False so gaps remain visible — matplotlib and Bokeh break the line at NaNs rather than drawing a continuous line across missing periods, which would misrepresent data coverage.color_series (
Series) – Optional second series whose values colour the line (and markers) via a colormap instead of a single colour — e.g. colour a flux line by air temperature. Aligned to series’ index; segments are coloured by the mean of their endpoints’ values; a segment whose colour value is missing is drawn in a neutral grey, since the data itself was measured. When given, plot()’s cmap/color_vmin/ color_vmax/show_colorbar/color_label apply and the scalar color argument is ignored — unless alignment leaves fewer than two colour values, in which case plot() warns and falls back to a plain line drawn in color.
See also
plot : Render the time series with matplotlib styling options
- plot_interactive(height=600, width=1200, save_to_file=False, showplot=True)[source]¶
Render interactive time series plot using Bokeh.
Provides interactive tools for data exploration: hover tooltips, zoom, pan, selection, and export. Useful for exploring large time series datasets.
- Parameters:
height (
int) – Plot height in pixels (default: 600)width (
int) – Plot width in pixels (default: 1200)save_to_file (
bool) – Save plot to HTML file (default: False, display in browser only)showplot (
bool) – Open the plot in a browser (default: True). Set False to build the figure without displaying it, e.g. to embed it in a Bokeh layout or to write it out yourself. Note that the HTML file is written by the display step, so save_to_file=True, showplot=False writes nothing.
- Tools Available:
Hover: Display date and value on mouse over
Box Zoom: Click and drag to zoom to region
Reset: Reset to original view
Pan: Click and drag to move across plot
Box Select: Select points in a region
Wheel Zoom: Scroll to zoom in/out
Undo/Redo: Undo and redo zoom/pan operations
Save: Export plot as PNG image
- Returns:
The Bokeh figure, so it can be embedded or saved by the caller.
- Parameters:
Example
>>> import diive as dv, pandas as pd >>> idx = pd.date_range('2024-06-01', periods=3, freq='30min') >>> ts = dv.plotting.TimeSeries(series=pd.Series([1.0, 2.0, 1.5], index=idx, name='TA')) >>> ts.plot_interactive(height=800, width=1600) # opens a browser tab
- plot_rangetool(height=300, width=900, overview_height=130, init_range=0.25, save_to_file=False, showplot=True)[source]¶
Render an interactive Bokeh plot with a RangeTool overview.
Two linked panels: a detail plot (top) showing a slice of the series, and a smaller overview plot (bottom) showing the full series with a draggable RangeTool. Drag or resize the shaded selection on the overview to pan and zoom the detail plot. The detail panel’s y-axis auto-scales to the data in the visible x-window, so the curve always fills the panel. Useful for navigating long time series without losing the overall context.
See https://docs.bokeh.org/en/latest/docs/examples/interaction/tools/range_tool.html
- Parameters:
height (
int) – Detail-panel height in pixels (default: 300).width (
int) – Plot width in pixels (default: 900).overview_height (
int) – Overview-panel height in pixels (default: 130).init_range (
float) – Fraction of the series shown in the detail panel initially, measured from the start (default: 0.25 = first quarter).save_to_file (
bool) – Save to a named HTML file instead of a temp file (default: False, opens in browser only).showplot (
bool) – Open the plot in a browser (default: True). Set False to build the layout without displaying it, e.g. to embed it or to write it out yourself. Note that the HTML file is written by the display step, so save_to_file=True, showplot=False writes nothing.
- Returns:
The Bokeh column(detail, overview) layout, so it can be embedded or saved by the caller.
Example
>>> import diive as dv, pandas as pd >>> idx = pd.date_range('2024-06-01', periods=3, freq='30min') >>> ts = dv.plotting.TimeSeries(series=pd.Series([1.0, 2.0, 1.5], index=idx, name='TA')) >>> ts.plot_rangetool(init_range=0.1) # opens a browser tab, zoomed to the first 10%
- plot(ax=None, format_style=None, color=None, linewidth=1.2, alpha=0.95, marker=False, markersize=3, cmap='viridis', color_vmin=None, color_vmax=None, show_colorbar=True, color_label=None, show_stats=None)[source]¶
Render time series plot with matplotlib styling (Phase 2 of two-phase design).
Chrome (title, labels, units, font sizes, colours, grid, legend) comes from a shared
FormatStyleso it looks and is configured the same way as every other diive plot. The data-rendering arguments (color/linewidth/alpha/marker/markersize) are specific to the line itself and stay here. Can be called multiple times on the same object to draw on different axes with different styling.Without a
format_stylethe plot uses the default look: white background, left and bottom spines only, outward ticks, light horizontal gridlines, a left-aligned title, concise date labels with the year at the end of the axis, a light zero line when the data cross zero, and no legend (the title names the series). A givenformat_stylesets the chrome instead, soFormatStyle()gives the diive house style.Drawing is additive: a second call on the same axes appends its line to whatever is already there rather than replacing it, and with a color_series it appends a second colorbar, which shrinks the main axes. That is what makes overlaying several series on one axes work; to re-draw instead of overlay, clear the axes first (ax.clear()) or pass a fresh one.
- Parameters:
ax – Matplotlib axes to plot on. If None, creates a new figure and displays it. Existing artists and any limits the caller set are kept — the series is drawn on top and the view grows to fit both.
format_style (
FormatStyle) – AFormatStyledescribing the chrome (title, labels, units, fonts, colours, grid, legend). When None the default look described above is used.color (
str) – Line color (default: Material Design blue #2196F3). Ignored when a color_series was given (the line is then colormap-coloured) — except when that series aligns to fewer than two values, where the plot falls back to a plain line in this colour and warns.linewidth (
float) – Line width in points (default: 1.2).alpha (
float) – Line/marker opacity, 0-1 (default: 0.95).marker (
bool) – If True, draw a point marker at each observation (default: False).markersize (
float) – Point marker size in points, used only when marker=True (default: 3).cmap (
str) – Colormap used when a color_series was given (default: ‘viridis’).color_vmin (
float) – Lower bound of the colour scale (default: the color_series min).color_vmax (
float) – Upper bound of the colour scale (default: the color_series max).show_colorbar (
bool) – Draw a colorbar for the colour-by series (default: True).color_label (
str) – Colorbar label (default: the color_series name).show_stats (
bool) – Write two lines above the axes: the time resolution of the records, the period, the number of values and the share of missing values, then mean, median, SD, min and max. Infinite values are counted on the first line and left out of the statistics. The time resolution is detected from the timestamps, also where it changes. None (default) shows them on a figure the plot creates itself (ax=None) and leaves them out on a given axes, where several series may be overlaid.
- Returns:
The matplotlib axes the series was drawn on (the new axes when ax=None), so callers can apply further styling.
Example
>>> import diive as dv, pandas as pd, matplotlib.pyplot as plt >>> idx = pd.date_range('2024-06-01', periods=3, freq='30min') >>> ts = dv.plotting.TimeSeries(series=pd.Series([1.0, 2.0, 1.5], index=idx, name='TA')) >>> ax = ts.plot(ax=plt.subplots()[1], format_style=dv.plotting.FormatStyle(yunits='(°C)'))
- class diive.plotting.TreeRingPlot(df, value_col, resample_freq='D', verbose=False)[source]¶
Bases:
objectCircular spiral visualization of annual time series as concentric color-coded rings.
Creates a polar plot where each year forms an annular ring. Color encodes a numeric value (e.g., temperature anomaly). Months are placed around the circle with January at the bottom (6 o’clock) and July at the top (12 o’clock), so the annual temperature cycle reads intuitively: cold winters at the bottom, warm summers at the top.
Inner rings correspond to the earliest years in the data; outer rings to the most recent, giving a tree-ring-like growth pattern that shows trends at a glance.
Example
>>> import diive as dv, pandas as pd, numpy as np >>> idx = pd.date_range('2020-01-01', periods=1096, freq='D') >>> tr = dv.plotting.TreeRingPlot(pd.DataFrame({'TA': np.arange(1096.)}, index=idx), 'TA') >>> tr.plot(cmap='RdBu_r', vmin=-20, vmax=20, cb_label='Air temperature (deg C)')
See also
examples/visualization/plot_treering_temperature.py
- __init__(df, value_col, resample_freq='D', verbose=False)[source]¶
Prepare time series data for tree-ring plotting (Phase 1 of two-phase design).
- Parameters:
df (
DataFrame) – DataFrame with DatetimeIndex at any sub-annual frequencyvalue_col (
str) – Column name with the numeric values to visualizeresample_freq (
str) – Pandas offset alias controlling angular resolution of each ring.'D'(default) resamples to daily means (366 slots per ring). Finer aliases such as'h'or'30min'preserve more detail at the cost of more slots. PassNoneto use the raw data as-is; the slot count is then inferred from the median time step.verbose (
bool) – Print progress messages (default False)
- Raises:
ValueError – If df does not have a DatetimeIndex or is empty
KeyError – If value_col is not found in df
- plot(ax=None, format_style=None, figsize=(10, 10), figdpi=100, cmap='RdBu_r', vmin=None, vmax=None, show_month_labels=True, show_month_lines=False, show_year_labels=True, show_year_separators=True, year_label_frequency=10, cb_label=None, cb_labelsize=None, cb_digits_after_comma=1, month_label_fontsize=None, year_label_fontsize=None)[source]¶
Render TreeRingPlot on a polar axis (Phase 2 of two-phase design).
All styling and presentation parameters live here. Can be called multiple times on the same object to produce differently styled outputs.
- Parameters:
ax – Polar matplotlib axes. If None, a new figure is created
format_style (
FormatStyle) – AFormatStylefor the shared chrome. Only itstitle/ title font fields apply here (this is a polar plot, so the cartesian spines/ticks/grid ofFormatStyle.applydo not).figsize (
tuple) – Figure size in inches (default (10, 10))figdpi (
int) – Figure DPI (default 100)cmap (
str) – Colormap name (default ‘RdBu_r’, blue=low, red=high)vmin (
float) – Minimum color scale value. If the data contains values below vmin, the colorbar is extended with a downward arrow automatically. Defaults to data minimum.vmax (
float) – Maximum color scale value. If the data contains values above vmax, the colorbar is extended with an upward arrow automatically. Defaults to data maximum.show_month_labels (
bool) – Show month abbreviations around the outer ring (default True)show_month_lines (
bool) – Draw thin radial lines at each month boundary (default False)show_year_labels (
bool) – Show year numbers on rings (default True)show_year_separators (
bool) – Draw thin white circles between year rings (default True)year_label_frequency (
int) – Interval between year labels, e.g. 10 = every decade (default 10). The first and last year are always labelled.cb_label (
str) – Colorbar label textcb_labelsize (
float) – Font size for colorbar tick labelscb_digits_after_comma (
int) – Decimal places on colorbar tick labels (default 1)month_label_fontsize (
float) – Font size for month labels (default theme value)year_label_fontsize (
float) – Font size for year labels (default theme value)
- plot_line(ax=None, format_style=None, figsize=(10, 10), figdpi=100, vmin=None, vmax=None, cmap='RdYlBu_r', linewidth=1.2, alpha=0.85, amplitude_scale=0.5, ring_width=0.35, show_month_labels=True, show_month_lines=False, show_year_labels=False, show_year_separators=False, year_label_frequency=1, cb_label=None, cb_labelsize=None, cb_digits_after_comma=1, month_label_fontsize=None, year_label_fontsize=None)[source]¶
Render TreeRingPlot as concentric radial line traces colored by data value.
Each year traces its own ring at a fixed base radius (oldest at center, newest at the outer edge). Within each ring the line wiggles radially by
amplitude_scalearound the base, encoding the data value. Segment color also encodes the data value viacmap, so both position and color carry the same information — matching the reference spiral-plot style.All styling and presentation parameters live here. Can be called multiple times on the same object to produce differently styled outputs.
- Parameters:
ax – Polar matplotlib axes. If None, a new figure is created.
format_style (
FormatStyle) – AFormatStylefor the shared chrome. Only itstitle/ title font fields apply here (this is a polar plot, so the cartesian spines/ticks/grid ofFormatStyle.applydo not).figsize (
tuple) – Figure size in inches (default (10, 10))figdpi (
int) – Figure DPI (default 100)vmin (
float) – Low colour anchor (defaults to data minimum).vmax (
float) – High colour anchor (defaults to data maximum).cmap (
str) – Colormap applied to data values (default ‘RdYlBu_r’, blue=low, red=high).linewidth (
float) – Line width in points (default 1.2)alpha (
float) – Line opacity (default 0.85)amplitude_scale (
float) – Maximum radial displacement as a fraction of one ring width. 0.5 makes lines reach ring boundaries; >0.5 causes overlap (default 0.5).ring_width (
float) – Radial width of each year’s ring in data units (default 0.35). Smaller values pack rings closer together.show_month_labels (
bool) – Show month abbreviations outside the outer ring (default True)show_month_lines (
bool) – Draw thin radial spokes at each month boundary (default False)show_year_labels (
bool) – Show year numbers at each ring’s midpoint (default False)show_year_separators (
bool) – Draw faint circles between year rings (default False)year_label_frequency (
int) – Interval between year labels, e.g. 1 = every year (default 1). The first and last year are always labelled.cb_label (
str) – Colorbar label textcb_labelsize (
float) – Font size for colorbar tick labelscb_digits_after_comma (
int) – Decimal places on colorbar tick labels (default 1)month_label_fontsize (
float) – Font size for month labels (default theme value)year_label_fontsize (
float) – Font size for year labels (default theme value)
- class diive.plotting.WaterfallPlot(series, series_units=None, resample='D', agg='sum', uptake_is_negative=True)[source]¶
Bases:
objectPlot a financial-style waterfall chart of sequential contributions to a running total.
Each period is drawn as a floating bar starting where the previous period’s running total ended, so the cumulative sum builds up across the series. Bars are colored by sign (e.g. CO2 uptake vs. release), with thin connector lines between consecutive bars and the final running total annotated.
Designed for daily CO2 flux budgets: pass the flux at its native resolution (e.g. half-hourly NEE) and it aggregates to one bar per period internally.
Two-phase design: data preparation (__init__) is separate from rendering (plot).
- Parameters:
series (
Series) – Flux time series with a datetime index. Aggregated to one value per period internally (see resample).series_units (
str) – Units string for the y-axis (e.g. r’($mathrm{gCm^{-2}}$)’). LaTeX is supported.resample (
str) – Pandas offset alias to aggregate the series before plotting (default ‘D’ for daily). Set to None to plot the series as-is, e.g. when it is already aggregated to one value per period.agg (
str) – Aggregation function passed to the resampler (default ‘sum’).uptake_is_negative (
bool) – Sign convention for coloring. With the default True (NEE convention), negative values are treated as uptake (sink) and colored blue, positive values as release (source) and colored red. Set to False when the data is sign-flipped so positive means uptake. A contribution of exactly 0.0 is neither uptake nor release and takes the release color under both conventions, which is never seen: the bar has zero height, so such a period shows only the flat connector. This is common for a variable that is genuinely zero for whole periods (1820 of 3649 daily bars for bundled CH-DAV precipitation).
- Methods:
plot – Render the waterfall chart with styling options
get – Return the axis
See also
examples/visualization/plot_waterfall.py — Daily CO2 uptake waterfall
- __init__(series, series_units=None, resample='D', agg='sum', uptake_is_negative=True)[source]¶
Aggregate the series and compute the running totals. See the class docstring for parameters.
- plot(ax=None, format_style=None, showplot=True, digits_after_comma=0, color_uptake='#2196F3', color_release='#F44336', bar_width=None, show_connectors=True)[source]¶
Render the waterfall chart (Phase 2 of the two-phase design).
Chrome (title, labels, units, font sizes, colours, grid, legend, zero line) comes from a shared
FormatStyle, so it looks and is configured like every other diive plot. The bar/connector/annotation rendering arguments stay here.- Parameters:
ax – Matplotlib axes to plot on. If None, a new figure is created and shown.
format_style (
FormatStyle) – AFormatStyledescribing the chrome. When None the diive house style is used. Theseries_unitsgiven to the constructor, when set, overrideformat_style.yunits.showplot (
bool) – Show the figure (only when this object created the figure).digits_after_comma (
int) – Decimals for the final-total annotation.color_uptake (
str) – Bar color for uptake (sink) periods.color_release (
str) – Bar color for release (source) periods, and for a contribution of exactly 0.0 (seeuptake_is_negative).bar_width (
float) – Bar width in days. Defaults to ~80% of the median spacing between periods.show_connectors (
bool) – Draw thin lines linking consecutive bars.
- Returns:
The matplotlib axis. The bars are one
PolyCollection(gid'waterfall_bars') and the connectors oneLineCollection(gid'waterfall_connectors'), both inax.collections.
- class diive.plotting.WindRosePlot(series, wind_dir, agg='mean', n_sectors=8, z=None, z_agg=None, verbose=False)[source]¶
Bases:
objectAggregate a variable into wind-direction sectors and draw it as a polar bar plot.
Bins wind direction into
n_sectorsequal compass sectors (North-centred, so the North sector straddles 0/360 degrees) and reduces the paired variable within each sector byagg. The result is a tidy per-sector table (results) and a wind-rose-style polar bar plot where each bar’s length is the sector’s aggregated value.Two-phase design: data + aggregation parameters go to
__init__; all styling lives inplot(), which can be called repeatedly with different looks.- Parameters:
series (
Series) – Variable to aggregate (numeric Series).wind_dir (
Series) – Wind direction in degrees (0-360), aligned toseriesby index. Readings outside that range (fill values such as -9999, a signed -180 to 180 convention, an un-wrapped offset) are dropped rather than wrapped, and the number dropped is warned about and kept inn_out_of_range.agg (
str) – Aggregation applied per sector — one of'mean','median','min','max','sum'(cumulative),'std','count'. Drives the plotted radius; the full table always holds every statistic.n_sectors (
int) – Number of equal wind-direction sectors (default 8). 4, 8 and 16 get compass labels (N, NE, …); other counts are labelled by degrees.z (
Series) – Optional second variable used to colour the bars. When given, it is aggregated per sector (over its own valid records) and drives the bar colours + colorbar, while the bar lengths still come fromseries. When omitted, bars are coloured by their own aggregated value.z_agg (
str) – Aggregation forz(same choices asagg); defaults toagg.verbose (
bool) – Emit the Rich per-sector report on construction (default False).
- Variables:
results – Per-sector
DataFrameindexed by sector label, with columnsCENTER_DEG,N_VALS,MEAN,MEDIAN,MIN,MAX,STD,SUM(plusZwhen a colour variable is given).n_used – Records that reached the sectors (both variables present, direction on the circle).
n_out_of_range – Records lost because their wind direction was off the circle.
Example
>>> import diive as dv, pandas as pd, numpy as np >>> flux = pd.Series(np.sin(np.arange(360.)), name='co2_flux') >>> rose = dv.plotting.WindRosePlot(series=flux, wind_dir=pd.Series(np.arange(360.)), ... agg='mean', n_sectors=16) >>> ax = rose.plot(cmap='RdBu_r', cb_label='Mean CO2 flux') # then rose.results
See also
examples/visualization/plot_windrose_basic.py
- plot(ax=None, format_style=None, figsize=(9, 9), figdpi=100, cmap='viridis', color=None, vmin=None, vmax=None, alpha=0.9, edgecolor='white', edgewidth=0.8, bar_width_frac=0.9, show_colorbar=True, show_sector_labels=True, max_sector_labels=16, show_zero_circle=True, cb_label=None, cb_labelsize=None, cb_digits_after_comma=None, sector_label_fontsize=None, sector_label_pad=14.0)[source]¶
Render the wind rose on a polar axis (Phase 2 of the two-phase design).
- Parameters:
ax – Polar matplotlib axes. If None, a new polar figure is created and the title goes on the figure. With a given axes the title goes on that axes, not on the figure, so the rose can be one panel of a caller’s multi-panel figure.
format_style (
FormatStyle) – SharedFormatStyle. This is a polar plot, so only the fields that describe something the rose actually draws are honoured:title(+title_fontsize,title_fontweight,text_color),ticks_fontsize(compass and radial tick labels, whensector_label_fontsizeis not given),chrome_color(tick labels + tick marks),show_grid,grid_colorandfacecolor. Deliberately ignored: the axis-label fields (xlabel/ylabel/xunits/yunits/axlabel_*) — the angular axis is the compass and the radial axis is labelled by the colorbar;zlabel— the colorbar label has its owncb_labelargument here; the legend fields — the rose draws no labelled artists;show_zeroline— the polar equivalent isshow_zero_circle; and the spine/tick geometry fields (spine_linewidth,ticks_direction,ticks_length,ticks_width), which describe cartesian spines a polar axes does not have.figsize (
tuple) – Figure size in inches (default (9, 9)).figdpi (
int) – Figure DPI (default 100).cmap (
str) – Colormap used to colour bars by the colour source — thezaggregate when one was given, else the bar value (default'viridis'). Ignored whencoloris given.color (
str) – Single solid bar colour. When set, overridescmapand the colorbar is suppressed.vmin (
float) – Low colour anchor (defaults to the colour source’s minimum).vmax (
float) – High colour anchor (defaults to the colour source’s maximum).alpha (
float) – Bar opacity (default 0.9).edgecolor (
str) – Bar edge colour (default ‘white’).edgewidth (
float) – Bar edge line width (default 0.8).bar_width_frac (
float) – Bar angular width as a fraction of the sector width (default 0.9; 1.0 = touching bars, lower = gaps between sectors).show_colorbar (
bool) – Draw the value colorbar (default True; ignored withcolor).show_sector_labels (
bool) – Draw compass / degree labels around the rose (default True).max_sector_labels (
int) – Maximum number of per-sector labels before switching to a fixed ring of compass bearings (default 16). With more sectors than this, 16 (or 8) cardinal compass points are shown instead of one crowded label per sector.show_zero_circle (
bool) – Draw a reference circle at value 0 when the aggregate spans negative values (default True).cb_label (
str) – Colorbar label (defaults to “{z_agg} {z_varname}” when a colour variable is given, else “{agg} {varname}”).cb_labelsize (
float) – Colorbar tick/label font size (default theme value).cb_digits_after_comma (
int) – Decimal places on colorbar ticks. Default None auto-picks the fewest decimals the tick values need (integer labels when they suffice); pass an int to force a fixed count.sector_label_fontsize (
float) – Compass-label font size (default theme value).sector_label_pad (
float) – Radial gap (points) between the outer ring and the compass labels (default 14), so labels clear the plotting area.
- Returns:
The polar matplotlib axes the rose was drawn on.