Skip to content
Snippets Groups Projects
Commit 00d179f7 authored by Sean Fitzgibbon's avatar Sean Fitzgibbon
Browse files

Added first pass at plotly examples notebook

parent d0d5b224
No related branches found
No related tags found
1 merge request!19Plotly examples
%% Cell type:markdown id: tags:
# `plotly.py`
[`plotly.py`](https://plotly.com/python/) 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/
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`
`plotly` is not installed in the `fslpython` environment so you will need to install it to run this notebook. In a terminal run the following command (you will need admin privileges):
```
sudo $FSLDIR/fslpython/bin/conda install -c conda-forge -n fslpython plotly
```
## Line & Scatter Plots
https://plotly.com/python/line-and-scatter/
%% Cell type:code id: tags:
``` python
import plotly.graph_objects as go
# Create random data with numpy
import numpy as np
np.random.seed(1)
N = 100
random_x = np.linspace(0, 1, N)
random_y0 = np.random.randn(N) + 5
random_y1 = np.random.randn(N)
random_y2 = np.random.randn(N) - 5
fig = go.Figure()
# Add traces
fig.add_trace(go.Scatter(x=random_x, y=random_y0,
mode='markers',
name='markers'))
fig.add_trace(go.Scatter(x=random_x, y=random_y1,
mode='lines+markers',
name='lines+markers'))
fig.add_trace(go.Scatter(x=random_x, y=random_y2,
mode='lines',
name='lines'))
fig.show()
```
%% Cell type:markdown id: tags:
## Bar Charts
https://plotly.com/python/bar-charts/
%% Cell type:code id: tags:
``` python
import plotly.graph_objects as go
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
fig = go.Figure()
fig.add_trace(go.Bar(
x=months,
y=[20, 14, 25, 16, 18, 22, 19, 15, 12, 16, 14, 17],
name='Primary Product',
marker_color='indianred'
))
fig.add_trace(go.Bar(
x=months,
y=[19, 14, 22, 14, 16, 19, 15, 14, 10, 12, 12, 16],
name='Secondary Product',
marker_color='lightsalmon'
))
# Here we modify the tickangle of the xaxis, resulting in rotated labels.
fig.update_layout(barmode='group', xaxis_tickangle=-45)
fig.show()
```
%% Cell type:markdown id: tags:
## Box Plots
https://plotly.com/python/box-plots/
%% Cell type:code id: tags:
``` python
import plotly.express as px
df = px.data.tips()
fig = px.box(df, x="day", y="total_bill", color="smoker")
fig.update_traces(quartilemethod="exclusive") # or "inclusive", or "linear" by default
fig.show()
```
%% Cell type:markdown id: tags:
## Distribution Plots
https://plotly.com/python/distplot/
%% Cell type:code id: tags:
``` python
import plotly.figure_factory as ff
import numpy as np
# Add histogram data
x1 = np.random.randn(200) - 2
x2 = np.random.randn(200)
x3 = np.random.randn(200) + 2
x4 = np.random.randn(200) + 4
# Group data together
hist_data = [x1, x2, x3, x4]
group_labels = ['Group 1', 'Group 2', 'Group 3', 'Group 4']
# Create distplot with custom bin_size
fig = ff.create_distplot(hist_data, group_labels, bin_size=.2)
fig.show()
```
%% Cell type:markdown id: tags:
## Violin Plots
https://plotly.com/python/violin/
%% Cell type:code id: tags:
``` python
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/violin_data.csv")
fig = go.Figure()
days = ['Thur', 'Fri', 'Sat', 'Sun']
for day in days:
fig.add_trace(go.Violin(x=df['day'][df['day'] == day],
y=df['total_bill'][df['day'] == day],
name=day,
box_visible=True,
meanline_visible=True))
fig.show()
```
%% Cell type:markdown id: tags:
## Dendrogram with Heatmap
https://plotly.com/python/dendrogram/
%% Cell type:code id: tags:
``` python
import plotly.graph_objects as go
import plotly.figure_factory as ff
import numpy as np
from scipy.spatial.distance import pdist, squareform
# get data
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")
data_array = data.view((float, len(data.dtype.names)))
data_array = data_array.transpose()
labels = data.dtype.names
# Initialize figure by creating upper dendrogram
fig = ff.create_dendrogram(data_array, orientation='bottom', labels=labels)
for i in range(len(fig['data'])):
fig['data'][i]['yaxis'] = 'y2'
# Create Side Dendrogram
dendro_side = ff.create_dendrogram(data_array, orientation='right')
for i in range(len(dendro_side['data'])):
dendro_side['data'][i]['xaxis'] = 'x2'
# Add Side Dendrogram Data to Figure
for data in dendro_side['data']:
fig.add_trace(data)
# Create Heatmap
dendro_leaves = dendro_side['layout']['yaxis']['ticktext']
dendro_leaves = list(map(int, dendro_leaves))
data_dist = pdist(data_array)
heat_data = squareform(data_dist)
heat_data = heat_data[dendro_leaves,:]
heat_data = heat_data[:,dendro_leaves]
heatmap = [
go.Heatmap(
x = dendro_leaves,
y = dendro_leaves,
z = heat_data,
colorscale = 'Blues'
)
]
heatmap[0]['x'] = fig['layout']['xaxis']['tickvals']
heatmap[0]['y'] = dendro_side['layout']['yaxis']['tickvals']
# Add Heatmap Data to Figure
for data in heatmap:
fig.add_trace(data)
# Edit Layout
fig.update_layout({'width':800, 'height':800,
'showlegend':False, 'hovermode': 'closest',
})
# Edit xaxis
fig.update_layout(xaxis={'domain': [.15, 1],
'mirror': False,
'showgrid': False,
'showline': False,
'zeroline': False,
'ticks':""})
# Edit xaxis2
fig.update_layout(xaxis2={'domain': [0, .15],
'mirror': False,
'showgrid': False,
'showline': False,
'zeroline': False,
'showticklabels': False,
'ticks':""})
# Edit yaxis
fig.update_layout(yaxis={'domain': [0, .85],
'mirror': False,
'showgrid': False,
'showline': False,
'zeroline': False,
'showticklabels': False,
'ticks': ""
})
# Edit yaxis2
fig.update_layout(yaxis2={'domain':[.825, .975],
'mirror': False,
'showgrid': False,
'showline': False,
'zeroline': False,
'showticklabels': False,
'ticks':""})
# Plot!
fig.show()
```
%% Cell type:markdown id: tags:
## Network Graph
https://plotly.com/python/network-graphs/
%% Cell type:code id: tags:
``` python
import plotly.graph_objects as go
import networkx as nx
G = nx.random_geometric_graph(200, 0.125)
edge_x = []
edge_y = []
for edge in G.edges():
x0, y0 = G.nodes[edge[0]]['pos']
x1, y1 = G.nodes[edge[1]]['pos']
edge_x.append(x0)
edge_x.append(x1)
edge_x.append(None)
edge_y.append(y0)
edge_y.append(y1)
edge_y.append(None)
edge_trace = go.Scatter(
x=edge_x, y=edge_y,
line=dict(width=0.5, color='#888'),
hoverinfo='none',
mode='lines')
node_x = []
node_y = []
for node in G.nodes():
x, y = G.nodes[node]['pos']
node_x.append(x)
node_y.append(y)
node_trace = go.Scatter(
x=node_x, y=node_y,
mode='markers',
hoverinfo='text',
marker=dict(
showscale=True,
# colorscale options
#'Greys' | 'YlGnBu' | 'Greens' | 'YlOrRd' | 'Bluered' | 'RdBu' |
#'Reds' | 'Blues' | 'Picnic' | 'Rainbow' | 'Portland' | 'Jet' |
#'Hot' | 'Blackbody' | 'Earth' | 'Electric' | 'Viridis' |
colorscale='YlGnBu',
reversescale=True,
color=[],
size=10,
colorbar=dict(
thickness=15,
title='Node Connections',
xanchor='left',
titleside='right'
),
line_width=2))
node_adjacencies = []
node_text = []
for node, adjacencies in enumerate(G.adjacency()):
node_adjacencies.append(len(adjacencies[1]))
node_text.append('# of connections: '+str(len(adjacencies[1])))
node_trace.marker.color = node_adjacencies
node_trace.text = node_text
fig = go.Figure(data=[edge_trace, node_trace],
layout=go.Layout(
titlefont_size=16,
showlegend=False,
hovermode='closest',
margin=dict(b=20,l=5,r=5,t=40),
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False))
)
fig.show()
```
%% Cell type:markdown id: tags:
## Custom Controls: Sliders
https://plotly.com/python/sliders/
%% Cell type:code id: tags:
``` python
import plotly.graph_objects as go
import numpy as np
# Create figure
fig = go.Figure()
# Add traces, one for each slider step
for step in np.arange(0, 5, 0.1):
fig.add_trace(
go.Scatter(
visible=False,
line=dict(color="#00CED1", width=6),
name="𝜈 = " + str(step),
x=np.arange(0, 10, 0.01),
y=np.sin(step * np.arange(0, 10, 0.01))))
# Make 10th trace visible
fig.data[10].visible = True
# Create and add slider
steps = []
for i in range(len(fig.data)):
step = dict(
method="update",
args=[{"visible": [False] * len(fig.data)},
{"title": "Slider switched to step: " + str(i)}], # layout attribute
)
step["args"][0]["visible"][i] = True # Toggle i'th trace to "visible"
steps.append(step)
sliders = [dict(
active=10,
currentvalue={"prefix": "Frequency: "},
pad={"t": 50},
steps=steps
)]
fig.update_layout(
sliders=sliders
)
fig.show()
```
%% Cell type:markdown id: tags:
## Custom Controls: Dropdown Menus
https://plotly.com/python/dropdowns/
%% Cell type:code id: tags:
``` python
import plotly.graph_objects as go
import pandas as pd
# load dataset
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/volcano.csv")
# Create figure
fig = go.Figure()
# Add surface trace
fig.add_trace(go.Heatmap(z=df.values.tolist(), colorscale="Viridis"))
# Update plot sizing
fig.update_layout(
width=800,
height=900,
autosize=False,
margin=dict(t=100, b=0, l=0, r=0),
)
# Update 3D scene options
fig.update_scenes(
aspectratio=dict(x=1, y=1, z=0.7),
aspectmode="manual"
)
# Add dropdowns
button_layer_1_height = 1.08
fig.update_layout(
updatemenus=[
dict(
buttons=list([
dict(
args=["colorscale", "Viridis"],
label="Viridis",
method="restyle"
),
dict(
args=["colorscale", "Cividis"],
label="Cividis",
method="restyle"
),
dict(
args=["colorscale", "Blues"],
label="Blues",
method="restyle"
),
dict(
args=["colorscale", "Greens"],
label="Greens",
method="restyle"
),
]),
direction="down",
pad={"r": 10, "t": 10},
showactive=True,
x=0.1,
xanchor="left",
y=button_layer_1_height,
yanchor="top"
),
dict(
buttons=list([
dict(
args=["reversescale", False],
label="False",
method="restyle"
),
dict(
args=["reversescale", True],
label="True",
method="restyle"
)
]),
direction="down",
pad={"r": 10, "t": 10},
showactive=True,
x=0.37,
xanchor="left",
y=button_layer_1_height,
yanchor="top"
),
dict(
buttons=list([
dict(
args=[{"contours.showlines": False, "type": "contour"}],
label="Hide lines",
method="restyle"
),
dict(
args=[{"contours.showlines": True, "type": "contour"}],
label="Show lines",
method="restyle"
),
]),
direction="down",
pad={"r": 10, "t": 10},
showactive=True,
x=0.58,
xanchor="left",
y=button_layer_1_height,
yanchor="top"
),
]
)
fig.update_layout(
annotations=[
dict(text="colorscale", x=0, xref="paper", y=1.06, yref="paper",
align="left", showarrow=False),
dict(text="Reverse<br>Colorscale", x=0.25, xref="paper", y=1.07,
yref="paper", showarrow=False),
dict(text="Lines", x=0.54, xref="paper", y=1.06, yref="paper",
showarrow=False)
])
fig.show()
```
%% Cell type:code id: tags:
``` 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