Skip to content

Commit 558cc47

Browse files
authored
Merge pull request #380 from martinRenou/fix_dpi_and_figure_label
Fix DPI + save figure label for static plot
2 parents 76111ce + eed758f commit 558cc47

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

ipympl/backend_nbagg.py

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,15 @@ def __init__(self, canvas, *args, **kwargs):
103103
def export(self):
104104
buf = io.BytesIO()
105105
self.canvas.figure.savefig(buf, format='png', dpi='figure')
106-
data = "<img src='data:image/png;base64,{0}'/>"
107-
data = data.format(b64encode(buf.getvalue()).decode('utf-8'))
106+
# Figure width in pixels
107+
pwidth = self.canvas.figure.get_figwidth() * self.canvas.figure.get_dpi()
108+
# Scale size to match widget on HiDPI monitors.
109+
if hasattr(self.canvas, 'device_pixel_ratio'): # Matplotlib 3.5+
110+
width = pwidth / self.canvas.device_pixel_ratio
111+
else:
112+
width = pwidth / self.canvas._dpi_ratio
113+
data = "<img src='data:image/png;base64,{0}' width={1}/>"
114+
data = data.format(b64encode(buf.getvalue()).decode('utf-8'), width)
108115
display(HTML(data))
109116

110117
@default('toolitems')
@@ -283,10 +290,27 @@ def _repr_mimebundle_(self, **kwargs):
283290
buf = io.BytesIO()
284291
self.figure.savefig(buf, format='png', dpi='figure')
285292
self._data_url = b64encode(buf.getvalue()).decode('utf-8')
293+
# Figure width in pixels
294+
pwidth = self.figure.get_figwidth() * self.figure.get_dpi()
295+
# Scale size to match widget on HiDPI monitors.
296+
if hasattr(self, 'device_pixel_ratio'): # Matplotlib 3.5+
297+
width = pwidth / self.device_pixel_ratio
298+
else:
299+
width = pwidth / self._dpi_ratio
300+
html = """
301+
<div style="display: inline-block;">
302+
<div class="jupyter-widgets widget-label" style="text-align: center;">
303+
{}
304+
</div>
305+
<img src='data:image/png;base64,{}' width={}/>
306+
</div>
307+
""".format(
308+
self._figure_label, self._data_url, width
309+
)
286310

287311
data = {
288312
'text/plain': plaintext,
289-
'image/png': self._data_url,
313+
'text/html': html,
290314
'application/vnd.jupyter.widget-view+json': {
291315
'version_major': 2,
292316
'version_minor': 0,

0 commit comments

Comments
 (0)