The library nbinteract comes with a set of functions that produce Javascript-based plots designed for interaction. The package combines the ipywidgets library and the bqplot plotting library to implement function-driven interfaces to interactive plotting.
The nbinteract plotting methods use ipywidgets to generate and display widgets, inferring the widget type as needed. When a user interacts with a widget, a Python callback updates the visualization without a complete rerender. This noticeably lowers visualization update time compared to using ipywidgets alone to render static images.
Histogram
The widget nbinteract.hist
generates an interactive histogram that allows users to change the parameters of the input hist_function.
hist_function (Array | (*args -> Array int | Array float)):
Function that takes in parameters to interact with and returns an
array of numbers. These numbers will be plotted in the resulting
histogram.
import nbinteract as nbi
import numpy as np
def hist_response_function(mean, sd, size=1000):
'''
Returns 1000 values picked at random from the normal
distribution with the mean and SD given.
'''
return np.random.normal(loc=mean, scale=sd, size=1000)
nbi.hist(hist_response_function, mean=(0, 10), sd=(0, 2.0, 0.2))
Options
options (dict): Options for the plot. Available options:
title: Title of the plot
aspect_ratio: Aspect ratio of plot figure (float)
animation_duration: Duration of transition on change of data, in milliseconds.
xlabel: Label of the x-axis
ylabel: Label of the y-axis
xlim: Tuple containing (lower, upper) for x-axis
ylim: Tuple containing (lower, upper) for y-axis
bins: Non-negative int for the number of bins (default 10)
normalized: Normalize histogram area to 1 if True. If False, plot unmodified counts. (default True)
interact_params (dict): Keyword arguments in the same format as
`ipywidgets.interact`. One argument is required for each argument
of `hist_function`.
Bar chart
The widget nbinteract.bar
generates an interactive bar chart that allows users to change the parameters of the inputs x_fn and y_fn.
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for categories of bar chart.
If function, must take parameters to interact with and return an
array of strings or numbers. These will become the categories on
the x-axis of the bar chart.
y_fn (Array | (Array, *args -> Array int | Array float)):
If array, uses array values for heights of bars.
If function, must take in the output of x_fn as its first parameter
and optionally other parameters to interact with. Must return an
array of numbers. These will become the heights of the bars on the
y-axis.
import nbinteract as nbi
import numpy as np
def categories(n):
return np.arange(n)
def heights(xs, offset):
return xs + offset
opts = {
'ylim': (0, 20),
}
nbi.bar(categories, heights, n=(0, 10), offset=(1, 10), options=opts)
Options
options (dict): Options for the plot. Available options:
title: Title of the plot
aspect_ratio: Aspect ratio of plot figure (float)
animation_duration: Duration of transition on change of data, in milliseconds.
xlabel: Label of the x-axis
ylabel: Label of the y-axis
ylim: Tuple containing (lower, upper) for y-axis
interact_params (dict): Keyword arguments in the same format as
`ipywidgets.interact`. One argument is required for each argument
of both `x_fn` and `y_fn`. If `x_fn` and `y_fn` have conflicting
parameter names, prefix the corresponding kwargs with `x__` and
`y__`.
Interactive Scatter plot
The widget nbinteract.scatter_drag
generates an interactive scatter plot with the best fit line plotted over the points. The points can be dragged by the user and the line will automatically update.
x_points (Array Number): x-values of points to plot
y_points (Array Number): y-values of points to plot
import nbinteract as nbi
import numpy as np
x_coords = np.arange(10)
y_coords = np.arange(10) + np.random.rand(10)
opts = {'xlim': (0, 9), 'ylim': (0, 11), 'animation_duration': 250}
nbi.scatter_drag(x_coords, y_coords, options=opts)
Options
show_eqn (bool): If True (default), displays the best fit line's
equation above the scatterplot.
options (dict): Options for the plot. Available options:
title: Title of the plot
aspect_ratio: Aspect ratio of plot figure (float)
animation_duration: Duration of transition on change of data, in milliseconds.
xlabel: Label of the x-axis
ylabel: Label of the y-axis
xlim: Tuple containing (lower, upper) for x-axis
ylim: Tuple containing (lower, upper) for y-axis
Scatter
The widget nbinteract.scatter
generates an interactive scatter chart that allows users to change the parameters of the inputs x_fn and y_fn.
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordinates.
If function, must take parameters to interact with and return an
array of strings or numbers. These will become the x-coordinates
of the scatter plot.
y_fn (Array | (Array, *args -> Array int | Array float)):
If array, uses array values for y-coordinates.
If function, must take in the output of x_fn as its first parameter
and optionally other parameters to interact with. Must return an
array of numbers. These will become the y-coordinates of the
scatter plot.
import nbinteract as nbi
import numpy as np
def x_values(n): return np.random.choice(100, n)
def y_values(xs): return np.random.choice(100, len(xs))
nbi.scatter(x_values, y_values, n=(0,200))
Options
options (dict): Options for the plot. Available options:
title: Title of the plot
aspect_ratio: Aspect ratio of plot figure (float)
animation_duration: Duration of transition on change of data, in milliseconds.
xlabel: Label of the x-axis
ylabel: Label of the y-axis
xlim: Tuple containing (lower, upper) for x-axis
ylim: Tuple containing (lower, upper) for y-axis
marker: Shape of marker plots.
Possible values:
{"circle", "cross", "diamond", "square", "triangle-down", "triangle-up", "arrow", "rectangle", "ellipse"}
interact_params (dict): Keyword arguments in the same format as
`ipywidgets.interact`. One argument is required for each argument
of both `x_fn` and `y_fn`. If `x_fn` and `y_fn` have conflicting
parameter names, prefix the corresponding kwargs with `x__` and
`y__`.
Line
Generates an interactive line chart that allows users to change the parameters of the inputs x_fn
and y_fn
. The first two arguments of line
are response functions that return the x and y-axis coordinates.
Either argument can be arrays themselves. Arguments for the response functions must be passed in as keyword arguments to line in the format expected by interact. The response function for the y-coordinates will be called with the x-coordinates as its first argument.
import nbinteract as nbi
import numpy as np
def x_values(max): return np.arange(0, max)
def y_values(xs, sd):
return xs + np.random.normal(0, scale=sd, size=len(xs))
opts = {
'xlim': (0, 50),
'ylim': (0, 55),
'animation_duration': 250,
}
nbi.line(x_values, y_values, max=(10, 50), sd=(1, 10), options=opts)
nbinteract.line(x_fn, y_fn, *, options={}, **interact_params)
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordinates.
If function, must take parameters to interact with and return an
array of strings or numbers. These will become the x-coordinates
of the line plot.
y_fn (Array | (Array, *args -> Array int | Array float)):
If array, uses array values for y-coordinates.
If function, must take in the output of x_fn as its first parameter
and optionally other parameters to interact with. Must return an
array of numbers. These will become the y-coordinates of the line
plot.
Options
options (dict): Options for the plot. Available options:
title: Title of the plot
aspect_ratio: Aspect ratio of plot figure (float)
animation_duration: Duration of transition on change of data, in milliseconds.
xlabel: Label of the x-axis
ylabel: Label of the y-axis
xlim: Tuple containing (lower, upper) for x-axis
ylim: Tuple containing (lower, upper) for y-axis
interact_params (dict): Keyword arguments in the same format as
`ipywidgets.interact`. One argument is required for each argument
of both `x_fn` and `y_fn`. If `x_fn` and `y_fn` have conflicting
parameter names, prefix the corresponding kwargs with `x__` and
`y__`.
Multiple Choice
Generates a multiple choice question that allows the user to select an answer choice and shows whether choice was correct.
nbinteract.multiple_choice(question, choices, answers)
import nbinteract as nbi
nbi.multiple_choice(question="Select all prime numbers.",
choices=['12', '3', '31'],
answers=[1, 2])
Options
question (str): Question text displayed above choices.
choices (list str): Answer choices that user can select.
answers (int | iterable int): Either an integer or iterable of
integers. Each integer in answers corresponds to the index of the
correct choice in `choices`.
Short Answer
Generates a short answer question that allows user to input an answer in a textbox and a submit button to check the answer.
nbinteract.short_answer(question, answers, explanation=None)
import nbinteract as nbi
nbi.short_answer('What is 1+1?', answers='2', explanation='1+1 is 2')
Options
question (str): The question being asked.
answers (str | list str | func): If a string, only that string will be
marked correct. If a list of string, any string in the list will be
marked correct. If a function, any input that causes the function
to return True will be marked correct.
explanation (str): The explanation to the question is displayed when
the user inputs the correct answer.