Created
February 7, 2021 15:18
-
-
Save letmaik/5eb19bc7a2c2cbdad6fc2fb725ecd0c1 to your computer and use it in GitHub Desktop.
Embed matplotlib svg plots as regular image in jupyter notebooks (with "Save as..." and automatic resize)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Jupyter Notebook content | |
import numpy as np | |
import matplotlib.pyplot as plt | |
import util | |
t = np.arange(0.0, 2.0, 0.01) | |
s = 1 + np.sin(2 * np.pi * t) | |
fig, ax = plt.subplots() | |
ax.plot(t, s) | |
ax.set(xlabel='time (s)', ylabel='voltage (mV)', | |
title='About as simple as it gets, folks') | |
ax.grid() | |
util.plt_svg() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Jupyter Notebook's SVG support inlines the SVG directly into the notebook website (without using <img>) | |
# and this prevents functionality like right-click "Save as ..." to save the image. | |
# It also causes the SVG to always show up in its full size, where non-SVG plots would be resized to fit | |
# and being enlarged with a double-click. | |
# The code below renders plots as SVG while keeping the functionality known from raster images. | |
# See sample_nb.py on how to use it. | |
import io | |
import base64 | |
def plt_svg(fig=None): | |
from IPython.display import HTML | |
if fig is None: | |
fig = plt.gcf() | |
f = io.BytesIO() | |
fig.savefig(f, format='svg', bbox_inches='tight') | |
plt.close(fig) | |
svg = f.getvalue() | |
svg_url = 'data:image/svg+xml;base64,' + base64.b64encode(svg).decode() | |
display(HTML(f'<img src="{svg_url}"></img>')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment