Skip to content
Snippets Groups Projects
Commit 22c8cdef authored by Paul McCarthy's avatar Paul McCarthy :mountain_bicyclist:
Browse files

Merge branch 'mnt/use-conda' into 'master'

Use conda to install additional packages

See merge request !34
parents 59c060e4 5aa5ab09
No related branches found
No related tags found
1 merge request!34Use conda to install additional packages
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# `bokeh` # `bokeh`
[`bokeh`](https://docs.bokeh.org/en/latest/index.html) is a Python library for creating interactive visualizations for modern web browsers. `bokeh` allows you to create these interactive web-based plots without having to code in javascript. [`bokeh`](https://docs.bokeh.org/en/latest/index.html) is a Python library for creating interactive visualizations for modern web browsers. `bokeh` allows you to create these interactive web-based plots without having to code in javascript.
`bokeh` has excellent documentation: https://docs.bokeh.org/en/latest/index.html `bokeh` has excellent documentation: https://docs.bokeh.org/en/latest/index.html
This notebook is not intended to instruct you how to use `bokeh`. Instead it pulls together interesting examples from the `bokeh` documentation into a single notebook to give you a taster of what can be done with `bokeh`. This notebook is not intended to instruct you how to use `bokeh`. Instead it pulls together interesting examples from the `bokeh` documentation into a single notebook to give you a taster of what can be done with `bokeh`.
## Install `bokeh` ## Install `bokeh`
`bokeh` is not installed in the `fslpython` environment so you will need to install it to run this notebook (e.g. `pip install bokeh`) `bokeh` is not installed in the `fslpython` environment so you will need to install it to run this notebook (e.g. `$FSLDIR/bin/conda install bokeh`)
Setup bokeh to work in this notebook: Setup bokeh to work in this notebook:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from bokeh.plotting import figure, output_file, show from bokeh.plotting import figure, output_file, show
from bokeh.io import output_notebook from bokeh.io import output_notebook
output_notebook() output_notebook()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Fetch some sampledata for the examples: Fetch some sampledata for the examples:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from bokeh import sampledata from bokeh import sampledata
sampledata.download() sampledata.download()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Scatter Plots ## Scatter Plots
https://docs.bokeh.org/en/latest/docs/gallery/iris.html https://docs.bokeh.org/en/latest/docs/gallery/iris.html
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from bokeh.sampledata.iris import flowers from bokeh.sampledata.iris import flowers
colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'} colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'}
colors = [colormap[x] for x in flowers['species']] colors = [colormap[x] for x in flowers['species']]
p = figure(title = "Iris Morphology") p = figure(title = "Iris Morphology")
p.xaxis.axis_label = 'Petal Length' p.xaxis.axis_label = 'Petal Length'
p.yaxis.axis_label = 'Petal Width' p.yaxis.axis_label = 'Petal Width'
p.circle(flowers["petal_length"], flowers["petal_width"], p.circle(flowers["petal_length"], flowers["petal_width"],
color=colors, fill_alpha=0.2, size=10) color=colors, fill_alpha=0.2, size=10)
# output_file("iris.html", title="iris.py example") # output_file("iris.html", title="iris.py example")
show(p) show(p)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Line Plots ## Line Plots
https://docs.bokeh.org/en/latest/docs/gallery/box_annotation.html https://docs.bokeh.org/en/latest/docs/gallery/box_annotation.html
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from bokeh.models import BoxAnnotation from bokeh.models import BoxAnnotation
from bokeh.sampledata.glucose import data from bokeh.sampledata.glucose import data
TOOLS = "pan,wheel_zoom,box_zoom,reset,save" TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
data = data.loc['2010-10-04':'2010-10-04'] data = data.loc['2010-10-04':'2010-10-04']
p = figure(x_axis_type="datetime", tools=TOOLS, title="Glocose Readings, Oct 4th (Red = Outside Range)") p = figure(x_axis_type="datetime", tools=TOOLS, title="Glocose Readings, Oct 4th (Red = Outside Range)")
p.background_fill_color = "#efefef" p.background_fill_color = "#efefef"
p.xgrid.grid_line_color=None p.xgrid.grid_line_color=None
p.xaxis.axis_label = 'Time' p.xaxis.axis_label = 'Time'
p.yaxis.axis_label = 'Value' p.yaxis.axis_label = 'Value'
p.line(data.index, data.glucose, line_color='grey') p.line(data.index, data.glucose, line_color='grey')
p.circle(data.index, data.glucose, color='grey', size=1) p.circle(data.index, data.glucose, color='grey', size=1)
p.add_layout(BoxAnnotation(top=80, fill_alpha=0.1, fill_color='red', line_color='red')) p.add_layout(BoxAnnotation(top=80, fill_alpha=0.1, fill_color='red', line_color='red'))
p.add_layout(BoxAnnotation(bottom=180, fill_alpha=0.1, fill_color='red', line_color='red')) p.add_layout(BoxAnnotation(bottom=180, fill_alpha=0.1, fill_color='red', line_color='red'))
show(p) show(p)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Bar Charts # Bar Charts
https://docs.bokeh.org/en/latest/docs/gallery/bar_stacked.html https://docs.bokeh.org/en/latest/docs/gallery/bar_stacked.html
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from bokeh.palettes import Spectral5 from bokeh.palettes import Spectral5
from bokeh.sampledata.autompg import autompg_clean as df from bokeh.sampledata.autompg import autompg_clean as df
from bokeh.transform import factor_cmap from bokeh.transform import factor_cmap
df.cyl = df.cyl.astype(str) df.cyl = df.cyl.astype(str)
df.yr = df.yr.astype(str) df.yr = df.yr.astype(str)
group = df.groupby(['cyl', 'mfr']) group = df.groupby(['cyl', 'mfr'])
index_cmap = factor_cmap('cyl_mfr', palette=Spectral5, factors=sorted(df.cyl.unique()), end=1) index_cmap = factor_cmap('cyl_mfr', palette=Spectral5, factors=sorted(df.cyl.unique()), end=1)
p = figure(plot_width=800, plot_height=500, title="Mean MPG by # Cylinders and Manufacturer", p = figure(plot_width=800, plot_height=500, title="Mean MPG by # Cylinders and Manufacturer",
x_range=group, toolbar_location=None, tooltips=[("MPG", "@mpg_mean"), ("Cyl, Mfr", "@cyl_mfr")]) x_range=group, toolbar_location=None, tooltips=[("MPG", "@mpg_mean"), ("Cyl, Mfr", "@cyl_mfr")])
p.vbar(x='cyl_mfr', top='mpg_mean', width=1, source=group, p.vbar(x='cyl_mfr', top='mpg_mean', width=1, source=group,
line_color="white", fill_color=index_cmap, ) line_color="white", fill_color=index_cmap, )
p.y_range.start = 0 p.y_range.start = 0
p.x_range.range_padding = 0.05 p.x_range.range_padding = 0.05
p.xgrid.grid_line_color = None p.xgrid.grid_line_color = None
p.xaxis.axis_label = "Manufacturer grouped by # Cylinders" p.xaxis.axis_label = "Manufacturer grouped by # Cylinders"
p.xaxis.major_label_orientation = 1.2 p.xaxis.major_label_orientation = 1.2
p.outline_line_color = None p.outline_line_color = None
show(p) show(p)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Distribution Plots # Distribution Plots
https://docs.bokeh.org/en/latest/docs/gallery/histogram.html https://docs.bokeh.org/en/latest/docs/gallery/histogram.html
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import numpy as np import numpy as np
import scipy.special import scipy.special
from bokeh.layouts import gridplot from bokeh.layouts import gridplot
def make_plot(title, hist, edges, x, pdf, cdf): def make_plot(title, hist, edges, x, pdf, cdf):
p = figure(title=title, tools='', background_fill_color="#fafafa") p = figure(title=title, tools='', background_fill_color="#fafafa")
p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],
fill_color="navy", line_color="white", alpha=0.5) fill_color="navy", line_color="white", alpha=0.5)
p.line(x, pdf, line_color="#ff8888", line_width=4, alpha=0.7, legend_label="PDF") p.line(x, pdf, line_color="#ff8888", line_width=4, alpha=0.7, legend_label="PDF")
p.line(x, cdf, line_color="orange", line_width=2, alpha=0.7, legend_label="CDF") p.line(x, cdf, line_color="orange", line_width=2, alpha=0.7, legend_label="CDF")
p.y_range.start = 0 p.y_range.start = 0
p.legend.location = "center_right" p.legend.location = "center_right"
p.legend.background_fill_color = "#fefefe" p.legend.background_fill_color = "#fefefe"
p.xaxis.axis_label = 'x' p.xaxis.axis_label = 'x'
p.yaxis.axis_label = 'Pr(x)' p.yaxis.axis_label = 'Pr(x)'
p.grid.grid_line_color="white" p.grid.grid_line_color="white"
return p return p
# Normal Distribution # Normal Distribution
mu, sigma = 0, 0.5 mu, sigma = 0, 0.5
measured = np.random.normal(mu, sigma, 1000) measured = np.random.normal(mu, sigma, 1000)
hist, edges = np.histogram(measured, density=True, bins=50) hist, edges = np.histogram(measured, density=True, bins=50)
x = np.linspace(-2, 2, 1000) x = np.linspace(-2, 2, 1000)
pdf = 1/(sigma * np.sqrt(2*np.pi)) * np.exp(-(x-mu)**2 / (2*sigma**2)) pdf = 1/(sigma * np.sqrt(2*np.pi)) * np.exp(-(x-mu)**2 / (2*sigma**2))
cdf = (1+scipy.special.erf((x-mu)/np.sqrt(2*sigma**2)))/2 cdf = (1+scipy.special.erf((x-mu)/np.sqrt(2*sigma**2)))/2
p1 = make_plot("Normal Distribution (μ=0, σ=0.5)", hist, edges, x, pdf, cdf) p1 = make_plot("Normal Distribution (μ=0, σ=0.5)", hist, edges, x, pdf, cdf)
# Log-Normal Distribution # Log-Normal Distribution
mu, sigma = 0, 0.5 mu, sigma = 0, 0.5
measured = np.random.lognormal(mu, sigma, 1000) measured = np.random.lognormal(mu, sigma, 1000)
hist, edges = np.histogram(measured, density=True, bins=50) hist, edges = np.histogram(measured, density=True, bins=50)
x = np.linspace(0.0001, 8.0, 1000) x = np.linspace(0.0001, 8.0, 1000)
pdf = 1/(x* sigma * np.sqrt(2*np.pi)) * np.exp(-(np.log(x)-mu)**2 / (2*sigma**2)) pdf = 1/(x* sigma * np.sqrt(2*np.pi)) * np.exp(-(np.log(x)-mu)**2 / (2*sigma**2))
cdf = (1+scipy.special.erf((np.log(x)-mu)/(np.sqrt(2)*sigma)))/2 cdf = (1+scipy.special.erf((np.log(x)-mu)/(np.sqrt(2)*sigma)))/2
p2 = make_plot("Log Normal Distribution (μ=0, σ=0.5)", hist, edges, x, pdf, cdf) p2 = make_plot("Log Normal Distribution (μ=0, σ=0.5)", hist, edges, x, pdf, cdf)
# Gamma Distribution # Gamma Distribution
k, theta = 7.5, 1.0 k, theta = 7.5, 1.0
measured = np.random.gamma(k, theta, 1000) measured = np.random.gamma(k, theta, 1000)
hist, edges = np.histogram(measured, density=True, bins=50) hist, edges = np.histogram(measured, density=True, bins=50)
x = np.linspace(0.0001, 20.0, 1000) x = np.linspace(0.0001, 20.0, 1000)
pdf = x**(k-1) * np.exp(-x/theta) / (theta**k * scipy.special.gamma(k)) pdf = x**(k-1) * np.exp(-x/theta) / (theta**k * scipy.special.gamma(k))
cdf = scipy.special.gammainc(k, x/theta) cdf = scipy.special.gammainc(k, x/theta)
p3 = make_plot("Gamma Distribution (k=7.5, θ=1)", hist, edges, x, pdf, cdf) p3 = make_plot("Gamma Distribution (k=7.5, θ=1)", hist, edges, x, pdf, cdf)
# Weibull Distribution # Weibull Distribution
lam, k = 1, 1.25 lam, k = 1, 1.25
measured = lam*(-np.log(np.random.uniform(0, 1, 1000)))**(1/k) measured = lam*(-np.log(np.random.uniform(0, 1, 1000)))**(1/k)
hist, edges = np.histogram(measured, density=True, bins=50) hist, edges = np.histogram(measured, density=True, bins=50)
x = np.linspace(0.0001, 8, 1000) x = np.linspace(0.0001, 8, 1000)
pdf = (k/lam)*(x/lam)**(k-1) * np.exp(-(x/lam)**k) pdf = (k/lam)*(x/lam)**(k-1) * np.exp(-(x/lam)**k)
cdf = 1 - np.exp(-(x/lam)**k) cdf = 1 - np.exp(-(x/lam)**k)
p4 = make_plot("Weibull Distribution (λ=1, k=1.25)", hist, edges, x, pdf, cdf) p4 = make_plot("Weibull Distribution (λ=1, k=1.25)", hist, edges, x, pdf, cdf)
show(gridplot([p1,p2,p3,p4], ncols=2, plot_width=400, plot_height=400, toolbar_location=None)) show(gridplot([p1,p2,p3,p4], ncols=2, plot_width=400, plot_height=400, toolbar_location=None))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Boxplot # Boxplot
https://docs.bokeh.org/en/latest/docs/gallery/boxplot.html https://docs.bokeh.org/en/latest/docs/gallery/boxplot.html
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import numpy as np import numpy as np
import pandas as pd import pandas as pd
# generate some synthetic time series for six different categories # generate some synthetic time series for six different categories
cats = list("abcdef") cats = list("abcdef")
yy = np.random.randn(2000) yy = np.random.randn(2000)
g = np.random.choice(cats, 2000) g = np.random.choice(cats, 2000)
for i, l in enumerate(cats): for i, l in enumerate(cats):
yy[g == l] += i // 2 yy[g == l] += i // 2
df = pd.DataFrame(dict(score=yy, group=g)) df = pd.DataFrame(dict(score=yy, group=g))
# find the quartiles and IQR for each category # find the quartiles and IQR for each category
groups = df.groupby('group') groups = df.groupby('group')
q1 = groups.quantile(q=0.25) q1 = groups.quantile(q=0.25)
q2 = groups.quantile(q=0.5) q2 = groups.quantile(q=0.5)
q3 = groups.quantile(q=0.75) q3 = groups.quantile(q=0.75)
iqr = q3 - q1 iqr = q3 - q1
upper = q3 + 1.5*iqr upper = q3 + 1.5*iqr
lower = q1 - 1.5*iqr lower = q1 - 1.5*iqr
# find the outliers for each category # find the outliers for each category
def outliers(group): def outliers(group):
cat = group.name cat = group.name
return group[(group.score > upper.loc[cat]['score']) | (group.score < lower.loc[cat]['score'])]['score'] return group[(group.score > upper.loc[cat]['score']) | (group.score < lower.loc[cat]['score'])]['score']
out = groups.apply(outliers).dropna() out = groups.apply(outliers).dropna()
# prepare outlier data for plotting, we need coordinates for every outlier. # prepare outlier data for plotting, we need coordinates for every outlier.
if not out.empty: if not out.empty:
outx = list(out.index.get_level_values(0)) outx = list(out.index.get_level_values(0))
outy = list(out.values) outy = list(out.values)
p = figure(tools="", background_fill_color="#efefef", x_range=cats, toolbar_location=None) p = figure(tools="", background_fill_color="#efefef", x_range=cats, toolbar_location=None)
# if no outliers, shrink lengths of stems to be no longer than the minimums or maximums # if no outliers, shrink lengths of stems to be no longer than the minimums or maximums
qmin = groups.quantile(q=0.00) qmin = groups.quantile(q=0.00)
qmax = groups.quantile(q=1.00) qmax = groups.quantile(q=1.00)
upper.score = [min([x,y]) for (x,y) in zip(list(qmax.loc[:,'score']),upper.score)] upper.score = [min([x,y]) for (x,y) in zip(list(qmax.loc[:,'score']),upper.score)]
lower.score = [max([x,y]) for (x,y) in zip(list(qmin.loc[:,'score']),lower.score)] lower.score = [max([x,y]) for (x,y) in zip(list(qmin.loc[:,'score']),lower.score)]
# stems # stems
p.segment(cats, upper.score, cats, q3.score, line_color="black") p.segment(cats, upper.score, cats, q3.score, line_color="black")
p.segment(cats, lower.score, cats, q1.score, line_color="black") p.segment(cats, lower.score, cats, q1.score, line_color="black")
# boxes # boxes
p.vbar(cats, 0.7, q2.score, q3.score, fill_color="#E08E79", line_color="black") p.vbar(cats, 0.7, q2.score, q3.score, fill_color="#E08E79", line_color="black")
p.vbar(cats, 0.7, q1.score, q2.score, fill_color="#3B8686", line_color="black") p.vbar(cats, 0.7, q1.score, q2.score, fill_color="#3B8686", line_color="black")
# whiskers (almost-0 height rects simpler than segments) # whiskers (almost-0 height rects simpler than segments)
p.rect(cats, lower.score, 0.2, 0.01, line_color="black") p.rect(cats, lower.score, 0.2, 0.01, line_color="black")
p.rect(cats, upper.score, 0.2, 0.01, line_color="black") p.rect(cats, upper.score, 0.2, 0.01, line_color="black")
# outliers # outliers
if not out.empty: if not out.empty:
p.circle(outx, outy, size=6, color="#F38630", fill_alpha=0.6) p.circle(outx, outy, size=6, color="#F38630", fill_alpha=0.6)
p.xgrid.grid_line_color = None p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = "white" p.ygrid.grid_line_color = "white"
p.grid.grid_line_width = 2 p.grid.grid_line_width = 2
p.xaxis.major_label_text_font_size="16px" p.xaxis.major_label_text_font_size="16px"
show(p) show(p)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Connectivity Matrix ## Connectivity Matrix
https://docs.bokeh.org/en/latest/docs/gallery/les_mis.html https://docs.bokeh.org/en/latest/docs/gallery/les_mis.html
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import numpy as np import numpy as np
from bokeh.sampledata.les_mis import data from bokeh.sampledata.les_mis import data
nodes = data['nodes'] nodes = data['nodes']
names = [node['name'] for node in sorted(data['nodes'], key=lambda x: x['group'])] names = [node['name'] for node in sorted(data['nodes'], key=lambda x: x['group'])]
N = len(nodes) N = len(nodes)
counts = np.zeros((N, N)) counts = np.zeros((N, N))
for link in data['links']: for link in data['links']:
counts[link['source'], link['target']] = link['value'] counts[link['source'], link['target']] = link['value']
counts[link['target'], link['source']] = link['value'] counts[link['target'], link['source']] = link['value']
colormap = ["#444444", "#a6cee3", "#1f78b4", "#b2df8a", "#33a02c", "#fb9a99", colormap = ["#444444", "#a6cee3", "#1f78b4", "#b2df8a", "#33a02c", "#fb9a99",
"#e31a1c", "#fdbf6f", "#ff7f00", "#cab2d6", "#6a3d9a"] "#e31a1c", "#fdbf6f", "#ff7f00", "#cab2d6", "#6a3d9a"]
xname = [] xname = []
yname = [] yname = []
color = [] color = []
alpha = [] alpha = []
for i, node1 in enumerate(nodes): for i, node1 in enumerate(nodes):
for j, node2 in enumerate(nodes): for j, node2 in enumerate(nodes):
xname.append(node1['name']) xname.append(node1['name'])
yname.append(node2['name']) yname.append(node2['name'])
alpha.append(min(counts[i,j]/4.0, 0.9) + 0.1) alpha.append(min(counts[i,j]/4.0, 0.9) + 0.1)
if node1['group'] == node2['group']: if node1['group'] == node2['group']:
color.append(colormap[node1['group']]) color.append(colormap[node1['group']])
else: else:
color.append('lightgrey') color.append('lightgrey')
data=dict( data=dict(
xname=xname, xname=xname,
yname=yname, yname=yname,
colors=color, colors=color,
alphas=alpha, alphas=alpha,
count=counts.flatten(), count=counts.flatten(),
) )
p = figure(title="Les Mis Occurrences", p = figure(title="Les Mis Occurrences",
x_axis_location="above", tools="hover,save", x_axis_location="above", tools="hover,save",
x_range=list(reversed(names)), y_range=names, x_range=list(reversed(names)), y_range=names,
tooltips = [('names', '@yname, @xname'), ('count', '@count')]) tooltips = [('names', '@yname, @xname'), ('count', '@count')])
p.plot_width = 800 p.plot_width = 800
p.plot_height = 800 p.plot_height = 800
p.grid.grid_line_color = None p.grid.grid_line_color = None
p.axis.axis_line_color = None p.axis.axis_line_color = None
p.axis.major_tick_line_color = None p.axis.major_tick_line_color = None
p.axis.major_label_text_font_size = "7px" p.axis.major_label_text_font_size = "7px"
p.axis.major_label_standoff = 0 p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = np.pi/3 p.xaxis.major_label_orientation = np.pi/3
p.rect('xname', 'yname', 0.9, 0.9, source=data, p.rect('xname', 'yname', 0.9, 0.9, source=data,
color='colors', alpha='alphas', line_color=None, color='colors', alpha='alphas', line_color=None,
hover_line_color='black', hover_color='colors') hover_line_color='black', hover_color='colors')
show(p) # show the plot show(p) # show the plot
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Sliders ## Sliders
https://docs.bokeh.org/en/latest/docs/gallery/slider.html https://docs.bokeh.org/en/latest/docs/gallery/slider.html
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import numpy as np import numpy as np
from bokeh.layouts import column, row from bokeh.layouts import column, row
from bokeh.models import CustomJS, Slider from bokeh.models import CustomJS, Slider
from bokeh.plotting import ColumnDataSource from bokeh.plotting import ColumnDataSource
x = np.linspace(0, 10, 500) x = np.linspace(0, 10, 500)
y = np.sin(x) y = np.sin(x)
source = ColumnDataSource(data=dict(x=x, y=y)) source = ColumnDataSource(data=dict(x=x, y=y))
plot = figure(y_range=(-10, 10), plot_width=400, plot_height=400) plot = figure(y_range=(-10, 10), plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
amp_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Amplitude") amp_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Amplitude")
freq_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Frequency") freq_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Frequency")
phase_slider = Slider(start=0, end=6.4, value=0, step=.1, title="Phase") phase_slider = Slider(start=0, end=6.4, value=0, step=.1, title="Phase")
offset_slider = Slider(start=-5, end=5, value=0, step=.1, title="Offset") offset_slider = Slider(start=-5, end=5, value=0, step=.1, title="Offset")
callback = CustomJS(args=dict(source=source, amp=amp_slider, freq=freq_slider, phase=phase_slider, offset=offset_slider), callback = CustomJS(args=dict(source=source, amp=amp_slider, freq=freq_slider, phase=phase_slider, offset=offset_slider),
code=""" code="""
const data = source.data; const data = source.data;
const A = amp.value; const A = amp.value;
const k = freq.value; const k = freq.value;
const phi = phase.value; const phi = phase.value;
const B = offset.value; const B = offset.value;
const x = data['x'] const x = data['x']
const y = data['y'] const y = data['y']
for (var i = 0; i < x.length; i++) { for (var i = 0; i < x.length; i++) {
y[i] = B + A*Math.sin(k*x[i]+phi); y[i] = B + A*Math.sin(k*x[i]+phi);
} }
source.change.emit(); source.change.emit();
""") """)
amp_slider.js_on_change('value', callback) amp_slider.js_on_change('value', callback)
freq_slider.js_on_change('value', callback) freq_slider.js_on_change('value', callback)
phase_slider.js_on_change('value', callback) phase_slider.js_on_change('value', callback)
offset_slider.js_on_change('value', callback) offset_slider.js_on_change('value', callback)
layout = row( layout = row(
plot, plot,
column(amp_slider, freq_slider, phase_slider, offset_slider), column(amp_slider, freq_slider, phase_slider, offset_slider),
) )
show(layout) show(layout)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# `nilearn` # `nilearn`
`nilearn` is a python package that provides **statistical** and **machine learning** tools for working with neuroimaging data. `nilearn` is a python package that provides **statistical** and **machine learning** tools for working with neuroimaging data.
According to https://nilearn.github.io/: According to https://nilearn.github.io/:
> >
> Nilearn enables approachable and versatile analyses of brain volumes. It provides **statistical** and **machine-learning** tools, with instructive documentation & open community. > Nilearn enables approachable and versatile analyses of brain volumes. It provides **statistical** and **machine-learning** tools, with instructive documentation & open community.
> >
> It supports general linear model (GLM) based analysis and leverages the scikit-learn Python toolbox for multivariate statistics with applications such as predictive modelling, classification, decoding, or connectivity analysis. > It supports general linear model (GLM) based analysis and leverages the scikit-learn Python toolbox for multivariate statistics with applications such as predictive modelling, classification, decoding, or connectivity analysis.
However, `nilearn` also provides a very convenient set of visualisation routines for neuroimaging data. This notebook will focus on these visualisation tools. However, `nilearn` also provides a very convenient set of visualisation routines for neuroimaging data. This notebook will focus on these visualisation tools.
`nilearn` has very good documentation, and the examples below borrow heavily from the visualisation documentation: https://nilearn.github.io/plotting/index.html `nilearn` has very good documentation, and the examples below borrow heavily from the visualisation documentation: https://nilearn.github.io/plotting/index.html
## This notebook ## This notebook
1. Plotting an anatomical image 1. Plotting an anatomical image
2. Plotting a statistical map 2. Plotting a statistical map
3. 2D maximum intensity projection 3. 2D maximum intensity projection
4. Surfaces 4. Surfaces
`nilearn` is not installed in the `fslpython` environment so you will need to install it to run this notebook (e.g. `pip install nilearn`) `nilearn` is not installed in the `fslpython` environment so you will need to install it to run this notebook (e.g. `$FSLDIR/bin/conda install nilearn`)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
First we will import the necessary packages for this notebook: First we will import the necessary packages for this notebook:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import os import os
from nilearn import plotting, datasets, surface from nilearn import plotting, datasets, surface
import matplotlib as mpl import matplotlib as mpl
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import nibabel as nb import nibabel as nb
%matplotlib inline %matplotlib inline
# get path to FSL installation for the FSLDIR environment variable # get path to FSL installation for the FSLDIR environment variable
FSLDIR = os.environ['FSLDIR'] FSLDIR = os.environ['FSLDIR']
## figure styling ## figure styling
mpl.rcParams['figure.dpi'] = 150 mpl.rcParams['figure.dpi'] = 150
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Plotting an anatomical image ## Plotting an anatomical image
In this section we will use `nilearn` to plot an anatomical volume. For these examples we will use the 1mm MNI152 T1w that is shipped with `FSL`. In these examples you will see different plotting layouts, as well as different styling options. In this section we will use `nilearn` to plot an anatomical volume. For these examples we will use the 1mm MNI152 T1w that is shipped with `FSL`. In these examples you will see different plotting layouts, as well as different styling options.
First we will use the `plot_anat` function (with default values) to plot the MNI152 T1w in an **ortho** view. First we will use the `plot_anat` function (with default values) to plot the MNI152 T1w in an **ortho** view.
> **NOTE:** > **NOTE:**
> 1. Here we use [`plot_anat`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_anat.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the orthographic images > 1. Here we use [`plot_anat`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_anat.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the orthographic images
> 2. Here we use python [f-strings](https://www.python.org/dev/peps/pep-0498/), formally known as literal string interpolation, which allow for easy formatting > 2. Here we use python [f-strings](https://www.python.org/dev/peps/pep-0498/), formally known as literal string interpolation, which allow for easy formatting
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_anat( plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz' f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Here we adjust the brightness of the image using the `dim` argument, and add a title to the plot with the `title` argument. Here we adjust the brightness of the image using the `dim` argument, and add a title to the plot with the `title` argument.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_anat( plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
dim=-0.5, dim=-0.5,
title='MNI T1 1mm' title='MNI T1 1mm'
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now we are going to use the `display_mode` argument to change to a **tiled** ortho view where the coronal and axial views are in a column, and the coronal and sagittal views are in a row. Now we are going to use the `display_mode` argument to change to a **tiled** ortho view where the coronal and axial views are in a column, and the coronal and sagittal views are in a row.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_anat( plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
dim=-0.5, dim=-0.5,
title='MNI T1 1mm', title='MNI T1 1mm',
display_mode='tiled' display_mode='tiled'
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now we are going to combine the `display_mode` and `cut_coords` arguments to create a row of 10 axial slices. Now we are going to combine the `display_mode` and `cut_coords` arguments to create a row of 10 axial slices.
Options for `display_mode` include: Options for `display_mode` include:
- `'x'` - sagittal - `'x'` - sagittal
- `'y'` - coronal - `'y'` - coronal
- `'z'` - axial - `'z'` - axial
- `'ortho'` - three cuts are performed in orthogonal directions - `'ortho'` - three cuts are performed in orthogonal directions
- `'tiled'` - three cuts are performed and arranged in a 2x2 grid - `'tiled'` - three cuts are performed and arranged in a 2x2 grid
In this instance, we give `cut_coords` a scalar integer that indicates the number of slices to show in the axial view. In this instance, we give `cut_coords` a scalar integer that indicates the number of slices to show in the axial view.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_anat( plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
dim=-0.5, dim=-0.5,
title='MNI T1 1mm', title='MNI T1 1mm',
display_mode='z', display_mode='z',
cut_coords=10 cut_coords=10
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
In the example below, a `display` object is returned by `plot_anat`. We can use this object to update/amend the plot. Here we add an overlay of the *HarvardOxford* atlas that ships with `FSL` to the image. In the example below, a `display` object is returned by `plot_anat`. We can use this object to update/amend the plot. Here we add an overlay of the *HarvardOxford* atlas that ships with `FSL` to the image.
We also use the `display` object to save the plot as a `*.png` image. We also use the `display` object to save the plot as a `*.png` image.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# plot MNI152 T1w and return display object # plot MNI152 T1w and return display object
display = plotting.plot_anat( display = plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
dim=-0.5, dim=-0.5,
title='MNI T1 1mm' title='MNI T1 1mm'
) )
# overlay the HarvardOxford atlas # overlay the HarvardOxford atlas
display.add_contours( display.add_contours(
f'{FSLDIR}/data/atlases/HarvardOxford/HarvardOxford-cort-maxprob-thr50-1mm.nii.gz', f'{FSLDIR}/data/atlases/HarvardOxford/HarvardOxford-cort-maxprob-thr50-1mm.nii.gz',
filled=True filled=True
) )
# save plot to file # save plot to file
display.savefig('myplot.png') display.savefig('myplot.png')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
`nilearn` plotting is built upon `matplotlib`, so we can use constructs from `matplotlib` to help us create more complex figures. `nilearn` plotting is built upon `matplotlib`, so we can use constructs from `matplotlib` to help us create more complex figures.
In this example we: In this example we:
1. create a 1x2 grid of subplots using `subplots` from `matplotlib` 1. create a 1x2 grid of subplots using `subplots` from `matplotlib`
2. plot a single slice of the MNI152 T1w in the first subplot using `plot_anat` from `nilearn` 2. plot a single slice of the MNI152 T1w in the first subplot using `plot_anat` from `nilearn`
3. plot a histogram of the intensities of the MNI152 T12 in the second subplot using `hist` from `matplotlib` 3. plot a histogram of the intensities of the MNI152 T12 in the second subplot using `hist` from `matplotlib`
4. style the histogram by setting the x/y labels 4. style the histogram by setting the x/y labels
> **NOTE:** Here we use `load` and `get_fdata` from the [`nibabel`](https://nipy.org/nibabel/) package to load the data from the MNI152 T1w nifti for the histogram. > **NOTE:** Here we use `load` and `get_fdata` from the [`nibabel`](https://nipy.org/nibabel/) package to load the data from the MNI152 T1w nifti for the histogram.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# create matplotlib figure with 1x2 subplots # create matplotlib figure with 1x2 subplots
fig, ax = plt.subplots(1, 2, figsize=(10, 5)) fig, ax = plt.subplots(1, 2, figsize=(10, 5))
# plot MNI T1w slice in first subplot # plot MNI T1w slice in first subplot
mni_t1 = f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz' mni_t1 = f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'
display = plotting.plot_anat( display = plotting.plot_anat(
mni_t1, mni_t1,
dim=-0.5, dim=-0.5,
axes=ax[0], axes=ax[0],
display_mode='z', display_mode='z',
cut_coords=[15] cut_coords=[15]
) )
# plot histogram of MNI T1w intensity in second subplot # plot histogram of MNI T1w intensity in second subplot
mni_t1_data = nb.load(mni_t1).get_fdata().ravel() mni_t1_data = nb.load(mni_t1).get_fdata().ravel()
ax[1].hist(mni_t1_data, bins=25) ax[1].hist(mni_t1_data, bins=25)
ax[1].set_ylabel('count') ax[1].set_ylabel('count')
ax[1].set_xlabel('intensity') ax[1].set_xlabel('intensity')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
> >
> **Exercise:** > **Exercise:**
> >
> Create a PNG figure that displays the same **Harvard-Oxford** parcellation, using a different colormap, and axial images in a 3x5 grid. > Create a PNG figure that displays the same **Harvard-Oxford** parcellation, using a different colormap, and axial images in a 3x5 grid.
> >
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# YOUR CODE HERE # YOUR CODE HERE
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Plotting a statistical map ## Plotting a statistical map
The examples in this section demonstrate how to plot a statistical map as an overlay on an anatomical image. Both images must be in the same space. The examples in this section demonstrate how to plot a statistical map as an overlay on an anatomical image. Both images must be in the same space.
First we will download a motor task statistical map from NeuroVault. First we will download a motor task statistical map from NeuroVault.
> **Note:** We use a method from [`nilearn`](https://nilearn.github.io/index.html) called [`fetch_neurovault_motor_task`](https://nilearn.github.io/modules/generated/nilearn.datasets.fetch_neurovault_motor_task.html) to download the statistical map. > **Note:** We use a method from [`nilearn`](https://nilearn.github.io/index.html) called [`fetch_neurovault_motor_task`](https://nilearn.github.io/modules/generated/nilearn.datasets.fetch_neurovault_motor_task.html) to download the statistical map.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
motor_images = datasets.fetch_neurovault_motor_task() motor_images = datasets.fetch_neurovault_motor_task()
stat_img = motor_images.images[0] stat_img = motor_images.images[0]
print(stat_img) print(stat_img)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now we can plot the statistical map as an overlay on the MNI152 T1w. We theshold the statistical map using the `threshold` argument. Now we can plot the statistical map as an overlay on the MNI152 T1w. We theshold the statistical map using the `threshold` argument.
> **NOTE:** Here we use [`plot_stat_map`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_stat_map.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the orthographic images > **NOTE:** Here we use [`plot_stat_map`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_stat_map.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the orthographic images
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_stat_map( plotting.plot_stat_map(
stat_img, stat_img,
threshold=3, threshold=3,
bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz' bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Like with the `plot_anat` examples earlier, we can style the plot and change the layout and views. Like with the `plot_anat` examples earlier, we can style the plot and change the layout and views.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_stat_map( plotting.plot_stat_map(
stat_img, stat_img,
threshold=3, threshold=3,
bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
display_mode='z', display_mode='z',
cut_coords=10, cut_coords=10,
title='motor-task', title='motor-task',
dim=-0.5, dim=-0.5,
vmax=10 vmax=10
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
In this next example we first find the coordinate of the centre of the largest connected component in the statistical map, then we plot an ortho view that is centred on this coordinate. In this next example we first find the coordinate of the centre of the largest connected component in the statistical map, then we plot an ortho view that is centred on this coordinate.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# find the coordinate of the centre of the largest connected component in the statistical map # find the coordinate of the centre of the largest connected component in the statistical map
coord = plotting.find_xyz_cut_coords(stat_img) coord = plotting.find_xyz_cut_coords(stat_img)
print(f'Center of the largest activation connected component = {coord}') print(f'Center of the largest activation connected component = {coord}')
# plot an ortho view that is centred on this coordinate # plot an ortho view that is centred on this coordinate
plotting.plot_stat_map( plotting.plot_stat_map(
stat_img, stat_img,
threshold=3, threshold=3,
bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
display_mode='ortho', display_mode='ortho',
cut_coords=coord, cut_coords=coord,
title='motor-task', title='motor-task',
dim=-0.5, dim=-0.5,
vmax=10 vmax=10
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
`nilearn` has some support for **interactive** viewing of volumetic images with the `view_img` function. Try clicking on the plot and moving the cursor around! `nilearn` has some support for **interactive** viewing of volumetic images with the `view_img` function. Try clicking on the plot and moving the cursor around!
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
view = plotting.view_img(stat_img, threshold=3) view = plotting.view_img(stat_img, threshold=3)
view # view interactive plot inline view # view interactive plot inline
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
view = plotting.view_img(stat_img, threshold=3) view = plotting.view_img(stat_img, threshold=3)
view.open_in_browser() # open interactive plot in new web browser view.open_in_browser() # open interactive plot in new web browser
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## 2D maximum intensity projection ## 2D maximum intensity projection
> Maximum intensity projection (MIP) is a method for 3D data that projects in the visualization plane the voxels with maximum intensity that fall in the way of parallel rays traced from the viewpoint to the plane of projection. https://en.wikipedia.org/wiki/Maximum_intensity_projection > Maximum intensity projection (MIP) is a method for 3D data that projects in the visualization plane the voxels with maximum intensity that fall in the way of parallel rays traced from the viewpoint to the plane of projection. https://en.wikipedia.org/wiki/Maximum_intensity_projection
`nilearn` can plot a maximum intensity projection overlayed on a brain schematic referred to as the "glass brain". In this example, the MIP of the motor task statistical map used in the previous examples is plotted on the glass brain. `nilearn` can plot a maximum intensity projection overlayed on a brain schematic referred to as the "glass brain". In this example, the MIP of the motor task statistical map used in the previous examples is plotted on the glass brain.
> **NOTE:** Here we use [`plot_glass_brain`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_glass_brain.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the maximum intensity projection. > **NOTE:** Here we use [`plot_glass_brain`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_glass_brain.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the maximum intensity projection.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_glass_brain( plotting.plot_glass_brain(
stat_img, stat_img,
title='2D max-intensity projection', title='2D max-intensity projection',
threshold=3, threshold=3,
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Surfaces ## Surfaces
`nilearn` has baked in functionality to project a volumetric image onto the surface and visualise it. `nilearn` has baked in functionality to project a volumetric image onto the surface and visualise it.
Here we visualise the same volumetric motor task statistical map, from earlier examples, on the inflated surface. Here we visualise the same volumetric motor task statistical map, from earlier examples, on the inflated surface.
> **NOTE:** Here we use [`plot_img_on_surf`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_img_on_surf.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the volumetric statistical map on the surface. > **NOTE:** Here we use [`plot_img_on_surf`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_img_on_surf.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the volumetric statistical map on the surface.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_img_on_surf( plotting.plot_img_on_surf(
stat_img, stat_img,
inflate=True, inflate=True,
threshold=0.5, threshold=0.5,
vmax=6 vmax=6
); );
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
`nilearn` also has some support for **interactive** viewing of volumetic images on the surface with the `view_img_on_surf` function. Try clicking on the plot and moving the cursor around! `nilearn` also has some support for **interactive** viewing of volumetic images on the surface with the `view_img_on_surf` function. Try clicking on the plot and moving the cursor around!
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
view = plotting.view_img_on_surf( view = plotting.view_img_on_surf(
stat_img, stat_img,
threshold=0.5, threshold=0.5,
surf_mesh='fsaverage', surf_mesh='fsaverage',
vmax=6 vmax=6
) )
view # view interactive plot inline view # view interactive plot inline
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
view = plotting.view_img_on_surf( view = plotting.view_img_on_surf(
stat_img, stat_img,
threshold=0.5, threshold=0.5,
surf_mesh='fsaverage', surf_mesh='fsaverage',
vmax=6 vmax=6
) )
view.open_in_browser() # view interactive plot inline view.open_in_browser() # view interactive plot inline
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
> >
> **Exercise:** > **Exercise:**
> >
> Visualise thee **Harvard-Oxford** atlas on a surface in the web browser > Visualise thee **Harvard-Oxford** atlas on a surface in the web browser
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# YOUR CODE HERE # YOUR CODE HERE
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
That's all folks.... That's all folks....
......
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## PLOTLY ## PLOTLY
[`plotly.py`](https://plotly.com/python/) is a python interface to the `plotly` javascript library which is an open-source graphing library which specialises in high-quality web-based interactive graphs. `plotly.py` allows you to create these interactive web-based plots without having to code in javascript. [`plotly.py`](https://plotly.com/python/) is a python interface to the `plotly` javascript library which is an open-source graphing library which specialises in high-quality web-based interactive graphs. `plotly.py` allows you to create these interactive web-based plots without having to code in javascript.
`plotly.py` has excellent documentation: https://plotly.com/python/ `plotly.py` has excellent documentation: https://plotly.com/python/
This notebook is not intended to instruct you how to use `plotly.py`. Instead it pulls together interesting examples from the `plotly.py` documentation into a single notebook to give you a taster of what can be done with `plotly.py`. This notebook is not intended to instruct you how to use `plotly.py`. Instead it pulls together interesting examples from the `plotly.py` documentation into a single notebook to give you a taster of what can be done with `plotly.py`.
### Install `plotly.py` ### Install `plotly.py`
`plotly` is not installed in the `fslpython` environment so you will need to install it to run this notebook. (e.g. with `pip install plotly`) `plotly` is not installed in the `fslpython` environment so you will need to install it to run this notebook. (e.g. with `$FSLDIR/bin/conda install plotly`)
### Line & Scatter Plots ### Line & Scatter Plots
https://plotly.com/python/line-and-scatter https://plotly.com/python/line-and-scatter
The graph_objects class gives you access to all the types of graphs that plotly has to offer. The graph_objects class gives you access to all the types of graphs that plotly has to offer.
Below are some random data plotted as scatter plots. Run the cell below and try the interactive interface. You can zoom in and out, you can see data values as you hover on the plot, and you can toggle on and off the different scatter plots. Below are some random data plotted as scatter plots. Run the cell below and try the interactive interface. You can zoom in and out, you can see data values as you hover on the plot, and you can toggle on and off the different scatter plots.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import plotly.graph_objects as go import plotly.graph_objects as go
# Create random data with numpy # Create random data with numpy
import numpy as np import numpy as np
np.random.seed(1) np.random.seed(1)
N = 100 N = 100
random_x = np.linspace(0, 1, N) random_x = np.linspace(0, 1, N)
random_y0 = np.random.randn(N) + 5 random_y0 = np.random.randn(N) + 5
random_y1 = np.random.randn(N) random_y1 = np.random.randn(N)
random_y2 = np.random.randn(N) - 5 random_y2 = np.random.randn(N) - 5
fig = go.Figure() fig = go.Figure()
# Add traces # Add traces
fig.add_trace(go.Scatter(x=random_x, y=random_y0, fig.add_trace(go.Scatter(x=random_x, y=random_y0,
mode='markers', mode='markers',
name='markers')) name='markers'))
fig.add_trace(go.Scatter(x=random_x, y=random_y1, fig.add_trace(go.Scatter(x=random_x, y=random_y1,
mode='lines+markers', mode='lines+markers',
name='lines+markers')) name='lines+markers'))
fig.add_trace(go.Scatter(x=random_x, y=random_y2, fig.add_trace(go.Scatter(x=random_x, y=random_y2,
mode='lines', mode='lines',
name='lines')) name='lines'))
fig.show() fig.show()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Bar Charts ## Bar Charts
https://plotly.com/python/bar-charts/ https://plotly.com/python/bar-charts/
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import plotly.graph_objects as go import plotly.graph_objects as go
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
fig = go.Figure() fig = go.Figure()
fig.add_trace(go.Bar( fig.add_trace(go.Bar(
x=months, x=months,
y=[20, 14, 25, 16, 18, 22, 19, 15, 12, 16, 14, 17], y=[20, 14, 25, 16, 18, 22, 19, 15, 12, 16, 14, 17],
name='Primary Product', name='Primary Product',
marker_color='indianred' marker_color='indianred'
)) ))
fig.add_trace(go.Bar( fig.add_trace(go.Bar(
x=months, x=months,
y=[19, 14, 22, 14, 16, 19, 15, 14, 10, 12, 12, 16], y=[19, 14, 22, 14, 16, 19, 15, 14, 10, 12, 12, 16],
name='Secondary Product', name='Secondary Product',
marker_color='lightsalmon' marker_color='lightsalmon'
)) ))
# Here we modify the tickangle of the xaxis, resulting in rotated labels. # Here we modify the tickangle of the xaxis, resulting in rotated labels.
fig.update_layout(barmode='group', xaxis_tickangle=-45) fig.update_layout(barmode='group', xaxis_tickangle=-45)
fig.show() fig.show()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Box Plots ## Box Plots
https://plotly.com/python/box-plots https://plotly.com/python/box-plots
Here we use `plotly.express`. It is probably the easiest way to create plotly plots (it uses graphical_objects under the hood). Here we also use it to get access to some of the toy datasets. Here we use `plotly.express`. It is probably the easiest way to create plotly plots (it uses graphical_objects under the hood). Here we also use it to get access to some of the toy datasets.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import plotly.express as px import plotly.express as px
df = px.data.tips() df = px.data.tips()
# have a peek inside this dataset # have a peek inside this dataset
print(df) print(df)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now let's do a boxplot to see how tips change by day and by smoker status. Try to interact with the plot. It shows you useful quantities, such as min/max, as you hover. Now let's do a boxplot to see how tips change by day and by smoker status. Try to interact with the plot. It shows you useful quantities, such as min/max, as you hover.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
fig = px.box(df, x="day", y="total_bill", color="smoker") fig = px.box(df, x="day", y="total_bill", color="smoker")
fig.update_traces(quartilemethod="exclusive") # or "inclusive", or "linear" by default fig.update_traces(quartilemethod="exclusive") # or "inclusive", or "linear" by default
fig.show() fig.show()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Distribution Plots ## Distribution Plots
https://plotly.com/python/distplot https://plotly.com/python/distplot
Here we use figure_factory, yet another collection of pre-specified nice plots. Here we use figure_factory, yet another collection of pre-specified nice plots.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import plotly.figure_factory as ff import plotly.figure_factory as ff
import numpy as np import numpy as np
# Add histogram data # Add histogram data
x1 = np.random.randn(200) - 2 x1 = np.random.randn(200) - 2
x2 = np.random.randn(200) x2 = np.random.randn(200)
x3 = np.random.randn(200) + 2 x3 = np.random.randn(200) + 2
x4 = np.random.randn(200) + 4 x4 = np.random.randn(200) + 4
# Group data together # Group data together
hist_data = [x1, x2, x3, x4] hist_data = [x1, x2, x3, x4]
group_labels = ['Group 1', 'Group 2', 'Group 3', 'Group 4'] group_labels = ['Group 1', 'Group 2', 'Group 3', 'Group 4']
# Create distplot with custom bin_size # Create distplot with custom bin_size
fig = ff.create_distplot(hist_data, group_labels, bin_size=.2) fig = ff.create_distplot(hist_data, group_labels, bin_size=.2)
fig.show() fig.show()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Violin Plots ## Violin Plots
https://plotly.com/python/violin/ https://plotly.com/python/violin/
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import plotly.graph_objects as go import plotly.graph_objects as go
import pandas as pd import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/violin_data.csv") df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/violin_data.csv")
fig = go.Figure() fig = go.Figure()
days = ['Thur', 'Fri', 'Sat', 'Sun'] days = ['Thur', 'Fri', 'Sat', 'Sun']
for day in days: for day in days:
fig.add_trace(go.Violin(x=df['day'][df['day'] == day], fig.add_trace(go.Violin(x=df['day'][df['day'] == day],
y=df['total_bill'][df['day'] == day], y=df['total_bill'][df['day'] == day],
name=day, name=day,
box_visible=True, box_visible=True,
meanline_visible=True)) meanline_visible=True))
fig.show() fig.show()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Dendrogram with Heatmap ## Dendrogram with Heatmap
https://plotly.com/python/dendrogram/ https://plotly.com/python/dendrogram/
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import plotly.graph_objects as go import plotly.graph_objects as go
import plotly.figure_factory as ff import plotly.figure_factory as ff
import numpy as np import numpy as np
from scipy.spatial.distance import pdist, squareform from scipy.spatial.distance import pdist, squareform
# get data # get data
data = np.genfromtxt("http://files.figshare.com/2133304/ExpRawData_E_TABM_84_A_AFFY_44.tab", data = np.genfromtxt("http://files.figshare.com/2133304/ExpRawData_E_TABM_84_A_AFFY_44.tab",
names=True,usecols=tuple(range(1,30)),dtype=float, delimiter="\t") names=True,usecols=tuple(range(1,30)),dtype=float, delimiter="\t")
data_array = data.view((float, len(data.dtype.names))) data_array = data.view((float, len(data.dtype.names)))
data_array = data_array.transpose() data_array = data_array.transpose()
labels = data.dtype.names labels = data.dtype.names
# Initialize figure by creating upper dendrogram # Initialize figure by creating upper dendrogram
fig = ff.create_dendrogram(data_array, orientation='bottom', labels=labels) fig = ff.create_dendrogram(data_array, orientation='bottom', labels=labels)
for i in range(len(fig['data'])): for i in range(len(fig['data'])):
fig['data'][i]['yaxis'] = 'y2' fig['data'][i]['yaxis'] = 'y2'
# Create Side Dendrogram # Create Side Dendrogram
dendro_side = ff.create_dendrogram(data_array, orientation='right') dendro_side = ff.create_dendrogram(data_array, orientation='right')
for i in range(len(dendro_side['data'])): for i in range(len(dendro_side['data'])):
dendro_side['data'][i]['xaxis'] = 'x2' dendro_side['data'][i]['xaxis'] = 'x2'
# Add Side Dendrogram Data to Figure # Add Side Dendrogram Data to Figure
for data in dendro_side['data']: for data in dendro_side['data']:
fig.add_trace(data) fig.add_trace(data)
# Create Heatmap # Create Heatmap
dendro_leaves = dendro_side['layout']['yaxis']['ticktext'] dendro_leaves = dendro_side['layout']['yaxis']['ticktext']
dendro_leaves = list(map(int, dendro_leaves)) dendro_leaves = list(map(int, dendro_leaves))
data_dist = pdist(data_array) data_dist = pdist(data_array)
heat_data = squareform(data_dist) heat_data = squareform(data_dist)
heat_data = heat_data[dendro_leaves,:] heat_data = heat_data[dendro_leaves,:]
heat_data = heat_data[:,dendro_leaves] heat_data = heat_data[:,dendro_leaves]
heatmap = [ heatmap = [
go.Heatmap( go.Heatmap(
x = dendro_leaves, x = dendro_leaves,
y = dendro_leaves, y = dendro_leaves,
z = heat_data, z = heat_data,
colorscale = 'Blues' colorscale = 'Blues'
) )
] ]
heatmap[0]['x'] = fig['layout']['xaxis']['tickvals'] heatmap[0]['x'] = fig['layout']['xaxis']['tickvals']
heatmap[0]['y'] = dendro_side['layout']['yaxis']['tickvals'] heatmap[0]['y'] = dendro_side['layout']['yaxis']['tickvals']
# Add Heatmap Data to Figure # Add Heatmap Data to Figure
for data in heatmap: for data in heatmap:
fig.add_trace(data) fig.add_trace(data)
# Edit Layout # Edit Layout
fig.update_layout({'width':800, 'height':800, fig.update_layout({'width':800, 'height':800,
'showlegend':False, 'hovermode': 'closest', 'showlegend':False, 'hovermode': 'closest',
}) })
# Edit xaxis # Edit xaxis
fig.update_layout(xaxis={'domain': [.15, 1], fig.update_layout(xaxis={'domain': [.15, 1],
'mirror': False, 'mirror': False,
'showgrid': False, 'showgrid': False,
'showline': False, 'showline': False,
'zeroline': False, 'zeroline': False,
'ticks':""}) 'ticks':""})
# Edit xaxis2 # Edit xaxis2
fig.update_layout(xaxis2={'domain': [0, .15], fig.update_layout(xaxis2={'domain': [0, .15],
'mirror': False, 'mirror': False,
'showgrid': False, 'showgrid': False,
'showline': False, 'showline': False,
'zeroline': False, 'zeroline': False,
'showticklabels': False, 'showticklabels': False,
'ticks':""}) 'ticks':""})
# Edit yaxis # Edit yaxis
fig.update_layout(yaxis={'domain': [0, .85], fig.update_layout(yaxis={'domain': [0, .85],
'mirror': False, 'mirror': False,
'showgrid': False, 'showgrid': False,
'showline': False, 'showline': False,
'zeroline': False, 'zeroline': False,
'showticklabels': False, 'showticklabels': False,
'ticks': "" 'ticks': ""
}) })
# Edit yaxis2 # Edit yaxis2
fig.update_layout(yaxis2={'domain':[.825, .975], fig.update_layout(yaxis2={'domain':[.825, .975],
'mirror': False, 'mirror': False,
'showgrid': False, 'showgrid': False,
'showline': False, 'showline': False,
'zeroline': False, 'zeroline': False,
'showticklabels': False, 'showticklabels': False,
'ticks':""}) 'ticks':""})
# Plot! # Plot!
fig.show() fig.show()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Network Graph ## Network Graph
https://plotly.com/python/network-graphs https://plotly.com/python/network-graphs
This one is very ugly. I don't know why anyone would use this... This one is very ugly. I don't know why anyone would use this...
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import plotly.graph_objects as go import plotly.graph_objects as go
import networkx as nx import networkx as nx
G = nx.random_geometric_graph(200, 0.125) G = nx.random_geometric_graph(200, 0.125)
edge_x = [] edge_x = []
edge_y = [] edge_y = []
for edge in G.edges(): for edge in G.edges():
x0, y0 = G.nodes[edge[0]]['pos'] x0, y0 = G.nodes[edge[0]]['pos']
x1, y1 = G.nodes[edge[1]]['pos'] x1, y1 = G.nodes[edge[1]]['pos']
edge_x.append(x0) edge_x.append(x0)
edge_x.append(x1) edge_x.append(x1)
edge_x.append(None) edge_x.append(None)
edge_y.append(y0) edge_y.append(y0)
edge_y.append(y1) edge_y.append(y1)
edge_y.append(None) edge_y.append(None)
edge_trace = go.Scatter( edge_trace = go.Scatter(
x=edge_x, y=edge_y, x=edge_x, y=edge_y,
line=dict(width=0.5, color='#888'), line=dict(width=0.5, color='#888'),
hoverinfo='none', hoverinfo='none',
mode='lines') mode='lines')
node_x = [] node_x = []
node_y = [] node_y = []
for node in G.nodes(): for node in G.nodes():
x, y = G.nodes[node]['pos'] x, y = G.nodes[node]['pos']
node_x.append(x) node_x.append(x)
node_y.append(y) node_y.append(y)
node_trace = go.Scatter( node_trace = go.Scatter(
x=node_x, y=node_y, x=node_x, y=node_y,
mode='markers', mode='markers',
hoverinfo='text', hoverinfo='text',
marker=dict( marker=dict(
showscale=True, showscale=True,
# colorscale options # colorscale options
#'Greys' | 'YlGnBu' | 'Greens' | 'YlOrRd' | 'Bluered' | 'RdBu' | #'Greys' | 'YlGnBu' | 'Greens' | 'YlOrRd' | 'Bluered' | 'RdBu' |
#'Reds' | 'Blues' | 'Picnic' | 'Rainbow' | 'Portland' | 'Jet' | #'Reds' | 'Blues' | 'Picnic' | 'Rainbow' | 'Portland' | 'Jet' |
#'Hot' | 'Blackbody' | 'Earth' | 'Electric' | 'Viridis' | #'Hot' | 'Blackbody' | 'Earth' | 'Electric' | 'Viridis' |
colorscale='YlGnBu', colorscale='YlGnBu',
reversescale=True, reversescale=True,
color=[], color=[],
size=10, size=10,
colorbar=dict( colorbar=dict(
thickness=15, thickness=15,
title='Node Connections', title='Node Connections',
xanchor='left', xanchor='left',
titleside='right' titleside='right'
), ),
line_width=2)) line_width=2))
node_adjacencies = [] node_adjacencies = []
node_text = [] node_text = []
for node, adjacencies in enumerate(G.adjacency()): for node, adjacencies in enumerate(G.adjacency()):
node_adjacencies.append(len(adjacencies[1])) node_adjacencies.append(len(adjacencies[1]))
node_text.append('# of connections: '+str(len(adjacencies[1]))) node_text.append('# of connections: '+str(len(adjacencies[1])))
node_trace.marker.color = node_adjacencies node_trace.marker.color = node_adjacencies
node_trace.text = node_text node_trace.text = node_text
fig = go.Figure(data=[edge_trace, node_trace], fig = go.Figure(data=[edge_trace, node_trace],
layout=go.Layout( layout=go.Layout(
titlefont_size=16, titlefont_size=16,
showlegend=False, showlegend=False,
hovermode='closest', hovermode='closest',
margin=dict(b=20,l=5,r=5,t=40), margin=dict(b=20,l=5,r=5,t=40),
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)) yaxis=dict(showgrid=False, zeroline=False, showticklabels=False))
) )
fig.show() fig.show()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Custom Controls: Sliders ## Custom Controls: Sliders
https://plotly.com/python/sliders https://plotly.com/python/sliders
Sliders are a very nice way to interact with plots. Here is a basic example where we plot a sine function and change its frequency. Note how all the data for plotting, and all the traces are pre-generated. This is not ideal if you need to change more than one parameter (e.g. both phase and frequency). Sliders are a very nice way to interact with plots. Here is a basic example where we plot a sine function and change its frequency. Note how all the data for plotting, and all the traces are pre-generated. This is not ideal if you need to change more than one parameter (e.g. both phase and frequency).
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import plotly.graph_objects as go import plotly.graph_objects as go
import numpy as np import numpy as np
# Create figure # Create figure
fig = go.Figure() fig = go.Figure()
# Add traces, one for each slider step # Add traces, one for each slider step
for step in np.arange(0, 5, 0.1): for step in np.arange(0, 5, 0.1):
fig.add_trace( fig.add_trace(
go.Scatter( go.Scatter(
visible=False, visible=False,
line=dict(color="#00CED1", width=6), line=dict(color="#00CED1", width=6),
name="𝜈 = " + str(step), name="𝜈 = " + str(step),
x=np.arange(0, 10, 0.01), x=np.arange(0, 10, 0.01),
y=np.sin(step * np.arange(0, 10, 0.01)))) y=np.sin(step * np.arange(0, 10, 0.01))))
# Make 10th trace visible # Make 10th trace visible
fig.data[10].visible = True fig.data[10].visible = True
# Create and add slider # Create and add slider
steps = [] steps = []
for i in range(len(fig.data)): for i in range(len(fig.data)):
step = dict( step = dict(
method="update", method="update",
args=[{"visible": [False] * len(fig.data)}, args=[{"visible": [False] * len(fig.data)},
{"title": "Slider switched to step: " + str(i)}], # layout attribute {"title": "Slider switched to step: " + str(i)}], # layout attribute
) )
step["args"][0]["visible"][i] = True # Toggle i'th trace to "visible" step["args"][0]["visible"][i] = True # Toggle i'th trace to "visible"
steps.append(step) steps.append(step)
sliders = [dict( sliders = [dict(
active=10, active=10,
currentvalue={"prefix": "Frequency: "}, currentvalue={"prefix": "Frequency: "},
pad={"t": 50}, pad={"t": 50},
steps=steps steps=steps
)] )]
fig.update_layout( fig.update_layout(
sliders=sliders sliders=sliders
) )
fig.show() fig.show()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Custom Controls: Dropdown Menus ## Custom Controls: Dropdown Menus
https://plotly.com/python/dropdowns/ https://plotly.com/python/dropdowns/
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import plotly.graph_objects as go import plotly.graph_objects as go
import pandas as pd import pandas as pd
# load dataset # load dataset
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/volcano.csv") df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/volcano.csv")
# Create figure # Create figure
fig = go.Figure() fig = go.Figure()
# Add surface trace # Add surface trace
fig.add_trace(go.Heatmap(z=df.values.tolist(), colorscale="Viridis")) fig.add_trace(go.Heatmap(z=df.values.tolist(), colorscale="Viridis"))
# Update plot sizing # Update plot sizing
fig.update_layout( fig.update_layout(
width=800, width=800,
height=900, height=900,
autosize=False, autosize=False,
margin=dict(t=100, b=0, l=0, r=0), margin=dict(t=100, b=0, l=0, r=0),
) )
# Update 3D scene options # Update 3D scene options
fig.update_scenes( fig.update_scenes(
aspectratio=dict(x=1, y=1, z=0.7), aspectratio=dict(x=1, y=1, z=0.7),
aspectmode="manual" aspectmode="manual"
) )
# Add dropdowns # Add dropdowns
button_layer_1_height = 1.08 button_layer_1_height = 1.08
fig.update_layout( fig.update_layout(
updatemenus=[ updatemenus=[
dict( dict(
buttons=list([ buttons=list([
dict( dict(
args=["colorscale", "Viridis"], args=["colorscale", "Viridis"],
label="Viridis", label="Viridis",
method="restyle" method="restyle"
), ),
dict( dict(
args=["colorscale", "Cividis"], args=["colorscale", "Cividis"],
label="Cividis", label="Cividis",
method="restyle" method="restyle"
), ),
dict( dict(
args=["colorscale", "Blues"], args=["colorscale", "Blues"],
label="Blues", label="Blues",
method="restyle" method="restyle"
), ),
dict( dict(
args=["colorscale", "Greens"], args=["colorscale", "Greens"],
label="Greens", label="Greens",
method="restyle" method="restyle"
), ),
]), ]),
direction="down", direction="down",
pad={"r": 10, "t": 10}, pad={"r": 10, "t": 10},
showactive=True, showactive=True,
x=0.1, x=0.1,
xanchor="left", xanchor="left",
y=button_layer_1_height, y=button_layer_1_height,
yanchor="top" yanchor="top"
), ),
dict( dict(
buttons=list([ buttons=list([
dict( dict(
args=["reversescale", False], args=["reversescale", False],
label="False", label="False",
method="restyle" method="restyle"
), ),
dict( dict(
args=["reversescale", True], args=["reversescale", True],
label="True", label="True",
method="restyle" method="restyle"
) )
]), ]),
direction="down", direction="down",
pad={"r": 10, "t": 10}, pad={"r": 10, "t": 10},
showactive=True, showactive=True,
x=0.37, x=0.37,
xanchor="left", xanchor="left",
y=button_layer_1_height, y=button_layer_1_height,
yanchor="top" yanchor="top"
), ),
dict( dict(
buttons=list([ buttons=list([
dict( dict(
args=[{"contours.showlines": False, "type": "contour"}], args=[{"contours.showlines": False, "type": "contour"}],
label="Hide lines", label="Hide lines",
method="restyle" method="restyle"
), ),
dict( dict(
args=[{"contours.showlines": True, "type": "contour"}], args=[{"contours.showlines": True, "type": "contour"}],
label="Show lines", label="Show lines",
method="restyle" method="restyle"
), ),
]), ]),
direction="down", direction="down",
pad={"r": 10, "t": 10}, pad={"r": 10, "t": 10},
showactive=True, showactive=True,
x=0.58, x=0.58,
xanchor="left", xanchor="left",
y=button_layer_1_height, y=button_layer_1_height,
yanchor="top" yanchor="top"
), ),
] ]
) )
fig.update_layout( fig.update_layout(
annotations=[ annotations=[
dict(text="colorscale", x=0, xref="paper", y=1.06, yref="paper", dict(text="colorscale", x=0, xref="paper", y=1.06, yref="paper",
align="left", showarrow=False), align="left", showarrow=False),
dict(text="Reverse<br>Colorscale", x=0.25, xref="paper", y=1.07, dict(text="Reverse<br>Colorscale", x=0.25, xref="paper", y=1.07,
yref="paper", showarrow=False), yref="paper", showarrow=False),
dict(text="Lines", x=0.54, xref="paper", y=1.06, yref="paper", dict(text="Lines", x=0.54, xref="paper", y=1.06, yref="paper",
showarrow=False) showarrow=False)
]) ])
fig.show() fig.show()
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment