Is it possible to store values from ipywidgets to cell code like Google colab Form - google-colaboratory

When I use Google Colab Form and change field value, new value stored in cell code. So next time I open notebook I see new value in cell.
How can I use same functionality for ipywidgets field?
For example.
Cell with Colab Form:
slices = 4 ##param {type:"slider", min:1, max:10, step:0}
Cell with ipywidget:
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
# interact() syntax
def f(x):
return x
interact(f, x=10);
# classic syntax
widgets.IntSlider(
value=7,
min=0,
max=10,
step=1,
description='Test:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='d'
)
In Google Colab Form changed slider value injects into cell code.
But I didn't find same functionality for ipywidgets. If I move slider - its new value will be lost on notebook reload.
Maybe some tricks exists for this?

Related

How to increase length of ouput table or dataframe in Jupyter Notebook?

I am working on the Jupyter notebook and have been facing issues in increasing the length of the output of the Jupyter Notebook. I can see the output as follows:
I tried increasing the default length of the columns in pandas with no success. Can you please help me with it?
If you were using the typical way to view a dataframe in Jupyter (see my puzzelment about your screenshot in my comments to your original post) it would be things like this:
adapted from answer to 'Pretty-print an entire Pandas Series / DataFrame'
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
display(df)
(Note that will work with the text-based viewing, too. Note it uses print(df) in the answer to 'Pretty-print an entire Pandas Series / DataFrame'.
Adjust the 'display.max_colwidth' if you want the entire column text to show:
with pd.option_context('display.max_rows', None, 'display.max_columns', None,'display.max_colwidth', -1):
display(df)
(If you prefer text like you posted, replace display() with print()
Generally with the solutions above the view window in Jupyter will get scrollbars so you can navigate to view all still.
You can also set the number of rows to show to be lower to save space, see example here.
You may also be interested in Pandas dataframe hide index functionality? or Using python / Jupyter Notebook, how to prevent row numbers from printing?.
As pointed out here, setting some some global options is covered in the Pandas Documentation for top-level options.
For display() to work these days you don't need to do anything extra. But if your are using old Jupyter or it doesn't work then try adding towards the top of your notebook file and running the following as a cell first:
from IPython.display import display

Google colab not displaying multiple graphs in a single cell

I am using Google Colab Notebook and this is my Code I am trying to display 2 graphs(one histogram 3rd line and other boxplot 4th line) but on output cell only boxplot graph is being rendered. Is it because I am using 2 different packages for rendering graphs in a single cell so only last graph rendering line will be rendered but both of these packages uses matplotlib as backend so I don't understand.
# housedf is a pandas dataframe
import seaborn as sns
plt.figure(figsize=(11, 8))
display(housedf.MSSubClass.hist(bins=50))
display(sns.boxplot(x=housedf.MSSubClass, y=housedf.SalePrice))
plt.show()

Different behaviour of ipywidgets.interactive_output() on Windows and macOS

I wanted to learn how to use interactive plots in Jupyter Notebook and created a script that updates a figure based on the current values of two sliders. The idea is simply that when the value of one of the sliders changes the figure should be updated.
This worked fine when I first ran the code on my Windows PC (using Windows 10). However, when I then ran the same code on my MacBook (using macOS Monterey 12.6.1), the figure is not updated but a new figure is created every time I change the value of one of my sliders.
Please find a MWE below:
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
%matplotlib widget
# Create two sliders
slider1 = widgets.IntSlider(value=4, min=0, max=10, step=1,
description='Slider1', continuous_update = False)
slider2 = widgets.IntSlider(value=8, min=0, max=10, step=1,
description='Slider2', continuous_update = False)
# Some function that plots the result based on the current values of the sliders
def plotResult(a, b):
plt.close('all')
plt.figure()
plt.hlines(a+b, xmin=0, xmax=10)
# Create interactive plot
interactive_plot = widgets.interactive_output(plotResult, {"a":slider1, "b":slider2})
ui = widgets.HBox([slider1, slider2])
display(ui, interactive_plot)
When I run the above code in a cell in my Jupyter Notebook, I get the following output:
(https://i.stack.imgur.com/NX02T.png).
When I now change any of the sliders, on Windows my figure is "updated in-place", while on macOS a new figure is created everytime (every figure newly created figure is labeled as 'Figure 1'). I don't understand why this is happening as I explicitly close all currently opening figures at the beginning of plotResults(a,b) by using the command plt.close('all').
I thought that since every newly created figure on macOS is labeled 'Figure 1' the problem could be that on macOS the cells are not refreshed. Thus, I additionally imported the module IPython using import IPython and then added the command IPython.display.clear_output(wait=True) after the first line of plotResults(a,b). However, this did not work and the problem persisted.
I also tried to use a different Matplotlib backend such as %matplotlib ipympl or %matplotlib nbagg instead of %matplotlib widget but this also did not help anything.

Jupyter-lab pyplot cell re-evaluation breaks interactive widget display

This code works as expected on a cleanly started kernel, but on re-executing the second cell, instead of an interactive widget (ipypml per https://matplotlib.org/3.3.0/users/interactive.html ), I get just the text output as in the image.
How are jupyter, jupyter-lab, widgets, pyplot, and matplotlib interacting to cause this problem?
And how do I properly do a plot so that I can re-execute the cell without re-starting the kernel?
Cell 0:
%matplotlib widget
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
Cell 1:
fig,ax = plt.subplots(num=0)
ax.plot(np.arange(4))
Cell 1 output:
[<matplotlib.lines.Line2D at 0x161b913a0>]
I found that I need to make sure the figure gets cleanly opened (or closed and re-opened) in each update. I had used the plt.subplots(num=0) option to keep repeated updates from creating new, non-displayed figures. (note that the 2nd cell in the screenshot has a been re-executed 5 times and has a [6] prefix)
plt.close(0)
fig,ax = plt.subplots(num=0)
ax.plot(np.arange(4))

How to add plot commands to a figure in more than one cell, but display it only in the end?

I want to do the following in a Jupyter Notebook:
Create a pyplot.figure in a cell;
For each subsequent cells, calculate values and plot them to that same figure without displaying anything;
At the end, in another cell, display the figure with the result of every previous plot command.
Currently, while using %matplotlib notebook, the figure is always displayed after the same cell it's been created, and I don't even call plt.show().
This is not the behavior I desire. Instead I would like to postpone the display of the figure for the last cell only, but the figure of course should contain the results of the sequential plot commands called in the cells in between.
You can capture the content of a cell of a jupyter notebook using the magic command %%capture. You can also hide any output of a specific line by putting a ; at the end of it.
Showing the figure can be done by simply typing the variable in which the figure is stored, e.g. fig.
Combining those techniques gives you
import matplotlib.pyplot as plt
%matplotlib notebook
%%capture captured
fig, ax=plt.subplots()
ax.plot([1,2,3]);
fig # now show the figure
which is probably more understandable in the acutal notebook like this:
Also see How to overlay plots from different cells?