IPython supports 1x png and jpeg, and 2x png, but not 2x jpeg
Below registers a 2x jpeg display formatter for matplotlib figures.
In Jupyter, 'retina' display is really publishing metadata that the display width and height should be half the pixel width and height of the image.
from IPython import get_ipython
from IPython.core.display import _jpegxy
from IPython.core.pylabtools import print_figure
from matplotlib.figure import Figure
def retina_jpeg(figure):
"""Renderer for 2x jpeg images"""
jpeg_bytes = print_figure(figure, fmt="jpg")
w, h = _jpegxy(jpeg_bytes)
return (jpeg_bytes, {"width": w // 2, "height": h // 2})
def enable_retina_jpeg():
"""Tell IPython to use the 2x jpeg renderer"""
display_formatter = get_ipython().display_formatter
# disable any existing Figure formatters
[f.pop(Figure, None) for f in display_formatter.formatters.values()]
# register 2x jpg
jpg_formatter = display_formatter.formatters["image/jpeg"]
jpg_formatter.for_type(Figure, retina_jpeg)
Registering the jpeg output and setting dpi must be done after calling %matplotlib inline
which sets the same options.
from matplotlib import rcParams
%matplotlib inline
# select jpg, dpi after registering matplotlib backend
rcParams['figure.dpi'] = 200
enable_retina_jpeg()
Now we can do 2x jpg figures
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0, 10, 1000)
plt.plot(t, np.sin(5 * t))
[<matplotlib.lines.Line2D at 0x1350988e0>]