Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions doc/release/next_whats_new/figure_alt_text.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Figures can carry alternative text
----------------------------------

Figures now have alternative text ("alt text"): a plain-text description

Check warning on line 4 in doc/release/next_whats_new/figure_alt_text.rst

View workflow job for this annotation

GitHub Actions / sphinx

[sphinx] doc/release/next_whats_new/figure_alt_text.rst#L4

py:obj reference target not found: Figure.set_alt_text [ref.obj]
Raw output
doc/release/next_whats_new/figure_alt_text.rst:4: WARNING: py:obj reference target not found: Figure.set_alt_text [ref.obj]

Check warning on line 4 in doc/release/next_whats_new/figure_alt_text.rst

View workflow job for this annotation

GitHub Actions / sphinx

[sphinx] doc/release/next_whats_new/figure_alt_text.rst#L4

py:obj reference target not found: Figure.get_alt_text [ref.obj]
Raw output
doc/release/next_whats_new/figure_alt_text.rst:4: WARNING: py:obj reference target not found: Figure.get_alt_text [ref.obj]
of the figure for people who cannot see it, e.g. when using a screen
reader. Set it with `.Figure.set_alt_text` and read it back with
`.Figure.get_alt_text`::

fig, ax = plt.subplots()
ax.plot([0, 1], [0, 1])
fig.set_alt_text("Line plot rising from (0, 0) to (1, 1)")

When saving to SVG, the root ``<svg>`` element gets a ``role="img"``
attribute and the alt text is written as its ``<title>`` child, which
makes it the accessible name of the figure. On the other backends that
accept file metadata (PNG, PDF, PostScript, PGF), the alt text is stored
as the ``'Description'`` metadata entry instead, unless a description is
explicitly passed to `.Figure.savefig`; note that file metadata is not
an accessible name, and PDF output does not become a tagged PDF.
16 changes: 16 additions & 0 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -2369,6 +2369,22 @@ def print_figure(
# _get_renderer may change the figure dpi (as vector formats
# force the figure dpi to 72), so we need to set it again here.
with cbook._setattr_cm(self.figure, dpi=dpi):
# Pass the figure's alt text on as the 'Description'
# metadata entry, unless the caller explicitly supplied
# one. Backends that give the alt text an accessible
# representation of its own (currently SVG) read it from
# the figure directly; for the other backends this lands
# in the file metadata only. Restrict this to the formats
# whose print methods accept metadata; the others (e.g.
# jpeg, tiff) reject a metadata argument entirely.
alt_text = self.figure.get_alt_text()
if (alt_text and format in {
'eps', 'pdf', 'pgf', 'png', 'ps', 'svg', 'svgz'}
and 'Description' not in (
kwargs.get('metadata') or {})):
kwargs['metadata'] = {
**(kwargs.get('metadata') or {}),
'Description': alt_text}
result = print_method(
filename,
facecolor=facecolor,
Expand Down
31 changes: 25 additions & 6 deletions lib/matplotlib/backends/backend_svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ def _svg_blend_mode(mpl_blend_mode):

class RendererSVG(RendererBase):
def __init__(self, width, height, svgwriter, basename=None, image_dpi=72,
*, metadata=None):
*, metadata=None, alt_text=None):
self.width = width
self.height = height
self.writer = _XMLWriter(svgwriter)
Expand Down Expand Up @@ -356,6 +356,11 @@ def __init__(self, width, height, svgwriter, basename=None, image_dpi=72,
str_height = _short_float_fmt(height)
str_width = _short_float_fmt(width)
svgwriter.write(svgProlog)
svg_attrib = {'xmlns:xlink': "http://www.w3.org/1999/xlink"}
if alt_text:
# Expose the figure as a single image to assistive technology;
# the <title> written below is its accessible name.
svg_attrib['role'] = 'img'
self._start_id = self.writer.start(
'svg',
width=f'{str_width}pt',
Expand All @@ -364,8 +369,10 @@ def __init__(self, width, height, svgwriter, basename=None, image_dpi=72,
xmlns="http://www.w3.org/2000/svg",
version="1.1",
id=mpl.rcParams['svg.id'],
attrib={'xmlns:xlink': "http://www.w3.org/1999/xlink"})
self._write_metadata(metadata)
attrib=svg_attrib)
if alt_text:
self.writer.element('title', text=alt_text)
self._write_metadata(metadata, alt_text=alt_text)
self._write_default_style()

def _get_clippath_id(self, clippath):
Expand All @@ -388,7 +395,7 @@ def finalize(self):
self.writer.close(self._start_id)
self.writer.flush()

def _write_metadata(self, metadata):
def _write_metadata(self, metadata, alt_text=None):
# Add metadata following the Dublin Core Metadata Initiative, and the
# Creative Commons Rights Expression Language. This is mainly for
# compatibility with Inkscape.
Expand All @@ -406,7 +413,12 @@ def _write_metadata(self, metadata):
if 'Title' in metadata:
title = metadata['Title']
_check_is_str(title, 'Title')
writer.element('title', text=title)
if not alt_text:
# If alt text was given it has already been written as the
# <title> (the accessible name); the metadata Title is still
# recorded as dc:title below, but a second <title> element
# would be ignored or misread by assistive technology.
writer.element('title', text=title)

# Special handling.
date = metadata.get('Date', None)
Expand Down Expand Up @@ -1425,6 +1437,12 @@ def print_svg(self, filename, *, bbox_inches_restore=None, metadata=None):
.. _DC: https://www.dublincore.org/specifications/dublin-core/

__ DC_

If the figure has alternative text (see `.Figure.set_alt_text`),
the root ``<svg>`` element is given a ``role="img"`` attribute and
the alt text is written as its ``<title>`` child (its accessible
name), taking precedence over the ``<title>`` element otherwise
derived from the ``'Title'`` metadata.
"""
with cbook.open_file_cm(filename, "w", encoding="utf-8") as fh:
if not cbook.file_requires_unicode(fh):
Expand All @@ -1435,7 +1453,8 @@ def print_svg(self, filename, *, bbox_inches_restore=None, metadata=None):
w, h = width * 72, height * 72
renderer = MixedModeRenderer(
self.figure, width, height, dpi,
RendererSVG(w, h, fh, image_dpi=dpi, metadata=metadata),
RendererSVG(w, h, fh, image_dpi=dpi, metadata=metadata,
alt_text=self.figure.get_alt_text() or None),
bbox_inches_restore=bbox_inches_restore)
self.figure.draw(renderer)
renderer.finalize()
Expand Down
40 changes: 40 additions & 0 deletions lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""
`matplotlib.figure` implements the following classes:

Expand Down Expand Up @@ -2739,6 +2739,8 @@

self.subplotpars = subplotpars

self._alt_text = ""

self._axstack = _AxesStack() # track all figure Axes and current Axes
self.clear()

Expand Down Expand Up @@ -3296,6 +3298,44 @@
self.dpi = val
self.stale = True

def get_alt_text(self):
"""Return the alternative text of the figure; see `set_alt_text`."""
return self._alt_text

def set_alt_text(self, alt_text):
"""
Set the alternative text ("alt text") describing this figure.

The alt text is a plain-text description of the figure's content
for people who cannot see the figure, e.g. when using a screen
reader. It defaults to ``""`` (no alternative text).

When the figure is saved, backends use the alt text as follows:

- The SVG backend gives the root ``<svg>`` element a
``role="img"`` attribute and writes the alt text as the
element's ``<title>`` child, which makes it the accessible name
of the figure.
- Other backends that accept file metadata (PNG, PDF, PostScript
and PGF) receive it as the ``'Description'`` metadata entry,
unless a ``'Description'`` is explicitly passed in the
*metadata* parameter of `.Figure.savefig`. Unlike the SVG
``<title>``, file metadata is not an accessible name; in
particular, this does not make PDF output a tagged PDF.

Parameters
----------
alt_text : str or None
The alternative text. Passing None or an empty string clears
the alt text, in which case saved output is unchanged.
"""
if alt_text is None:
alt_text = ""
if not isinstance(alt_text, str):
raise TypeError(
f"alt_text must be a string or None, not {type(alt_text)}")
self._alt_text = alt_text

def set_figwidth(self, val, forward=True):
"""
Set the width of the figure in inches.
Expand Down
2 changes: 2 additions & 0 deletions lib/matplotlib/figure.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,8 @@ class Figure(FigureBase):
def get_figheight(self) -> float: ...
def get_dpi(self) -> float: ...
def set_dpi(self, val: float) -> None: ...
def get_alt_text(self) -> str: ...
def set_alt_text(self, alt_text: str | None) -> None: ...
def set_figwidth(self, val: float, forward: bool = ...) -> None: ...
def set_figheight(self, val: float, forward: bool = ...) -> None: ...
def clear(self, keep_observers: bool = ...) -> None: ...
Expand Down
56 changes: 56 additions & 0 deletions lib/matplotlib/tests/test_backend_svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,62 @@ def test_svg_metadata():
assert values == metadata['Keywords']


def test_svg_alt_text():
# The figure's alt text becomes the accessible name of the SVG:
# role="img" on the root element and the alt text as its <title> child.
SVGNS = '{http://www.w3.org/2000/svg}'

fig, ax = plt.subplots()
fig.set_alt_text('A line plot of Tom & Jerry against time')
with BytesIO() as fd:
fig.savefig(fd, format='svg')
buf = fd.getvalue().decode()

root = xml.etree.ElementTree.fromstring(buf)
assert root.attrib['role'] == 'img'
titles = [node.text for node in root.findall(f'./{SVGNS}title')]
assert titles == ['A line plot of Tom & Jerry against time']


def test_svg_alt_text_takes_precedence_over_metadata_title():
# With both alt text and a 'Title' metadata entry, there is a single
# <title> element (the alt text); the Title is still recorded in the
# Dublin Core metadata.
SVGNS = '{http://www.w3.org/2000/svg}'
RDFNS = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}'
CCNS = '{http://creativecommons.org/ns#}'
DCNS = '{http://purl.org/dc/elements/1.1/}'

fig, ax = plt.subplots()
fig.set_alt_text('alt text')
with BytesIO() as fd:
fig.savefig(fd, format='svg', metadata={'Title': 'metadata title'})
buf = fd.getvalue().decode()

root = xml.etree.ElementTree.fromstring(buf)
titles = [node.text for node in root.findall(f'./{SVGNS}title')]
assert titles == ['alt text']
rdf, = root.findall(f'./{SVGNS}metadata/{RDFNS}RDF')
dc_titles = [node.text
for node in rdf.findall(f'./{CCNS}Work/{DCNS}title')]
assert dc_titles == ['metadata title']


def test_svg_no_alt_text_by_default():
# Without alt text the output is unchanged: no role attribute and no
# <title> element on the root element.
SVGNS = '{http://www.w3.org/2000/svg}'

fig, ax = plt.subplots()
with BytesIO() as fd:
fig.savefig(fd, format='svg')
buf = fd.getvalue().decode()

root = xml.etree.ElementTree.fromstring(buf)
assert 'role' not in root.attrib
assert not root.findall(f'./{SVGNS}title')


@image_comparison(["multi_font_aspath.svg"], style='mpl20')
def test_multi_font_aspath():
fonts, test_str = _gen_multi_font_text()
Expand Down
31 changes: 31 additions & 0 deletions lib/matplotlib/tests/test_figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -1734,6 +1734,37 @@ def test_gridspec_no_mutate_input():
plt.subplot_mosaic('AB', width_ratios=[1, 2], gridspec_kw=gs)


def test_alt_text():
fig = Figure()
assert fig.get_alt_text() == ""
fig.set_alt_text("A description of the figure")
assert fig.get_alt_text() == "A description of the figure"
fig.set_alt_text(None)
assert fig.get_alt_text() == ""
with pytest.raises(TypeError, match="alt_text must be a string"):
fig.set_alt_text(42)


def test_alt_text_saved_as_description_metadata():
# On backends without an accessible representation of the alt text, it
# is passed through as the 'Description' file metadata; an explicit
# 'Description' given to savefig takes precedence.
fig = Figure()
fig.set_alt_text("A description of the figure")
with io.BytesIO() as fd:
fig.savefig(fd, format="png")
fd.seek(0)
with Image.open(fd) as im:
assert im.text["Description"] == "A description of the figure"
with io.BytesIO() as fd:
fig.savefig(fd, format="png", metadata={"Description": "explicit"})
fd.seek(0)
with Image.open(fd) as im:
assert im.text["Description"] == "explicit"
# Formats whose print methods do not accept metadata at all still save.
fig.savefig(io.BytesIO(), format="jpeg")


@pytest.mark.parametrize('fmt', ['eps', 'pdf', 'png', 'ps', 'svg', 'svgz'])
def test_savefig_metadata(fmt):
Figure().savefig(io.BytesIO(), format=fmt, metadata={})
Expand Down
Loading