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).
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.
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'))
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:
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With