ginput from matplotlib in JupyterLab does not work - python

According to
https://www.geeksforgeeks.org/matplotlib-pyplot-ginput-in-python/ the ginput function in Python is given by the following code:
%matplotlib widget
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(10)
plt.plot(t, np.sin(t))
plt.title('matplotlib.pyplot.ginput()\
function Example', fontweight ="bold")
print("After 3 clicks :")
x = plt.ginput(3)
print(x)
plt.show()
The only modification for jupyterlab that I inserted is the magic function
%matplotlib widget
at the beginning of the script. However, I do not get ginput() to work in Jupyterlab. It does not yield any errors, just no Figure appears, where I could click with the mouse. The output of ginput() accordingly is empty. In other Python IDE's, it works flawlessly (e.g. Thonny).
Did anybody get the ginput() function to work in Jupyterlab?

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()

Clearing all seaborn plots each time running the code in plots tab spyder IDE

I create some plots in one run of code, the plots are in plots tab. I tried to delete it all each time i rerun it but somehow the previous plots are still there not closing, it only creates new plots without clearing the previous plots from the previous run. I already tried to use plt.close('all') but it does not work. How do i clear all plots every time i rerun the code?
Here's my code
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
plt.close('all')
avo_sales = pd.read_csv('avocados.csv')
avo_sales.rename(columns = {'4046':'small Hass sold','4225':'large Hass sold','4770':'xlarge Hass sold'},
inplace= True)
for column in avo_sales.columns[2:11]:
sns.set()
fig, ax = plt.subplots()
sns.set(style="ticks")
sns.boxplot(column, data= avo_sales) # column is chosen here
sns.despine(offset=10, trim=True)
The images in the plots pane are handled by Spyder and are not reachable from the IPython console.
A simple solution would be to press the "remove images" icon before you re-run the code:
I don't know how to even get Spyder to put plots in the plot pane, but here's a few things that might work.
Try disabling some of the pane options:
Try some magic functions:
%reset - reset everything
%matplotlib - puts all plots inline with your code in the interactive window
%clear - clears the interactive window
Use IPython directly to help (via: https://gist.github.com/stsievert/8655158355b7155b2dd8):
from IPython import get_ipython
get_ipython().magic('reset -sf')

widget for function input is not shown in nbviewer

I've written a python module and would like to make some of the functions available via a jupyter notebook. For this I would like to visualise (plot) the functions. The notebook should be interactive, i.e. the user can change inputs and gets the corresponding result / plot back.
I've tried to make a use case work as I've never used jupyter before. I followed this. Here is the code from their site:
%matplotlib inline
from ipywidgets import interact
import matplotlib.pyplot as plt
import numpy as np
def f(m, b):
plt.figure(2)
x = np.linspace(-10, 10, num=1000)
plt.plot(x, m * x + b)
plt.ylim(-5, 5)
plt.show()
interactive_plot = interactive(f, m=(-2.0, 2.0), b=(-3, 3, 0.5))
output = interactive_plot.children[-1]
output.layout.height = '350px'
interactive_plot
locally everything is working fine. As soon as I upload it to github and want to show it on nbviewer (can be found here) the interactive sliders don't work. What am I doing wrong?
Is there a restriction for this on the python version?

Imagegrid in Jupyter notebook

I'm following an example from the matplotlib documentation on Imagegrid, and I'm trying to replicate it from within Jupyter notebook:
% matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
im = np.arange(100)
im.shape = 10, 10
fig = plt.figure(1, (4., 4.))
grid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols=(2, 2), # creates 2x2 grid of axes
axes_pad=0.1, # pad between axes in inch.
)
for i in range(4):
grid[i].imshow(im) # The AxesGrid object work as a list of axes.
plt.show()
Expected output:
What I'm getting:
I'm not getting the grid of images, as you can see. What am I doing wrong?
EDIT
If I remove the %matplotlib inline option, I just get this (it's cell[1] to prove I restarted my kernel):
No plots shown.
I'm running matplotlib version 3.0.0, checked with conda list matplotlib, jupyter is 4.4.0, checked with jupyter --version. On Windows 10, Anaconda, python 3.6.
This is an issue with matplotlib 3.0.0. This has now been fixed, such that it will not occur in the upcoming 3.0.1 bugfix release.
In the meantime you have two options.
Revert to matplotlib 2.2.3
Decide to not crop the images when using %matplotlib inline. Do so via
%config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
in IPython or Jupyter.
Remove
%matplotlib inline
and restart everything or put it in a separate cell as seen below. It appears that the magic command always needs to be run in a separate cell before the plotting and if it was run before the kernel needs to be restarted. See here
enter link description here
and it will work. %matplotlib inline is not necessary to render plots in jupyter it is just a convenience. plt.show() will render plots whenever it is called.
I have had this issue with some mpl in jupyter. I think the issue is that the magic command causes it to render any plot as soon as it is available as opposed to mpl which waits until it is told to render and how.
Full example code straight from the mpl example you linked in your question:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
im = np.arange(100)
im.shape = 10, 10
fig = plt.figure(1, (4., 4.))
grid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols=(2, 2), # creates 2x2 grid of axes
axes_pad=0.1, # pad between axes in inch.
)
for i in range(4):
grid[i].imshow(im) # The AxesGrid object work as a list of axes.
plt.show() # Renders all available axes when called

programming with matplotlib : plot() and draw()

I'm using python3 with matplotlib. I've encountered some issues with the pyplot.draw() function : no graphic window appears on my screen when I run my script.
The pyplot.plot() function works just fine :
#!/usr/bin/python3.2
#-*-coding:utf-8-*
from matplotlib import pyplot as plt
import numpy as np
plt.figure(1)
plt.plot(np.arange(35), np.arange(25),'r')
plt.show()
In this situation ./myscript.py displays the graphic window.
But when I try to make an simple animation :
import numpy as np
from matplotlib import pyplot as plt
from time import sleep
plt.ion()
nb_images = 1000
tableau = np.random.normal(10,10,(nb_images, 100, 100))
image = plt.imshow(tableau[0,:,:])
for k in np.arange(nb_images)
image.set_data(tableau[k,:,:])
print(k)
plt.draw()
sleep(0.1)
./myscript.py does the calculation (my terminal displays the "k" value) but the graphic window doesn't appear on my screen...
The problem is the same when I'm using python2.x
The backend in the configuration file "matplotlibrc" (python3.2) is "tkagg". I've already tried to change it but still no graphic window to admire my animation....
Thanks for you help.

Categories

Resources