Examples taken from: https://github.com/bloomberg/bqplot
flex_title = "bqplot plots"
flex_orientation = "rows"
flex_source_code = "https://github.com/danielfrg/jupyter-flex/blob/master/examples/plots/bqplot.ipynb"
import numpy as np
import pandas as pd
from pandas import date_range
from bqplot import *
size = 100
np.random.seed(0)
x_data = range(size)
y_data = np.random.randn(size)
y_data_2 = np.random.randn(size)
y_data_3 = np.cumsum(np.random.randn(size) * 100.)
x_ord = OrdinalScale()
y_sc = LinearScale()
bar = Bars(x=np.arange(10), y=np.random.rand(10), scales={'x': x_ord, 'y': y_sc})
ax_x = Axis(scale=x_ord)
ax_y = Axis(scale=y_sc, tick_format='0.2f', orientation='vertical')
Figure(marks=[bar], axes=[ax_x, ax_y], padding_x=0.025, padding_y=0.025)
x_ord = OrdinalScale()
y_sc = LinearScale()
bar = Bars(x=x_data, y=[y_data[:20], y_data_2[:20]],
scales={'x': x_ord, 'y': y_sc}, padding=0.2,
colors=CATEGORY10)
ax_x = Axis(scale=x_ord)
ax_y = Axis(scale=y_sc, orientation='vertical', tick_format='0.2f')
Figure(marks=[bar], axes=[ax_x, ax_y])
# In this example, the color is just the magnitude of the y data
x_ord = OrdinalScale()
y_sc = LinearScale()
col_sc = ColorScale(scheme='Reds')
bar = Bars(x=x_data[:20], y=y_data[:20], color=np.abs(y_data[:20]),
scales={'x': x_ord, 'y': y_sc, 'color': col_sc}, padding=0.2)
ax_x = Axis(scale=x_ord)
ax_y = Axis(scale=y_sc, orientation='vertical', tick_format='0.2f')
ax_c = ColorAxis(scale=col_sc, tick_format='0.2f')
margin = dict(top=50, bottom=80, left=50, right=50)
Figure(marks=[bar], axes=[ax_x, ax_y, ax_c], fig_margin=margin)
# By default color is applied along the axis=1
x_ord = OrdinalScale()
y_sc = LinearScale()
col_sc = ColorScale(scheme='Reds')
y_vals = [y_data[:20], y_data_2[:20], y_data_3[:20] / 100.0]
color_data = np.mean(y_vals, axis=1)
bar = Bars(x=x_data, y=y_vals, color=color_data,
scales={'x': x_ord, 'y': y_sc, 'color': col_sc}, padding=0.2,
labels=['Dim 1', 'Dim 2', 'Dim 3'], display_legend=True)
ax_x = Axis(scale=x_ord)
ax_y = Axis(scale=y_sc, orientation='vertical', tick_format='0.2f')
ax_c = ColorAxis(scale=col_sc, tick_format='0.2f')
margin = dict(top=50, bottom=80, left=50, right=50)
Figure(marks=[bar], axes=[ax_x, ax_y, ax_c], fig_margin=margin)
security_1 = np.cumsum(np.random.randn(150)) + 100.
security_2 = np.cumsum(np.random.randn(150)) + 100.
sc_x = LinearScale()
sc_y = LinearScale()
line = Lines(x=np.arange(len(security_1)), y=security_1,
scales={'x': sc_x, 'y': sc_y})
ax_x = Axis(scale=sc_x, label='Index')
ax_y = Axis(scale=sc_y, orientation='vertical', label='y-values of Security 1')
Figure(marks=[line], axes=[ax_x, ax_y], title='Security 1')
# Here we define the dates we would like to use
dates = date_range(start='01-01-2007', periods=150)
dt_x = DateScale()
sc_y = LinearScale()
time_series = Lines(x=dates, y=security_1, scales={'x': dt_x, 'y': sc_y})
ax_x = Axis(scale=dt_x, label='Date')
ax_y = Axis(scale=sc_y, orientation='vertical', label='Security 1')
Figure(marks=[time_series], axes=[ax_x, ax_y], title='A Time Series Plot')
x_dt = DateScale()
y_sc = LinearScale()
col_sc = ColorScale(colors=['Red', 'Green'])
dates_color = date_range(start='06-01-2007', periods=150)
securities = 100. + np.cumsum(np.random.randn(150, 10), axis=0)
positions = np.random.randint(0, 2, size=10)
# Here we generate 10 random price series and 10 random positions
# We pass the color scale and the color data to the lines
line = Lines(x=dates_color, y=securities.T,
scales={'x': x_dt, 'y': y_sc, 'color': col_sc}, color=positions,
labels=['Security 1', 'Security 2'])
ax_x = Axis(scale=x_dt, label='Date')
ax_y = Axis(scale=y_sc, orientation='vertical', label='Security 1')
Figure(marks=[line], axes=[ax_x, ax_y], legend_location='top-left')
line.color = None
price_data = pd.DataFrame(np.cumsum(np.random.randn(150, 2).dot([[1.0, -0.8], [-0.8, 1.0]]), axis=0) + 100,
columns=['Security 1', 'Security 2'], index=pd.date_range(start='01-01-2007', periods=150))
size = 100
np.random.seed(0)
x_data = range(size)
y_data = np.cumsum(np.random.randn(size) * 100.0)
ord_keys = np.array(['A', 'B', 'C', 'D', 'E', 'F'])
ordinal_data = np.random.randint(5, size=size)
symbols = ['Security 1', 'Security 2']
dates_all = price_data.index.values
dates_all_t = dates_all[1:]
sec1_levels = np.array(price_data[symbols[0]].values.flatten())
log_sec1 = np.log(sec1_levels)
sec1_returns = log_sec1[1:] - log_sec1[:-1]
sec2_levels = np.array(price_data[symbols[1]].values.flatten())
sc_x = DateScale()
sc_y = LinearScale()
scatt = Scatter(x=dates_all, y=sec2_levels, scales={'x': sc_x, 'y': sc_y})
ax_x = Axis(scale=sc_x, label='Date')
ax_y = Axis(scale=sc_y, orientation='vertical', tick_format='0.0f', label='Security 2')
Figure(marks=[scatt], axes=[ax_x, ax_y])
sc_x = DateScale()
sc_y = LinearScale()
sc_c1 = ColorScale()
scatter = Scatter(x=dates_all, y=sec2_levels, color=sec1_returns,
scales={'x': sc_x, 'y': sc_y, 'color': sc_c1},
stroke='black')
ax_y = Axis(label='Security 2', scale=sc_y,
orientation='vertical', side='left')
ax_x = Axis(label='Date', scale=sc_x, num_ticks=10, label_location='end')
ax_c = ColorAxis(scale=sc_c1, tick_format='0.2%', label='Returns', orientation='vertical', side='right')
m_chart = dict(top=50, bottom=70, left=50, right=100)
Figure(axes=[ax_x, ax_c, ax_y], marks=[scatter], fig_margin=m_chart,
title='Scatter of Security 2 vs Dates')
## Setting the fill back
scatter.stroke = 'black'
scatter.fill = True
## Changing the color to a different variable
scatter.color = sec2_levels
ax_c.tick_format = '0.0f'
ax_c.label = 'Security 2'
## Changing the range of the color scale
sc_c1.colors = ['blue', 'green', 'orange']
from ipywidgets import Label
## Enabling moving of points in scatter. Try to click and drag any of the points in the scatter and
## notice the line representing the mean of the data update
sc_x = LinearScale()
sc_y = LinearScale()
scat = Scatter(x=x_data[:10], y=y_data[:10], scales={'x': sc_x, 'y': sc_y}, colors=['orange'],
enable_move=True)
lin = Lines(x=[], y=[], scales={'x': sc_x, 'y': sc_y}, line_style='dotted', colors=['orange'])
def update_line(change=None):
with lin.hold_sync():
lin.x = [np.min(scat.x), np.max(scat.x)]
lin.y = [np.mean(scat.y), np.mean(scat.y)]
update_line()
# update line on change of x or y of scatter
scat.observe(update_line, names=['x'])
scat.observe(update_line, names=['y'])
ax_x = Axis(scale=sc_x)
ax_y = Axis(scale=sc_y, tick_format='0.2f', orientation='vertical')
fig = Figure(marks=[scat, lin], axes=[ax_x, ax_y])
## In this case on drag, the line updates as you move the points.
scat.update_on_move = True
latex_widget = Label(color='Green', font_size='16px')
def callback_help(name, value):
latex_widget.value = str(value)
latex_widget
scat.on_drag_start(callback_help)
scat.on_drag(callback_help)
scat.on_drag_end(callback_help)
## Restricting movement to only along the Y-axis
scat.restrict_y = True
## Enabling adding the points to Scatter. Try clicking anywhere on the scatter to add points
with scat.hold_sync():
scat.enable_move = False
scat.interactions = {'click': 'add'}
from ipywidgets import ToggleButtons, VBox
interact_control = ToggleButtons(options=['Add', 'Delete', 'Drag XY', 'Drag X', 'Drag Y'],
style={'button_width': '120px'})
def change_interact(change):
interact_parameters = {
'Add': {'interactions': {'click': 'add'},
'enable_move': False},
'Delete': {'interactions': {'click': 'delete'},
'enable_move': False},
'Drag XY': {'interactions': {'click': None},
'enable_move': True,
'restrict_x': False,
'restrict_y': False},
'Drag X': {'interactions': {'click': None},
'enable_move': True,
'restrict_x': True,
'restrict_y': False},
'Drag Y': {'interactions': {'click': None},
'enable_move': True,
'restrict_x': False,
'restrict_y': True}
}
for param, value in interact_parameters[interact_control.value].items():
setattr(scat, param, value)
interact_control.observe(change_interact, names='value')
fig.title = 'Adding/Deleting/Moving points'
VBox([fig, interact_control])