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)?
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.
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()
Related
Here's a minimal example. It works perfectly in a Jupyter notebook, but when the html file is opened in a browser, clicking the plot produces no output.
If embed_minimal_html is called after the widget has been used in the Jupyter notebook several times and output is present, the same output will appear in the opened html file (without the black border for some reason), but additional clicks will not produce additional output.
import plotly.graph_objects as go
import ipywidgets as widgets
from ipywidgets.embed import embed_minimal_html
fig = go.FigureWidget(data=[go.Scatter(x=[1, 2], y=[1, 2])])
scatter = fig.data[0]
output = widgets.Output(layout={'border': '1px solid black'})
#scatter.on_click
def output_point(_, points, __):
with output:
print("Point: ({}, {})".format(points.xs[0], points.ys[0]))
minimal_onclick_widget = widgets.VBox([fig, output])
embed_minimal_html('minimal_onclick_widget.html', views=[minimal_onclick_widget], title="Minimal on_click widget")
minimal_onclick_widget
Any ideas what's going on, or how to fix it?
I think it might have something to do with server-side versus client-side event handling. The link and dlink widgets go through the Python kernel (server-side) and don't work in static html embeddings like the one above, but they have client-side alternatives jslink and jsdlink that do: https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Events.html#Linking-widgets-attributes-from-the-client-side. It's not stated explicitly in the docs, but maybe on_click is a server-side event with no client-side alternative.
I am writting a jupyter notebook in which at the begining I am creating a complex tab ipywidget for the user to select some inptus (see picture). I am wondering if there is any way to hide to the user the code cell that contains the code to create that widget.
I saw on this forum some questiosn about hiding code when exporting the notebook but in my case the user will access the j_notebook online. Just would like to avoid complexity by hiding some code cells
in module.py
import ipywidgets as ipyw
from IPython.display import display
button = ipyw.Button('Try this:')
out = ipyw.Output()
def print_it(button):
with out:
print('You clicked it')
button.on_click(print_it)
display(ipyw.VBox(children=[button, out]))
In your notebook:
import module
Good morning SO,
Setup :
Windows 7 (I know)
Sublime Text 3
Python 3.6
My problem :
I have some 28x28 images in a file, say one of them is at the relative path 'MyDir/myimage.png'
I'm trying to display the example image using the display module in the package IPython
from IPython.display import display,Image
img=Image(filename='MyDir/myimage.png')
display(img)
The problem is that instead of outputing the image in a figure, it only outputs the type of the object img in the console (display displays only in console).
Output :
<IPython.core.display.Image object>
Any ideas?
IPython (interactive python) won't work as expected in the console.
But in jupyter notebook, for instance, all goes well:
There's also qtconsole which sounds like it's just a more console-like jupyter notebook. I haven't checked it out, since between vscode and jupyter notebook, I've been fine thus far.
To learn more, you could search for comparisons between tools like jupyter and qt. And also take a look at the IPython docs. But if you just want the darn thing to show you an image, you could run your python script in jupyter or the like. Or use PIL as this answer to another question mentions.
Also, you could use matplotlib.pyplot to show images instead (this works in console and in jupyter):
from matplotlib.pyplot import figure, imshow, axis, show
from matplotlib.image import imread
import numpy as np
import os
imageDirectory = "c:\\some\\directory\\of\\images"
list_of_files = np.array(os.listdir(imageDirectory))[0:20] # just show the first 20 images
fig = figure()
number_of_files = len(list_of_files)
for i in range(number_of_files):
a=fig.add_subplot(1,number_of_files,i+1)
image = imread(os.path.join(imageDirectory, list_of_files[i]))
imshow(image,cmap='Greys_r')
axis('off')
show()
I have a cell that looks like this:
from IPython.display import Image
i = Image(filename='test.png')
i
print("test")
The output is just:
test
I don't see the image in the output. I checked to see that the file exists (anyway, if it did not exist, you get an error).
Any clues?
creating the image with
i = Image(filename='test.png')
only creates the object to display. Objects are displayed by one of two actions:
a direct call to IPython.display.display(obj), e.g.
from IPython.display import display
display(i)
the displayhook, which automatically displays the result of the cell, which is to say putting i on the last line of the cell. The lone i in your example doesn't display because it is not the last thing in the cell. So while this doesn't display the image:
i = Image(filename='test.png')
i
print("test")
This would:
i = Image(filename='test.png')
print("test")
i
I had the same problem.
Matplot lib expects to show figs outside the command line, for example in the GTK or QT.
Use this: get_ipython().magic(u'matplotlib inline')
It will enable inline backend for usage with IPython notebook.
See more here and here.
After looking into the code, I can say, that under Windows, as of IPython 7.1.0, this is only supported with %matplotlib inline, which does not work under the interactive IPython shell.
There is extra code in Jupyter. The following example works with
jupyter qtconsole
jupyter notebook
jupyter console in principle, but only via external program, and then for the example the temporary file got deleted
def test_display():
import pyx
c = pyx.canvas.canvas()
circle = pyx.path.circle(0, 0, 2)
c.stroke(circle, [pyx.style.linewidth.Thick,pyx.color.rgb.red])
return c
display(test_display())
I would like to customize matplotlib image display so that i can type control-c and it will copy the image to the clipboard so then i can copy it to openoffice spreadsheet to organize all of my raw data and image results. Is there any way to do this? Thanks!
If you're using the wx backend, FigureCanvasWxAgg has a Copy_to_Clipboard method you can use. You could bind the CTRL+C key event to call this method. For an example, see this sample code.
import matplotlib
import matplotlib.pyplot as plt
if not globals().has_key('__figure'):
__figure = matplotlib.pyplot.figure
def on_key(event):
print event
if event.key=='c':
#print event.canvas.__dict__#.Copy_to_Clipboard(event=event)
# print event.canvas._tkphoto.__dict__
plt.savefig("/tmp/fig.png")
def my_figure():
fig = __figure()
fig.canvas.mpl_connect('key_press_event',on_key)
return fig
matplotlib.pyplot.figure = my_figure
This works for tk backend, but i have no clue how to copy an image to a clipboard. For text, i can use xclip, but images dont work! And for some reason the wx backend doesnt work too well on ubuntu...