Matplotlib didn’t show the plot - python

I don’t know why my matplotlib didn’t show plots, and no errors too. I thinks I missing something on its installation because when in IPython notebooks an QtIpython using %mayplotlib inline directive have no problems but when running from terminal or script didn’t show anything. Any ideas ??
for example, in QtIPython and Ipython notebook I run
%matplotlib inline
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
ax.plot([1,2,3,4,5,6,7,8,9,0],[2,3,4,5,6,7,8,9,0,11], '-r')
ax.grid()
plt.show()
and the plot shows Ok!
but in a simple script with
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
ax.plot([1,2,3,4,5,6,7,8,9,0],[2,3,4,5,6,7,8,9,0,11], '-r')
ax.grid()
plt.show()
didn’t show anything

If you use matplotlib inline in IPython notebook, the plots are shown automatically. If you plot things in a script you have to put a plt.show() at the end to actually show the figure. In the terminal you can also use plt.ion() to switch on intreactive mode.

Related

refresh matplotlib in Jupyter when updating with ipywidget

I want to draw a line in a Jupyter notebook, which can be moved using an ipywidget slider. I also want to have the mouse coordinates displayed, for which I'm using %matplotlib notebook. Here is what I have so far :
%matplotlib notebook
from ipywidgets import interact
fig, ax = plt.subplots()
#interact(n=(-200, 0))
def show(n):
# fig.clear() #doesn't show anything
y = -n+x
ax.plot(x, y)
plt.show()
When moving the line using the slider, the plot doesn't refresh, all previous positions of the line
remain visible:
I tried to refresh using fig.clear(), but then noting shows.
How can I solve this?
I have an extensive answer about this here: Matplotlib figure is not updating with ipywidgets slider
but the short of my recommendations are:
use ipympl %matplotlib ipympl instead of notebook as this will play nicer with ipywidgets
Use mpl-interactions to handle making plots controlled by sliders.
It will do the optimal thing of using set_data for you rather than clearing and replotting the lines.
It also interprets the shorthand for numbers in a way that (I think) makes more sense when making plots (e.g. using linspace instead of arange) see https://mpl-interactions.readthedocs.io/en/stable/comparison.html for more details.
So for your example I recommend doing:
install libraries
pip install ipympl mpl-interactions
%matplotlib ipympl
from ipywidgets import interact
import matplotlib.pyplot as plt
from mpl_interactions import ipyplot as iplt
x = np.linspace(0,100)
fig, ax = plt.subplots()
def y(x, n):
return x - n
ctrls = iplt.plot(x, y, n=(-200,0))
it got a bit longer because I added the imports you left out of your question and also defined x.
Which gives you this:
That said if you don't want to use those I think what you want is ax.cla() I think when you do fig.clear you are also removing the axes which is why nothing shows up.
%matplotlib notebook
from ipywidgets import interact
fig, ax = plt.subplots()
#interact(n=(-200, 0))
def show(n):
y = -n+x
ax.cla()
ax.plot(x, y)
plt.show()

how to draw empty plot on jupyter notebook instead address? [duplicate]

This question already has answers here:
How to make IPython notebook matplotlib plot inline
(11 answers)
Closed 4 years ago.
import matplotlib.pyplot as plt
%matplotlib inline
fig=plt.figure()
plt.show()
Output is:
matplotlib.figure.Figure at 0x536ea70
I want to see empty plot and i was going through a pycon tutorial the same code produced a empty plot.
IPython will not generate any output for figures that do not contain an axes.
If you add an axes to your figure, the figure will show fine.
%matplotlib inline
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
plt.show()
or
%matplotlib inline
import matplotlib.pyplot as plt
plt.gca()
plt.show()
If you then remove the axes, it will again show the returned python string again.
The solution to show a completely empty figure with the inline backend is hence to add an axes but then turn it invisible.
%matplotlib inline
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_visible(False)
plt.show()

How do you update inline images in Ipython?

Edit: My question is not in regards to an "animation" per se. My question here, is simply about how to continuously show, a new inline image, in a for loop, within an Ipython notebook.
In essence, I would like to show an updated image, at the same location, inline, and have it update within the loop to show. So my code currently looks something like this:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from IPython import display
%matplotlib inline
fig, ax = plt.subplots(nrows = 1, ncols = 1, figsize=(10, 10))
for ii in xrange(10):
im = np.random.randn(100,100)
ax.cla()
ax.imshow(im, interpolation='None')
ax.set_title(ii)
plt.show()
The problem is that this currently just..., well, shows the first image, and then it never changes.
Instead, I would like it to simply show the updated image at each iteration, inline, at the same place. How do I do that? Thanks.
I am not sure that you can do this without animation. Notebooks capture the output of matplotlib to include in the cell once the plotting is over. The animation framework is rather generic and covers anything that is not a static image. matplotlib.animation.FuncAnimation would probably do what you want.
I adapted your code as follows:
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation
f = plt.figure()
ax = f.gca()
im = np.random.randn(100,100)
image = plt.imshow(im, interpolation='None', animated=True)
def function_for_animation(frame_index):
im = np.random.randn(100,100)
image.set_data(im)
ax.set_title(str(frame_index))
return image,
ani = matplotlib.animation.FuncAnimation(f, function_for_animation, interval=200, frames=10, blit=True)
Note: You must restart the notebook for the %matplotlib notebook to take effect and use a backend that supports animation.
EDIT: There is normally a way that is closer to your original question but it errors on my computer. In the example animation_demo there is a plain "for loop" with a plt.pause(0.5) statement that should also work.
You can call figure.canvas.draw() each time you append something new to the figure. This will refresh the plot (from here). Try:
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from IPython import display
from time import sleep
fig = plt.figure()
ax = fig.gca()
fig.show()
for ii in range(10):
im = np.random.randn(100, 100)
plt.imshow(im, interpolation='None')
ax.set_title(ii)
fig.canvas.draw()
sleep(0.1)
I could not test this in an IPython Notebook, however.

pyplot plot freezes (not responding)

I am struggling with pyplot from the matlpotlib library. The figure freezes already when I try to create the plot:
plt.figure()
plt.ion()
ax1 = plt.subplot(211) #Here it freezes
plt.title('test', fontsize=8)
plt.xlim(-1700, 1700)
plt.ylabel('x-axis')
plt.xlabel('y-axis')
plt.grid()
plt.show()
...do something else
I have only worked with Pyqt plots, but this time I would like to solve my Problem without multithreading since I do not care if the plot stops my code for a short moment. The problem is, the script does not stop but continues to run and does not wait until the figure is completely created. (time.sleep() does not help). Is there a solution without threads?
Cheers,
James
Ps.: If I add a breakpoint after the code and run in debug mode, there is no Problem (obviously).
For me, it worked using:
import matplotlib
matplotlib.use('TkAgg')
Is this one working as you want it?
import matplotlib.pyplot as plt
plt.figure()
plt.ion()
ax1 = plt.subplot(211) #Here it freezes
plt.title('test', fontsize=8)
plt.xlim(-1700, 1700)
plt.ylabel('x-axis')
plt.xlabel('y-axis')
plt.grid()
plt.draw() # draw the plot
plt.pause(5) # show it for 5 seconds
print("Hallo") # continue doing other stuff
Using plt.clf is a simple addon to close figure after the plot is completed.
import matplotlib.pyplot as plt
plt.figure()
plt.ion()
ax1 = plt.subplot(211)
plt.title('test', fontsize=8)
plt.xlim(-1700, 1700)
plt.ylabel('x-axis')
plt.xlabel('y-axis')
plt.grid()
plt.show()
plt.clf() # Here is another path
fig = plt.figure() will cause the freeze for my PyQt5 as well.
I don't the exactly reasons but find nice workaround and works for me.
Workaround:
from matplotlib.Figure import Figure
fig1 = Figure()
ax1 = fig1.add_subplot()
You can find more examples from
https://pythonspot.com/pyqt5-matplotlib/

Jupyter, Interactive Matplotlib: Hide the toolbar of the interactive view

I am starting using the interactive plotting from Matplotlib:
%matplotlib notebook
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, figsize=(8, 3))
plt.plot([i for i in range (10)],np.random.randint(10, size=10))
plt.show()
Anyone knows if there is a way to hide the toolbars of the interactive mode?
I disabled the interactive mode buttons and toolbar with some python generated css.
Run the following in one of the notebook cells:
%%html
<style>
.output_wrapper button.btn.btn-default,
.output_wrapper .ui-dialog-titlebar {
display: none;
}
</style>
Unfortunately there's no good css selectors on the buttons, so I've tried to use as specific selector as possible, though this may end up disabling other buttons that you might generate in the output cell.
Indeed, this approach affects all output cells in the notebook.
Use the magic %matplotlib ipympl with canvas. toolbar_visible=False. To prevent double-appearence of figure, use plt. ioff() while instantiate figure:
import matplotlib.pyplot as plt
plt.ioff()
fig, ax = plt.subplots()
plt.ion()
fig.canvas.toolbar_visible = False
display(fig.canvas)
It's a little bit doubly, but so you know how to play with plt
Edit: Haven't mind you on jupyter. This works on jupyterlab

Categories

Resources