FILE: docs/api/matplotlib.md¶
Matplotlib API Reference¶
Functions for streamlined plotting: context manager, subplot grids, bar annotations, and consistent colours.
quickplot(figsize=(10, 6), title=None, save=None, dpi=150, show=True, style=None)¶
Context manager that creates a figure and axes, then cleans up automatically.
Parameters:
- figsize – (width, height) in inches
- title – optional figure title
- save – file path to save the figure (None = don't save)
- dpi – resolution for saved figure
- show – call plt.show() on exit
- style – matplotlib style (e.g., 'seaborn-v0_8-whitegrid')
Returns: Context manager yielding matplotlib Axes
Example:
with dk.quickplot(figsize=(10, 5), title='My Plot', save='plot.png') as ax:
ax.plot(x, y)
ax.set_xlabel('X')
ax.set_ylabel('Y')
plot_grid(plot_fns, n_cols=2, figsize='auto', titles=None, sharey=False, sharex=False, show=True, save=None, dpi=150)¶
Create a grid of subplots from a list of plotting functions.
Parameters:
- plot_fns – list of functions, each taking an ax argument
- n_cols – number of columns in the grid
- figsize – tuple or 'auto' (auto = (n_cols*6, n_rows*4))
- titles – list of titles for each subplot
- sharey – share y‑axis across subplots
- sharex – share x‑axis across subplots
- show – call plt.show()
- save – file path to save figure
- dpi – resolution for saved figure
Returns: (fig, axes) where axes is a 1D numpy array of Axes objects
Example:
def plot1(ax): ax.plot(x, y1)
def plot2(ax): ax.scatter(x, y2)
fns = [plot1, plot2]
dk.plot_grid(fns, n_cols=2, titles=['Line', 'Scatter'])
annotate_bars(ax, fmt='.1f', offset=3, fontsize=9, color=None, ha='center', va='bottom')¶
Add value labels to every bar in a bar chart.
Parameters:
- ax – matplotlib Axes containing the bars
- fmt – format string (e.g., '.1f')
- offset – pixel offset from bar top/right
- fontsize – label font size
- color – label colour (None = default)
- ha – horizontal alignment
- va – vertical alignment
Returns: ax (same axes, for chaining)
Example:
ax = sns.barplot(data=df, x='cat', y='value')
dk.annotate_bars(ax, fmt='.0f', offset=5)
ColorRegistry(palette='tab10')¶
Class that assigns consistent colours to category values across multiple plots.
Methods:
- get(value) – returns colour for a value (assigns new colour if unseen)
- get_mapping(values) – returns dict {value: color} for a list of values
- reset() – clears all assignments
- set_palette(palette) – changes the colour palette and resets
Example:
colors = dk.ColorRegistry(palette='Set2')
ax1.bar(cats, vals1, color=[colors.get(c) for c in cats])
ax2.bar(cats, vals2, color=[colors.get(c) for c in cats]) # same colours