Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize / rescale a SVG graphic in an iPython / Jupyter Notebook?

I've a large SVG (.svg graphic) object to display in a iPython / Jupyter Notebook. In fact, I've a large neural network model graphic created with Keras to display.

from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot

SVG(model_to_dot(model,show_shapes=True).create(prog='dot', format='svg'))

So, I want to resize / rescale / shrink the SVG graphic to fit in my Notebook page (particularly horizontally, since the page width is limited).

like image 432
Claude COULOMBE Avatar asked Jul 21 '18 03:07

Claude COULOMBE


People also ask

How do I import an image into a Jupyter notebook?

Method 1: Direct insertion using the edit menu first, change the type of the cell to -> markdown. Step 2: After that click edit in the jupyter notebook menu. after that click 'insert image'. Edit -> insert image.


2 Answers

Another option is to use the "dpi" (dots per inch) property. A little hacky but this allowed me to shrink my SVG. Tensorflow: model_to_doc

    from IPython.display import SVG
    from keras.utils import model_to_dot

    SVG(model_to_dot(model, show_shapes= True, show_layer_names=True, dpi=65).create(prog='dot', format='svg'))
like image 62
Kristina Milkovich Avatar answered Sep 20 '22 16:09

Kristina Milkovich


A new improved solution particularly useful using spaCy, (tested with the version 2.2.4). In order to be able to scale the .svg without cropping, we must add a viewBox to the XML / HTML svg representation.

Before scaling:

enter image description here

import spacy
import re
from spacy import displacy

nlp_model = spacy.load("en_core_web_sm")
doc = nlp_model(u"To be or not to be, that is the question")
svg = displacy.render(doc,  style='dep', page=True, jupyter=False)

def add_viewbox_svg(svg):
    regex = r'class="displacy" width="([\d\.]*)" height="([\d\.]*)'
    match_results = re.findall(regex,svg)
    new_svg = svg.replace("<svg ","<svg viewBox='0 0 "+
                          match_results[0][0]+" "+
                          match_results[0][1]+
                          "' preserveAspectRatio='none' ")
    return new_svg

new_svg = add_viewbox_svg(svg)

Then using style:

style = "<style>svg{width:100% !important;height:100% !important;</style>"
display(HTML(style))
display(HTML(new_svg))

After scaling:

enter image description here

like image 22
Claude COULOMBE Avatar answered Sep 20 '22 16:09

Claude COULOMBE