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 (explicitfontsizeor a custom outline). ExtraAxes.textkwargs select the matplotlib renderer, the only one that can apply them.- Parameters:
- template
str Template identifier – memegen ID, file path, or URL.
- *lines
str Text lines for each text position (top, bottom, etc.).
- font
str,optional Font family name (default
config["font"]).- color
str,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_color
str,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_width
float,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.- fontsize
float,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).- style
str,optional Text transform –
"upper","lower", or"none". memegen applies each template’s own casing (usually upper), so underbackend="auto"anything but"upper"selects the Pillow backend.- backend
str,optional "auto"(default),"memegen","pillow", or"matplotlib"(legacy, draws captions withmatplotlib.axes.Axes.text()).- extension
str,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, height
int,optional Output dimensions in pixels. memegen backend only.
- layout
str,optional memegen layout (e.g.
"top"). memegen backend only.- background
str,optional Image URL to use instead of the template image. memegen only supports this on its
customtemplate, so the render uses that template with your captions. memegen backend only.- overlayssequence
ofOverlaySpec,optional Ad-hoc overlay image placements. memegen backend only.
- template_style
str,optional memegen template-specific style (e.g.
"maga"for"ds"). memegen backend only.- alt_text
str,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 bysavefig(PNG/SVGDescription, PDFSubject).- showbool,
optional Whether to call
matplotlib.pyplot.show()after rendering.- savefig
str,Path,orNone,optional Path to save the meme image to.
- figsize
tupleof(float,float)orNone,optional Figure size as
(width, height)in inches.- dpi
intorNone,optional Dots per inch.
- ax
AxesorNone,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 underbackend="auto"selects it; an explicit"memegen"or"pillow"backend ignores them with aUserWarning.
- template
- Returns:
- fig
matplotlib.figure.Figure The matplotlib Figure containing the rendered meme.
- ax
matplotlib.axes.Axes The matplotlib Axes containing the rendered meme.
- fig
- Raises:
TemplateNotFoundErrorIf template looks like a memegen ID but memegen doesn’t know it.
FileNotFoundErrorIf template looks like a file path but the file doesn’t exist.
ValueErrorIf
backend,style, orextensionis not a valid choice.requests.HTTPErrorIf 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
memifyalways renders text with matplotlib’sAxes.text(the figure isn’t a memegen template, so the API doesn’t apply). Thebackendparameter onmeme()is intentionally not exposed here.- Parameters:
- fig
matplotlib.figure.Figure The matplotlib figure to add text to.
- *lines
str Text lines to overlay.
- position
str,optional Layout –
"top-bottom"(default),"top","bottom", or"center".- font
strorNone,optional Font family name.
- color
strorNone,optional Text fill color.
- outline_color
strorNone,optional Text outline color.
- outline_width
floatorNone,optional Outline stroke width.
- fontsize
floatorNone,optional Font size in points (auto if
None).- style
strorNone,optional Text transform –
"upper","lower", or"none".- alt_text
strorNone,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 thesavefigfile.- showbool,
optional Whether to call
matplotlib.pyplot.show()after rendering (default:False).- savefig
str,Path,orNone,optional Path to save the result to.
- **text_kwargs
Additional keyword arguments forwarded to
Axes.text()for each rendered caption.
- fig
- Returns:
matplotlib.figure.FigureThe 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:
- rc
MappingorNone,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.
- rc
- Yields:
MemeplotlibConfigThe 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(), andMemerender records a description of the image. Use it as thealtattribute when publishing the meme on the web, in chat, or in documentation.- Parameters:
- artist
matplotlib.figure.Figureormatplotlib.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.
- artist
- Returns:
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_id
str memegen template identifier (e.g.
"buzz","drake").- linessequence
ofstr Caption lines in slot order. Empty strings become
_to preserve the slot.- api_base
str Base URL of the memegen API (e.g.
"https://api.memegen.link").- extension
str,optional Output format. One of
"png","jpg","jpeg","gif","webp". Default"png".- template_style
strorNone,optional Template-specific style (e.g.
"maga"). May also be an arbitrary image URL for ad-hoc overlays.- font
strorNone,optional memegen font alias (see
MEMEGEN_FONT_ALIASES).- color
strorNone,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. (Thememe()dispatcher repeats a singlecolorfor every line before calling this.)- width
intorNone,optional Output width in pixels.
- height
intorNone,optional Output height in pixels.
- layout
strorNone,optional Alternate layout (e.g.
"top").- background
strorNone,optional Custom background image URL. memegen only honours it when template_id is
"custom"; aUserWarningis emitted otherwise.- overlayssequence
ofOverlaySpecorNone,optional Ad-hoc overlay placements.
- watermark
strorNone,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"]).
- template_id
- Returns:
strFully-formed memegen rendering URL.
- Raises:
ValueErrorIf 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:
objectA meme builder with a fluent (chainable) API.
- Parameters:
- template
strorTemplate Template identifier (memegen ID, file path, URL) or a
Templateinstance.- *lines
str Initial text lines.
- font
strorNone,optional Font family name.
- color
strorNone,optional Text fill color.
- outline_color
strorNone,optional Text outline color. Forces the Pillow backend under
backend="auto", since memegen renders a hard-coded black stroke.- outline_width
floatorNone,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".- fontsize
floatorNone,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).- style
strorNone,optional Text transform –
"upper","lower", or"none".- backend
strorNone,optional Override the rendering backend (
"auto","memegen","pillow","matplotlib").Noneusesconfig["backend"].- extension
strorNone,optional Output format requested from memegen (
"png","jpg","gif","webp"). memegen backend only.- width, height
intorNone,optional Output dimensions in pixels. memegen backend only.
- layout
strorNone,optional memegen layout (e.g.
"top"). memegen backend only.- background
strorNone,optional Custom background image URL. memegen backend only.
- overlayssequence
ofOverlaySpecorNone,optional Ad-hoc overlay image placements. memegen backend only.
- template_style
strorNone,optional memegen template-specific style (e.g.
"maga"). memegen backend only.- alt_text
strorNone,optional Text alternative for screen-reader users.
Nonegenerates one from the template name and captions; seealt_text.
- template
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")
- 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:
- index
int Zero-based line index.
- text
str The text to place at the given slot.
- fontsize
float,optional Override font size for this slot.
- color
str,optional Override fill colour for this slot.
- font
str,optional Override font family for this slot.
- position
TextPosition,optional Override the text-box position metadata for this slot.
- outline_color
str,optional Override the outline colour for this slot (e.g. a white outline for a caption over a dark region).
- outline_width
float,optional Override the outline width for this slot.
- style
str,optional Override the text transform for this slot –
"upper","lower", or"none".
- index
- Returns:
MemeSelf, 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).
- show()[source]#
Render and display the meme.
Calls
render()if the meme has not been rendered yet, then displays the figure withmatplotlib.pyplot.show().
- save(path, dpi=None, **kwargs)[source]#
Render and save the meme to a file.
- Parameters:
- path
strorPath Output file path (e.g.,
"meme.png").- dpi
intorNone,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/SVGDescription(PDFSubject) metadata; entries in ametadatakwarg take precedence.
- path
- 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 raisesValueError. Userc_context()for scoped overrides.Notes
Only the keys defined in
MemeplotlibConfig.VALID_KEYSare accepted. The set of keys is fixed at class definition time.Examples
>>> from memeplotlib import config >>> config["font"] = "comic" >>> config["dpi"] 150
- 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:
objectA meme template with a background image and text position metadata.
- Parameters:
- id
str Template identifier (e.g.,
"buzz","drake").- name
str Human-readable display name.
- image_url
str URL or local file path to the background image.
- text_positions
listofTextPosition,optional Regions where text lines are rendered. Defaults to a classic top/bottom layout.
- keywords
listofstr,optional Search keywords associated with the template.
- example
listofstr,optional Example text lines for the template.
- lines_count
int,optional Maximum number of caption slots the template supports (mirrors the memegen
linesfield). Defaults to2.- overlays_count
int,optional Number of template-defined overlay slots (mirrors the memegen
overlaysfield). Defaults to0.- styles
listofstr,optional Template-specific style names (mirrors the memegen
stylesfield). Defaults to[].- is_memegenbool,
optional Trueif this template was constructed from memegen API metadata;Falsefor custom local files / arbitrary URLs. Used by the rendering dispatcher to decide whether the memegen backend is even reachable.
- id
- classmethod from_memegen(template_id, api_base=None)[source]#
Fetch template metadata and blank image from the memegen API.
- Parameters:
- Returns:
TemplateA Template instance with metadata populated from the API.
- Raises:
TemplateNotFoundErrorIf 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:
- Returns:
TemplateA 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:
- cache
TemplateCacheorNone,optional Cache instance for storing/retrieving downloaded images.
- cache
- Returns:
numpy.ndarrayRGBA image array with shape
(height, width, 4).
- class memeplotlib.TemplateRegistry(api_base=None, cache=None)[source]#
Bases:
objectRegistry that discovers and caches templates from the memegen API.
- Parameters:
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_id
str The memegen template ID.
- template_id
- Returns:
TemplateThe resolved template.
- Raises:
TemplateNotFoundErrorIf the template ID is not found.
- class memeplotlib.OverlaySpec[source]#
Bases:
TypedDictAn ad-hoc overlay placement passed alongside a memegen render.
memegen accepts several overlay images but positions only the first:
centerandscaleon 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:
objectDefines 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_x
float Left edge of the text box (0.0 to 1.0).
- anchor_y
float Top edge of the text box (0.0 to 1.0).
- scale_x
float Width of the text box as a fraction of image width.
- scale_y
float Height of the text box as a fraction of image height.
- align
str Horizontal text alignment (
"center","left","right").- style
str Reserved: default text style for this position (
"upper","lower","none"). Not currently applied by any renderer; use thestyleargument instead.- angle
float Reserved: text rotation angle in degrees. Not currently applied by any renderer.
- anchor_x
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 raisesValueError. Userc_context()for scoped overrides.Notes
Only the keys defined in
MemeplotlibConfig.VALID_KEYSare 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:
LookupErrorRaised when a template ID is not found in the memegen API.
Subclasses
LookupError, so generic “not found” handling (and any existingexcept Exception) catches it.