Skip to content

Commit ba1f41b

Browse files
committed
FIX: review comments
1 parent 59aed70 commit ba1f41b

File tree

8 files changed

+70
-46
lines changed

8 files changed

+70
-46
lines changed

doc/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -380,7 +380,7 @@ def gallery_image_warning_filter(record):
380380
plot_formats = [formats[target] for target in ['html', 'latex']
381381
if target in sys.argv] or list(formats.values())
382382
# make 2x images for srcset argument to <img>
383-
plot_srcset = '2x'
383+
plot_srcset = ['2x']
384384

385385
# GitHub extension
386386

doc/users/next_whats_new/plot_directive_srcset.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ figures and add these to the the built html docs. In ``conf.py``::
1111
'matplotlib.sphinxext.figmpl_directive',
1212
...]
1313

14-
plot_srcset = '2x'
14+
plot_srcset = ['2x']
1515

1616
will make png files with double the resolution for hiDPI displays. Resulting
1717
html files will have image entries like::

lib/matplotlib/_tight_bbox.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
66

7+
import numpy as np
78

89
def adjust_bbox(fig, bbox_inches, fixed_dpi=None):
910
"""
@@ -54,8 +55,12 @@ def restore_bbox():
5455
dpi_scale = fixed_dpi / fig.dpi
5556

5657
fig.bbox_inches = Bbox.from_bounds(0, 0, *bbox_inches.size)
57-
x0, y0 = tr.transform(bbox_inches.p0)
58+
print(bbox_inches.p0)
59+
x0 = np.floor(bbox_inches.p0[0]*fig.dpi * dpi_scale)
60+
y0 = np.floor(bbox_inches.p0[1]*fig.dpi * dpi_scale)
61+
# x0, y0 = tr.transform(bbox_inches.p0)
5862
w1, h1 = fig.bbox.size * dpi_scale
63+
print('x0, y0, w1, h1', x0, y0, w1, h1, fig.bbox)
5964
fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1)
6065
fig.transFigure.invalidate()
6166

lib/matplotlib/cbook.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1277,7 +1277,10 @@ def _to_unmasked_float_array(x):
12771277
if hasattr(x, 'mask'):
12781278
return np.ma.asarray(x, float).filled(np.nan)
12791279
else:
1280-
return np.asarray(x, float)
1280+
try:
1281+
return np.asarray(x, float)
1282+
except TypeError:
1283+
return np.asarray([float(xx) for xx in x])
12811284

12821285

12831286
def _check_1d(x):

lib/matplotlib/sphinxext/figmpl_directive.py

Lines changed: 24 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,9 @@ class figmplnode(nodes.General, nodes.Element):
3131

3232
class FigureMpl(Figure):
3333
"""
34-
Implements a directive to allow an optional hidpi image. Meant to be
35-
used with the *plot_srcset* configuration option in conf.py,
34+
Implements a directive to allow an optional hidpi image.
35+
36+
Meant to be used with the *plot_srcset* configuration option in conf.py,
3637
and gets set in the TEMPLATE of plot_directive.py
3738
3839
e.g.::
@@ -47,7 +48,7 @@ class FigureMpl(Figure):
4748
4849
<img src="sphx_glr_bar_001_hidpi.png"
4950
srcset="_images/some_plot-1.png,
50-
_images/some_plots-1.2x.png 2.00 x",
51+
_images/some_plots-1.2x.png 2.00x",
5152
alt="bar"
5253
class="plot_directive" />
5354
@@ -64,7 +65,7 @@ class FigureMpl(Figure):
6465
6566
<img src="../_images/nestedpage-index-1.png"
6667
srcset="../_images/nestedpage-index-1.png,
67-
../_images/_images/nestedpage-index-1.2x.png 2x",
68+
../_images/_images/nestedpage-index-1.2x.png 2.00x",
6869
alt="bar"
6970
class="sphx-glr-single-img" />
7071
@@ -101,7 +102,7 @@ def run(self):
101102

102103
# we would like uri to be the highest dpi version so that
103104
# latex etc will use that. But for now, lets just make
104-
# imagenm
105+
# imagenm... maybe pdf one day?
105106

106107
image_node['uri'] = imagenm
107108
image_node['srcset'] = self.options.get('srcset', None)
@@ -186,23 +187,22 @@ def visit_figmpl_html(self, node):
186187
# ../../_images/ for dirhtml and ../_images/ for html
187188
imagerel = relpath(imagedir, os.path.dirname(dest))
188189
if self.builder.name == "dirhtml":
189-
imagerel = '..' + imagerel + ''
190-
else: # html
191-
imagerel = imagerel + ''
190+
imagerel = f'..{imagerel}'
192191

193192
# make uri also be relative...
194193
nm = PurePosixPath(node['uri'][1:]).name
195-
uri = imagerel + '/' + rel + nm
194+
uri = f'{imagerel}/{rel}{nm}'
196195

197196
# make srcset str. Need to change all the prefixes!
197+
maxsrc = uri
198+
srcsetst = ''
198199
if srcset:
199-
srcsetst = ''
200200
maxmult = -1
201201
for mult in srcset:
202202
nm = PurePosixPath(srcset[mult][1:]).name
203203
# ../../_images/plot_1_2_0x.png
204-
path = imagerel + '/' + rel + nm
205-
srcsetst += f'{path}'
204+
path = f'{imagerel}/{rel}{nm}'
205+
srcsetst += path
206206
if mult == 0:
207207
srcsetst += ', '
208208
else:
@@ -214,20 +214,23 @@ def visit_figmpl_html(self, node):
214214

215215
# trim trailing comma and space...
216216
srcsetst = srcsetst[:-2]
217-
else:
218-
srcsetst = ''
219-
maxsrc = uri
220217

221218
alt = node['alt']
222219
if node['class'] is not None:
223-
classst = ''
224-
for cl in node['class']:
225-
classst += cl + ' '
220+
classst = ' '.join(node['class'])
226221
classst = f'class="{classst}"'
227222

228223
else:
229224
classst = ''
230225

226+
stylers = ['width', 'height', 'scale']
227+
stylest = ''
228+
for style in stylers:
229+
if node[style]:
230+
stylest += f'{style}: {node[style]};'
231+
232+
figalign = node['align'] if node['align'] else 'center'
233+
231234
# <figure class="align-default" id="id1">
232235
# <a class="reference internal image-reference" href="_images/index-1.2x.png">
233236
# <img alt="_images/index-1.2x.png" src="_images/index-1.2x.png" style="width: 53%;" />
@@ -237,15 +240,6 @@ def visit_figmpl_html(self, node):
237240
# <a class="headerlink" href="#id1" title="Permalink to this image">#</a></p>
238241
# </figcaption>
239242
# </figure>
240-
241-
stylers = ['width', 'height', 'scale']
242-
stylest = ''
243-
for style in stylers:
244-
if node[style]:
245-
stylest += f'{style}: {node[style]};'
246-
247-
figalign = node['align'] if node['align'] else 'center'
248-
249243
img_block = (f'<img src="{uri}" style="{stylest}" srcset="{srcsetst}" ' +
250244
f'alt="{alt}" {classst}/>')
251245
html_block = f'<figure class="align-{figalign}">\n'
@@ -265,9 +259,9 @@ def visit_figmpl_latex(self, node):
265259
imagedir, srcset = _copy_images_figmpl(self, node)
266260
maxmult = -1
267261
# choose the highest res version for latex:
268-
for key in srcset.keys():
269-
maxmult = max(maxmult, key)
270-
node['uri'] = str(PurePosixPath(srcset[maxmult]).name)
262+
# choose the highest res version for latex:
263+
maxmult = max(srcset, default=-1)
264+
node['uri'] = PurePosixPath(srcset[maxmult]).name
271265

272266
self.visit_figure(node)
273267

lib/matplotlib/sphinxext/plot_directive.py

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -141,9 +141,9 @@
141141
Provide a customized template for preparing restructured text.
142142
143143
plot_srcset
144-
Allow the srcset image option for responsive image resolutions. Comma
145-
separated string with the multiplicative factors followed by an "x".
146-
e.g. "2.0x, 1.5x". "2.0x" will create a png with the default "png"
144+
Allow the srcset image option for responsive image resolutions. List of
145+
strings with the multiplicative factors followed by an "x".
146+
e.g. ["2.0x", "1.5x"]. "2.0x" will create a png with the default "png"
147147
resolution from plot_formats, multiplied by 2. If plot_src is
148148
specified, the plot directive uses the
149149
:doc:`/api/sphinxext_figmpl_directive_api` (instead of the usual figure
@@ -378,11 +378,9 @@ def _split_code_at_show(text, function_name):
378378
{%- endif -%}
379379
)
380380
{% endif %}
381-
382381
"""
383382

384383
TEMPLATE_SRCSET = _SOURCECODE + """
385-
386384
{% for img in images %}
387385
.. figure-mpl:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}
388386
{% for option in options -%}
@@ -587,12 +585,10 @@ def get_plot_formats(config):
587585
return formats
588586

589587

590-
def _parse_srcset(st):
588+
def _parse_srcset(entries):
591589
"""
592590
Parse srcset for multiples...
593591
"""
594-
entries = st.split(',')
595-
596592
srcset = {}
597593
for entry in entries:
598594
entry = entry.strip()
@@ -729,7 +725,7 @@ def run(arguments, content, options, state_machine, state, lineno):
729725
config = document.settings.env.config
730726
nofigs = 'nofigs' in options
731727

732-
if (config.plot_srcset and setup.app.builder.name == 'singlehtml'):
728+
if config.plot_srcset and setup.app.builder.name == 'singlehtml':
733729
raise ExtensionError(
734730
'plot_srcset option not compatible with single HTML writer')
735731

@@ -911,8 +907,7 @@ def run(arguments, content, options, state_machine, state, lineno):
911907
else:
912908
src_name = None
913909
if config.plot_srcset:
914-
srcset0 = _parse_srcset(config.plot_srcset)
915-
srcset = [srcset0[sr] for sr in srcset0]
910+
srcset = [*_parse_srcset(config.plot_srcset).values()]
916911
template = TEMPLATE_SRCSET
917912
else:
918913
srcset = None

lib/matplotlib/tests/test_sphinxext.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ def test_srcset_version(tmp_path):
192192
doctree_dir = tmp_path / 'doctrees'
193193

194194
build_sphinx_html(tmp_path, doctree_dir, html_dir, extra_args=[
195-
'-D', 'plot_srcset=2x'])
195+
'-c', f'{tmp_path}/confSrcset/'])
196196

197197
def plot_file(num, suff=''):
198198
return img_dir / f'some_plots-{num}{suff}.png'
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import sphinx
2+
from packaging.version import parse as parse_version
3+
4+
# -- General configuration ------------------------------------------------
5+
6+
extensions = ['matplotlib.sphinxext.plot_directive',
7+
'matplotlib.sphinxext.figmpl_directive']
8+
templates_path = ['_templates']
9+
source_suffix = '.rst'
10+
master_doc = 'index'
11+
project = 'tinypages'
12+
copyright = '2014, Matplotlib developers'
13+
version = '0.1'
14+
release = '0.1'
15+
exclude_patterns = ['_build']
16+
pygments_style = 'sphinx'
17+
18+
# -- Options for HTML output ----------------------------------------------
19+
20+
if parse_version(sphinx.__version__) >= parse_version('1.3'):
21+
html_theme = 'classic'
22+
else:
23+
html_theme = 'default'
24+
25+
# html_static_path = ['_static']
26+
27+
plot_srcset = ['2x']

0 commit comments

Comments
 (0)