How can I use the display() function in Microsoft Azure Notebook - python

I am unable to display the .png file created by pyplot. I created the file in Microsoft Azure Jupyter Notebook. os.listdir() returns xx.png, so I know that the file was created. Yet, display(Image("xx.png")) does not show the image. I have read about ten related posts on stackoverflow and tried numerous variations of the command, but nothing works.
When I reproduce the problem on my local computer it works fine.
This question is a re-write of a previous question that was marked as duplicate and left to die. I hope that this post will make the question easier to understand.
Following is the code used to create the file:
from IPython.display import display
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
y = [2,4,6,8,10,12,14,16,18,20]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
plt.title('Legend inside')
ax.legend()
fig.savefig('xx.png')

There are two ways given the code you have to show the image.
1) You can call %matplotlib inline at the top of the notebook. This will inline graphics and you will see the image by calling fig
2) You can from IPython.display import Image and Image('xx.png') and the image should be displayed.

It appears you are missing an import statement, try :
from Ipython.display import Image
display(Image("xx.png"))

Related

Question on data exchange between libsora and matplotlib.pyplot

In order to save a wave spectrum image, a typical code is as following,
###########################
import matplotlib.pyplot as plt
import librosa.display
y, sr = librosa.load(filename)
fig = plt.Figure()
canvas = FigureCanvas(fig)
...
librosa.display.specshow(logmelspec, sr=sample_rate, x_axis='time', y_axis='log')
fig.savefig('spec.png')
The question is, 'fig' is created in Figure class, and is also a parameter for FigureCanvas, librosa.display.specshow is a function belong to librosa.display class.
How does fig know the input data for fig.savefig ?
How does the data exchange work between 'fig' and 'librosa'?
When I run this code, it did save the right image as expected(however, if I build a FileDialog based application, load a new wav file and call 'fig.savefig' again, the image will become random).
It seems the following way can fix this issue,
plt.savefig("spec.png")
plt.clf()
plt.close()

Suppress display of final frame in matplotlib animation in jupyter

I am working on a project that involves generating a matplotlib animation using pyplot.imshow for the frames. I am doing this in a jupyter notebook. I have managed to get it working, but there is one annoying bug (or feature?) left. After the animation is created, Jupyter shows the last frame of the animation in the output cell. I would like the output to include the animation, captured as html, but not this final frame. Here is a simple example:
import numpy as np
from matplotlib import animation
from IPython.display import HTML
grid = np.zeros((10,10),dtype=int)
fig1 = plt.figure(figsize=(8,8))
ax1 = fig1.add_subplot(1,1,1)
def animate(i):
grid[i,i]=1
ax1.imshow(grid)
return
ani = animation.FuncAnimation(fig1, animate,frames=10);
html = HTML(ani.to_jshtml())
display(html)
I can use the capture magic, but that suppresses everything. This would be OK, but my final goal is to make this public, via binder, and make it as simple as possible for students to use.
I have seen matplotlib animations on the web that don't seem to have this problems, but those used plot, rather than imshow, which might be an issue.
Any suggestions would be greatly appreciated.
Thanks,
David
That's the answer I got from the same thing I was looking for in 'jupyter lab'. Just add plt.close().
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from IPython.display import HTML
grid = np.zeros((10,10),dtype=int)
fig1 = plt.figure(figsize=(8,8))
ax1 = fig1.add_subplot(1,1,1)
def animate(i):
grid[i,i]=1
ax1.imshow(grid)
return
ani = animation.FuncAnimation(fig1, animate,frames=10);
html = HTML(ani.to_jshtml())
display(html)
plt.close() # update

Create Multipage PDF in matplotlib without drawing figure on desktop

In the following example code...
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
with PdfPages('multipage_pdf.pdf') as pdf:
for i in range(10):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter([0, 1, 2], [0, 1, 2])
pdf.savefig()
plt.close()
... every single plot pops up a windows with the actual canvas. Is there an elegant solution to skip the actual drawing of the canvas on the screen and draw the plot directly into a multipage pdf?
PS: Problem only caused when running code within spyder, so related to spyder and not to anything else. Running code directly using python does not cause this popping up of windows.
I think what you are looking for is to clear the figure.
first_page = plt.figure(figsize=(11.69, 8.27))
first_page.clf()
Check out the documentation:
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.clf.html
Some examples:
https://www.programcreek.com/python/example/102298/matplotlib.pyplot.clf
The problem did not arise from matplotlib or anything similar, but just running the code from within Spyder caused this problem. Running the code using python directly does not cause the issues I had before.

Python Animation

I tried to program something similar to what the person in this thread programed: Matplotlib Animation
His code does work for me very fine considering the proposed fix but when I tried to program something similar the animation somehow does not work in jupyter notebook for me. (If I download it as a .py it works fine)
I think its very weird that it works as a .py but not in jupyter, especially considering that the code example in the link above also does work in jupyter notebook for me.
My code is the following: (of course there are functions missing which produce the variables "time" and "inputs[b,t,x,y,z]")
%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
def plot_fig():
global time, inputs
fig = plt.figure("Animation")
img = []
for i in range(time):
img.append([plt.imshow(inputs[1,i,:,:,0])])
anim = animation.ArtistAnimation(fig, img, interval = 25, blit=True, repeat_delay = 0)
plt.show()
Somehow I only get a static picture of inputs[1,0,:,:,0] in jupyter notebook.
I do not get any errors.
Does anyone have an idea why?
Thanks for any help!
Edit:
this code which creates random matrices does somehow work for me as well.
Very weird considering the inputs matrix in the code above has the right dimensions and the right content.
%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
time = 100
fig = plt.figure("Animation")
img = []
for i in range(time):
inputs = np.random.rand(10,10)
img.append([plt.imshow(inputs)])
anim = animation.ArtistAnimation(fig, img, interval = 25, blit=True, repeat_delay = 0)
plt.show()

I've got some problems of iteration with my animation function (matplotlib.animation/Python)

I'm trying to create an animated histogram for work, using matplotlib.animation, but animation.FuncAnimation is not functioning properly : when using this code, that i found on the official documentation,
"""
A simple example of an animated plot
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
def animate(i):
print(i)
line.set_ydata(np.sin(x + i/10.0)) # update the data
return line,
# Init only required for blitting to give a clean slate.
def init():
line.set_ydata(np.ma.array(x, mask=True))
return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200),init_func=init,interval=25, blit=True)
plt.show()
I get as final result the graph created by init() function (an empty graph also), but no animate iterations. Furthermore, I tested other codes, which practically gave me the same result : i get the initialization, or the first frame, but not more. matplotlib and matplotlib.animation are installed, everything seems to be ok, except it doesn't work. Have someone an idea how to fix it ? (Thank you in advance :) !)
I had the same issue working with Jupyter notebook and I solved it by inserting the line
%matplotlib notebook
in the code.
It may be that IPython inside your Spyder is configured to automatically use the inline backend. This would show your plots inside the console as png images. Of course png images cannot be animated.
I would suggest not to use IPython but execute the script in a dedicated Python console. In Spyder, go to Run/Configure.. and set the option to new dedicated Python console.

Categories