Display SVG in IPython notebook from a function

妖精的绣舞 提交于 2019-12-03 06:51:24

问题


In IPython notebook, the following code displays the SVG below the cell:

from IPython.display import SVG
SVG(url='http://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg')

The following displays nothing:

from IPython.display import SVG
def show_svg():
    SVG(url='http://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg')

Is there a way to display an SVG from within a function (or a class)?


回答1:


You need to display the SVG like

from IPython.display import SVG, display
def show_svg():
    display(SVG(url='http://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg'))

You first example works as the SVG object returns itself an is subsequently displayed by the IPython display machinery. As you want to create your SVG object in a custom method, you need to take care of the displaying.
The display call is similar to the ordinary print statement, but can handle different representations like images, html, latex, etc. For details have a look at the rich display documentation.




回答2:


Add return to your function :

from IPython.display import SVG
def show_svg():
    return SVG(url='http://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg')

Then call your functions as the last line in cell:

show_svg()


来源:https://stackoverflow.com/questions/30334385/display-svg-in-ipython-notebook-from-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!