API Reference#

Top-level functions#

memeplotlib.meme(template, *lines, font=<object object>, color=<object object>, outline_color=<object object>, outline_width=<object object>, fontsize=<object object>, style=<object object>, backend=None, extension=None, width=None, height=None, layout=None, background=None, overlays=None, template_style=None, alt_text=None, show=False, savefig=None, figsize=None, dpi=None, ax=None, **text_kwargs)[source]#

Create a meme from a template with text lines.

The default backend="auto" selects the memegen rendering API for memegen-catalogue templates, and falls back to a Pillow client-side renderer for custom local images or whenever the user supplies a feature memegen can’t express (explicit fontsize or a custom outline). Extra Axes.text kwargs select the matplotlib renderer, the only one that can apply them.

Parameters:
templatestr

Template identifier – memegen ID, file path, or URL.

*linesstr

Text lines for each text position (top, bottom, etc.).

fontstr, optional

Font family name (default config["font"]).

colorstr, optional

Text fill color for every caption (default config["color"]). On the memegen backend, a comma-separated list such as "white,red" sets one color per line; when no color is chosen, memegen templates keep their own caption colors.

outline_colorstr, optional

Text outline color. Passing a non-default value under backend="auto" forces the Pillow backend, since memegen renders a hard-coded black stroke.

outline_widthfloat, optional

Outline stroke width. Under Pillow the stroke scales with the fitted font size (each unit adds 1/24 of it, so the default 2.0 matches memegen’s size / 12). Passing a non-default value under backend="auto" forces the Pillow backend.

fontsizefloat, optional

Explicit font size. Forces the Pillow backend under backend="auto" (memegen always auto-fits). Units depend on the backend: points under "matplotlib"; under "pillow", pixels at the template image’s native resolution, used as a maximum (captions still shrink to fit their box).

stylestr, optional

Text transform – "upper", "lower", or "none". memegen applies each template’s own casing (usually upper), so under backend="auto" anything but "upper" selects the Pillow backend.

backendstr, optional

"auto" (default), "memegen", "pillow", or "matplotlib" (legacy, draws captions with matplotlib.axes.Axes.text()).

extensionstr, optional

Output format requested from memegen – "png", "jpg", "gif", or "webp". memegen backend only. Animated GIF/WebP responses are shown as their last frame (where every timed caption is visible); the figure cannot hold the animation.

width, heightint, optional

Output dimensions in pixels. memegen backend only.

layoutstr, optional

memegen layout (e.g. "top"). memegen backend only.

backgroundstr, optional

Image URL to use instead of the template image. memegen only supports this on its custom template, so the render uses that template with your captions. memegen backend only.

overlayssequence of OverlaySpec, optional

Ad-hoc overlay image placements. memegen backend only.

template_stylestr, optional

memegen template-specific style (e.g. "maga" for "ds"). memegen backend only.

alt_textstr, optional

Text alternative describing the meme for screen-reader users. If omitted, one is generated from the template name and captions. Retrieve it with get_alt_text(); it is also embedded in the file written by savefig (PNG/SVG Description, PDF Subject).

showbool, optional

Whether to call matplotlib.pyplot.show() after rendering.

savefigstr, Path, or None, optional

Path to save the meme image to.

figsizetuple of (float, float) or None, optional

Figure size as (width, height) in inches.

dpiint or None, optional

Dots per inch.

axAxes or None, optional

Existing matplotlib Axes to render onto.

**text_kwargs

Additional keyword arguments forwarded to Axes.text(). Only the "matplotlib" backend applies them, so passing any under backend="auto" selects it; an explicit "memegen" or "pillow" backend ignores them with a UserWarning.

Returns:
figmatplotlib.figure.Figure

The matplotlib Figure containing the rendered meme.

axmatplotlib.axes.Axes

The matplotlib Axes containing the rendered meme.

Raises:
TemplateNotFoundError

If template looks like a memegen ID but memegen doesn’t know it.

FileNotFoundError

If template looks like a file path but the file doesn’t exist.

ValueError

If backend, style, or extension is not a valid choice.

requests.HTTPError

If memegen or an image URL returns an error status.

Examples

>>> import memeplotlib as memes
>>> fig, ax = memes.meme("buzz", "memes", "memes everywhere")
>>> fig, ax = memes.meme(
...     "drake", "writing tests", "shipping to prod",
...     font="impact", color="yellow",
... )
>>> fig, ax = memes.meme(
...     "buzz", "hello", "world",
...     fontsize=48,  # forces pillow backend under auto
... )
memeplotlib.memify(fig, *lines, position='top-bottom', font=None, color=None, outline_color=None, outline_width=None, fontsize=None, style=None, alt_text=None, show=False, savefig=None, **text_kwargs)[source]#

Add meme-style text to an existing matplotlib figure.

Overlays bold, outlined text on top of any matplotlib figure – useful for turning plots, charts, or other visualizations into memes.

Note

memify always renders text with matplotlib’s Axes.text (the figure isn’t a memegen template, so the API doesn’t apply). The backend parameter on meme() is intentionally not exposed here.

Parameters:
figmatplotlib.figure.Figure

The matplotlib figure to add text to.

*linesstr

Text lines to overlay.

positionstr, optional

Layout – "top-bottom" (default), "top", "bottom", or "center".

fontstr or None, optional

Font family name.

colorstr or None, optional

Text fill color.

outline_colorstr or None, optional

Text outline color.

outline_widthfloat or None, optional

Outline stroke width.

fontsizefloat or None, optional

Font size in points (auto if None).

stylestr or None, optional

Text transform – "upper", "lower", or "none".

alt_textstr or None, optional

Text alternative describing the result for screen-reader users. If omitted, the captions are described and appended to any alt text the figure already carries. Retrieve it with get_alt_text(); it is also embedded in the savefig file.

showbool, optional

Whether to call matplotlib.pyplot.show() after rendering (default: False).

savefigstr, Path, or None, optional

Path to save the result to.

**text_kwargs

Additional keyword arguments forwarded to Axes.text() for each rendered caption.

Returns:
matplotlib.figure.Figure

The modified Figure.

Examples

>>> import matplotlib.pyplot as plt
>>> import memeplotlib as memes
>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 9])
>>> memes.memify(fig, "stonks")
memeplotlib.rc_context(rc=None)[source]#

Temporarily override config keys, restoring originals on exit.

Mirrors matplotlib.rc_context(). Useful for scoped styling that should not leak to other code.

Parameters:
rcMapping or None, optional

Mapping of key-value pairs to apply within the context. If None, the active config is yielded unchanged but still snapshotted for restoration on exit.

Yields:
MemeplotlibConfig

The active config singleton.

Examples

>>> from memeplotlib import config, rc_context
>>> config["font"] = "impact"
>>> with rc_context({"font": "comic", "color": "yellow"}):
...     config["font"]
'comic'
>>> config["font"]
'impact'
memeplotlib.get_alt_text(artist)[source]#

Return the alt text memeplotlib attached to a Figure or Axes.

Every meme(), memify(), and Meme render records a description of the image. Use it as the alt attribute when publishing the meme on the web, in chat, or in documentation.

Parameters:
artistmatplotlib.figure.Figure or matplotlib.axes.Axes

A figure or axes returned by memeplotlib. For a figure holding several memes (e.g. subplots), the descriptions of its axes are joined in order.

Returns:
str or None

The description, or None if memeplotlib did not render it.

Examples

>>> import memeplotlib as memes
>>> fig, ax = memes.meme("buzz", "memes", "memes everywhere")
>>> memes.get_alt_text(fig)
'Meme using the "Buzz Lightyear" template. Top text: "memes". Bottom text: "memes everywhere".'
memeplotlib.build_memegen_url(template_id, lines, *, api_base, extension='png', template_style=None, font=None, color=None, width=None, height=None, layout=None, background=None, overlays=None, watermark=None)[source]#

Construct a memegen rendering URL.

Parameters:
template_idstr

memegen template identifier (e.g. "buzz", "drake").

linessequence of str

Caption lines in slot order. Empty strings become _ to preserve the slot.

api_basestr

Base URL of the memegen API (e.g. "https://api.memegen.link").

extensionstr, optional

Output format. One of "png", "jpg", "jpeg", "gif", "webp". Default "png".

template_stylestr or None, optional

Template-specific style (e.g. "maga"). May also be an arbitrary image URL for ad-hoc overlays.

fontstr or None, optional

memegen font alias (see MEMEGEN_FONT_ALIASES).

colorstr or None, optional

Text colors, one per caption line, comma-separated (e.g. "white" or "white,red"; HTML names or hex). memegen applies a single value to line 1 only; lines without a value keep the template’s color. (The meme() dispatcher repeats a single color for every line before calling this.)

widthint or None, optional

Output width in pixels.

heightint or None, optional

Output height in pixels.

layoutstr or None, optional

Alternate layout (e.g. "top").

backgroundstr or None, optional

Custom background image URL. memegen only honours it when template_id is "custom"; a UserWarning is emitted otherwise.

overlayssequence of OverlaySpec or None, optional

Ad-hoc overlay placements.

watermarkstr or None, optional

"none" asks memegen to omit its “Memegen.link” watermark. It is honoured only for requests carrying an API key with image access (config["api_key"]).

Returns:
str

Fully-formed memegen rendering URL.

Raises:
ValueError

If extension is unsupported.

Examples

>>> build_memegen_url(
...     "buzz", ["memes", "memes everywhere"],
...     api_base="https://api.memegen.link",
... )
'https://api.memegen.link/images/buzz/memes/memes_everywhere.png'
>>> build_memegen_url(
...     "ds", ["a", "b"],
...     api_base="https://api.memegen.link",
...     template_style="maga",
...     font="comic",
...     color="white,black",
...     width=600,
... )
'https://api.memegen.link/images/ds/a/b.png?style=maga&font=comic&...'

Classes#

class memeplotlib.Meme(template, *lines, font=None, color=None, outline_color=None, outline_width=None, fontsize=None, style=None, backend=None, extension=None, width=None, height=None, layout=None, background=None, overlays=None, template_style=None, alt_text=None)[source]#

Bases: object

A meme builder with a fluent (chainable) API.

Parameters:
templatestr or Template

Template identifier (memegen ID, file path, URL) or a Template instance.

*linesstr

Initial text lines.

fontstr or None, optional

Font family name.

colorstr or None, optional

Text fill color.

outline_colorstr or None, optional

Text outline color. Forces the Pillow backend under backend="auto", since memegen renders a hard-coded black stroke.

outline_widthfloat or None, optional

Outline stroke width; under Pillow it scales with the fitted font size (each unit adds 1/24 of it). Forces the Pillow backend under backend="auto".

fontsizefloat or None, optional

Font size: points under the matplotlib backend, pixels at the template’s native resolution (used as a maximum) under Pillow. Forces the Pillow backend under backend="auto" (memegen always auto-fits).

stylestr or None, optional

Text transform – "upper", "lower", or "none".

backendstr or None, optional

Override the rendering backend ("auto", "memegen", "pillow", "matplotlib"). None uses config["backend"].

extensionstr or None, optional

Output format requested from memegen ("png", "jpg", "gif", "webp"). memegen backend only.

width, heightint or None, optional

Output dimensions in pixels. memegen backend only.

layoutstr or None, optional

memegen layout (e.g. "top"). memegen backend only.

backgroundstr or None, optional

Custom background image URL. memegen backend only.

overlayssequence of OverlaySpec or None, optional

Ad-hoc overlay image placements. memegen backend only.

template_stylestr or None, optional

memegen template-specific style (e.g. "maga"). memegen backend only.

alt_textstr or None, optional

Text alternative for screen-reader users. None generates one from the template name and captions; see alt_text.

Examples

>>> from memeplotlib import Meme
>>> Meme("buzz").top("memes").bottom("memes everywhere").show()
>>> m = Meme("drake")
>>> m.top("writing tests")
>>> m.bottom("shipping to prod")
>>> fig, ax = m.render()
>>> m.save("output.png")
>>> # Per-line override forces the Pillow backend.
>>> Meme("buzz").top("hi").line(1, "world", fontsize=48).save("out.png")
top(text)[source]#

Set the top text line (index 0).

Parameters:
textstr

The text to place at the top of the meme.

Returns:
Meme

Self, for method chaining.

bottom(text)[source]#

Set the bottom text line (index 1).

Parameters:
textstr

The text to place at the bottom of the meme.

Returns:
Meme

Self, for method chaining.

text(index, text)[source]#

Set text at a specific line index.

Parameters:
indexint

Zero-based line index.

textstr

The text to place at the given position.

Returns:
Meme

Self, for method chaining.

line(index, text, *, fontsize=None, color=None, font=None, position=None, outline_color=None, outline_width=None, style=None)[source]#

Set text and per-line styling overrides for a single slot.

Passing any styling override forces the Pillow backend on render (memegen has no per-line equivalent).

Parameters:
indexint

Zero-based line index.

textstr

The text to place at the given slot.

fontsizefloat, optional

Override font size for this slot.

colorstr, optional

Override fill colour for this slot.

fontstr, optional

Override font family for this slot.

positionTextPosition, optional

Override the text-box position metadata for this slot.

outline_colorstr, optional

Override the outline colour for this slot (e.g. a white outline for a caption over a dark region).

outline_widthfloat, optional

Override the outline width for this slot.

stylestr, optional

Override the text transform for this slot – "upper", "lower", or "none".

Returns:
Meme

Self, for method chaining.

with_backend(backend)[source]#

Set the rendering backend.

Parameters:
backendstr

One of "auto", "memegen", "pillow", "matplotlib".

Returns:
Meme

Self, for method chaining.

with_alt_text(text)[source]#

Set (or, with None, reset to the generated default) the alt text.

Parameters:
textstr or None

Description of the meme for screen-reader users.

Returns:
Meme

Self, for method chaining.

property alt_text#

The alt text for this meme: explicit, or generated from its captions.

Generating the default resolves the template (which may require a network request for memegen IDs).

render(ax=None, figsize=None, dpi=None)[source]#

Render the meme and return the Figure and Axes.

Parameters:
axAxes or None, optional

Existing axes to render onto.

figsizetuple of (float, float) or None, optional

Figure size in inches (width, height).

dpiint or None, optional

Dots per inch.

Returns:
tuple of (Figure, Axes)

The rendered matplotlib Figure and Axes.

show()[source]#

Render and display the meme.

Calls render() if the meme has not been rendered yet, then displays the figure with matplotlib.pyplot.show().

save(path, dpi=None, **kwargs)[source]#

Render and save the meme to a file.

Parameters:
pathstr or Path

Output file path (e.g., "meme.png").

dpiint or None, optional

Dots per inch for the saved image.

**kwargs

Additional keyword arguments passed to matplotlib.figure.Figure.savefig(). The alt text is embedded as PNG/SVG Description (PDF Subject) metadata; entries in a metadata kwarg take precedence.

class memeplotlib.MemeplotlibConfig[source]#

Bases: MutableMapping[str, Any]

RcParams-style validated mapping of memeplotlib defaults.

Backed by an internal dictionary. Setting an unknown key raises KeyError. Setting a known key with an invalid value raises ValueError. Use rc_context() for scoped overrides.

Notes

Only the keys defined in MemeplotlibConfig.VALID_KEYS are accepted. The set of keys is fixed at class definition time.

Examples

>>> from memeplotlib import config
>>> config["font"] = "comic"
>>> config["dpi"]
150
reset()[source]#

Restore every key to its default value.

class memeplotlib.Template(id, name, image_url, text_positions=<factory>, keywords=<factory>, example=<factory>, lines_count=2, overlays_count=0, styles=<factory>, is_memegen=False)[source]#

Bases: object

A meme template with a background image and text position metadata.

Parameters:
idstr

Template identifier (e.g., "buzz", "drake").

namestr

Human-readable display name.

image_urlstr

URL or local file path to the background image.

text_positionslist of TextPosition, optional

Regions where text lines are rendered. Defaults to a classic top/bottom layout.

keywordslist of str, optional

Search keywords associated with the template.

examplelist of str, optional

Example text lines for the template.

lines_countint, optional

Maximum number of caption slots the template supports (mirrors the memegen lines field). Defaults to 2.

overlays_countint, optional

Number of template-defined overlay slots (mirrors the memegen overlays field). Defaults to 0.

styleslist of str, optional

Template-specific style names (mirrors the memegen styles field). Defaults to [].

is_memegenbool, optional

True if this template was constructed from memegen API metadata; False for custom local files / arbitrary URLs. Used by the rendering dispatcher to decide whether the memegen backend is even reachable.

classmethod from_memegen(template_id, api_base=None)[source]#

Fetch template metadata and blank image from the memegen API.

Parameters:
template_idstr

The memegen template ID (e.g., "buzz", "drake").

api_basestr or None, optional

Override the API base URL.

Returns:
Template

A Template instance with metadata populated from the API.

Raises:
TemplateNotFoundError

If the template ID doesn’t exist in the memegen API.

Examples

>>> t = Template.from_memegen("buzz")
>>> t.name
'Buzz Lightyear'
classmethod from_image(path_or_url, lines=2, name='')[source]#

Create a template from a local image file or URL.

Parameters:
path_or_urlstr

Path to a local image file, or an HTTP(S) URL.

linesint, optional

Number of text lines, which determines the number of text positions (default: 2).

namestr, optional

Display name for the template. Defaults to the file stem.

Returns:
Template

A Template instance backed by the given image.

Examples

>>> t = Template.from_image("photo.jpg")
>>> t = Template.from_image("https://example.com/img.png", lines=3)
get_image(cache=None)[source]#

Return the template background image as a NumPy RGBA array.

Downloads from the image URL if not already loaded or cached.

Parameters:
cacheTemplateCache or None, optional

Cache instance for storing/retrieving downloaded images.

Returns:
numpy.ndarray

RGBA image array with shape (height, width, 4).

class memeplotlib.TemplateRegistry(api_base=None, cache=None)[source]#

Bases: object

Registry that discovers and caches templates from the memegen API.

Parameters:
api_basestr or None, optional

Base URL for the memegen API. Uses config["api_base"] if None.

cacheTemplateCache or None, optional

Cache instance for storing template metadata. Defaults to the process-wide shared cache.

Examples

>>> reg = TemplateRegistry()
>>> results = reg.search("dog")
>>> all_templates = reg.list_all()
get(template_id)[source]#

Get a template by ID, fetching from the API if needed.

Parameters:
template_idstr

The memegen template ID.

Returns:
Template

The resolved template.

Raises:
TemplateNotFoundError

If the template ID is not found.

search(query)[source]#

Search templates by keyword, name, or ID.

Parameters:
querystr

Search term to match against template IDs, names, and keywords (case-insensitive).

Returns:
list of dict

Matching template metadata dicts.

list_all()[source]#

List all available templates.

Returns:
list of dict

Full template catalog from the memegen API.

refresh()[source]#

Force re-fetch of the template catalog from the API.

class memeplotlib.OverlaySpec[source]#

Bases: TypedDict

An ad-hoc overlay placement passed alongside a memegen render.

memegen accepts several overlay images but positions only the first: center and scale on later overlays are ignored (with a warning).

style#

Overlay image URL.

center#

Overlay anchor as (x, y) fractions in the range [0, 1] (first overlay only).

scale#

Overlay scale factor (first overlay only).

class memeplotlib.TextPosition(anchor_x=0.0, anchor_y=0.0, scale_x=1.0, scale_y=0.2, align='center', style='upper', angle=0.0)[source]#

Bases: object

Defines where and how a text line is rendered on a template.

All coordinates are fractional (0.0 to 1.0) relative to the image dimensions. (0, 0) is the top-left corner.

Attributes:
anchor_xfloat

Left edge of the text box (0.0 to 1.0).

anchor_yfloat

Top edge of the text box (0.0 to 1.0).

scale_xfloat

Width of the text box as a fraction of image width.

scale_yfloat

Height of the text box as a fraction of image height.

alignstr

Horizontal text alignment ("center", "left", "right").

stylestr

Reserved: default text style for this position ("upper", "lower", "none"). Not currently applied by any renderer; use the style argument instead.

anglefloat

Reserved: text rotation angle in degrees. Not currently applied by any renderer.

Singletons and exceptions#

memeplotlib.config = MemeplotlibConfig()#

RcParams-style validated mapping of memeplotlib defaults.

Backed by an internal dictionary. Setting an unknown key raises KeyError. Setting a known key with an invalid value raises ValueError. Use rc_context() for scoped overrides.

Notes

Only the keys defined in MemeplotlibConfig.VALID_KEYS are accepted. The set of keys is fixed at class definition time.

Examples

>>> from memeplotlib import config
>>> config["font"] = "comic"
>>> config["dpi"]
150
exception memeplotlib.TemplateNotFoundError[source]#

Bases: LookupError

Raised when a template ID is not found in the memegen API.

Subclasses LookupError, so generic “not found” handling (and any existing except Exception) catches it.