@@ -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