Interactive Plots Integration (Plotly, Bokeh, Highcharts)

PyBloqs also supports plotting with interactive plotting libraries such as Plotly(offline), Bokeh and Highcharts.

The plots will be rendered in HTML and will rely on your browser’s CSS and JS capabilities to provide interactivity.

Plotly Example

[1]:
%%capture
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
# The lines below are only needed for notebook output
from plotly.offline import init_notebook_mode
init_notebook_mode()
[2]:
%%capture
trace1 = go.Scatter(x=[1,2,3], y=[4,5,6], marker={'color': 'red', 'symbol': 104, 'size': 10},
                    mode="markers+lines",  text=["one","two","three"], name='1st Trace')

data=go.Data([trace1])
layout=go.Layout(title="First Plot", xaxis={'title':'x1'}, yaxis={'title':'x2'})
plotly_fig=go.Figure(data=data,layout=layout)
[3]:
import pybloqs as p
p.Block(plotly_fig)
[3]:

Bokeh Example

[4]:
import numpy as np
from six.moves import zip
from bokeh.plotting import figure as b_fig
# The lines below are only needed for notebook output
from bokeh.io.output import output_notebook
from bokeh.resources import INLINE
output_notebook(resources=INLINE)
Loading BokehJS ...
[5]:
N = 4000
x = np.random.random(size=N) * 100
y = np.random.random(size=N) * 100
radii = np.random.random(size=N) * 1.5
colors2 = ["#%02x%02x%02x" % (int(r), int(g), 150) for r, g in zip(50+2*x, 30+2*y)]
bokeh_fig = b_fig(width=300, height=300)
bokeh_fig.scatter(x,y, radius=radii, fill_color=colors2, fill_alpha=0.6, line_color=None)
[5]:
GlyphRenderer(
id = '70b52809-b7ff-469a-ba98-be4685fe9d76', …)
[6]:
p.Block(bokeh_fig)
[6]:

Combining Bokeh and Plotly plots with HStack

[7]:
p.HStack([p.Block(bokeh_fig), p.Block(plotly_fig)])
[7]:

Highcharts examples

Please note: Highcharts has a proprietary license

Simple line chart

When evaluated as the last expression in a Notebook Cell, the plot is automatically displayed inline. Note how the plot name (hover over the line to see the little popup) is taken from the input data (if available).

[8]:
import pandas as pd
import numpy as np
from datetime import datetime

df = pd.DataFrame((np.random.rand(200, 4)-0.5)/10,
                  columns=list("ABCD"),
                  index=pd.date_range(datetime(2000,1,1), periods=200))
df_cr = (df + 1).cumprod()
a = df_cr['A']
b = df_cr['B']
c = df_cr['C']
[9]:
import pybloqs.plot as pp
pp.interactive()
pp.Plot(a)
Interactive mode initialized successfully
[9]:

Saving as interactive HTML

[10]:
pp.Plot(df).save("chart_sample.html")
[10]:
'chart_sample.html'

Scatter Plot

Regular scatter plot, with zooming on both the x and y axes.

[11]:
pp.Plot(df.values[:,:2], pp.Scatter(pp.Marker(enabled=True)), pp.Chart(zoom_type="xy"))
[11]:

Bar Charts

Notice how when viewing all the data at once, the chart shows monthly data, yet zooming in reveals additional detail at up to daily resolution. This is accomplished by using a custom data grouping.

[12]:
bar_grouping = pp.DataGrouping(approximation="open", enabled=True, group_pixel_width=100)
[13]:
# Bar chart from a dataframe
pp.Plot(df, pp.Column(bar_grouping))
[13]:
[14]:
# Stacked bar chart
pp.Plot(df, pp.Column(bar_grouping, stacking="normal"))
[14]:
[15]:
# Composite bar chart from two separate plots.
s2 = pp.Plot([pp.Plot(a, pp.Column(bar_grouping)),
              pp.Plot(b, pp.Column(bar_grouping))])
s2
[15]:

Comparing series in a dataframe

Plot the cumulative percentage difference between input series (or columns of a dataframe). The cumulative difference is always calculated from the start of the observation window. This results in intuitively correct behavior when zooming in or sliding the window, as the chart will dynamically recalculate the values. Incredibly useful for comparing model performance over time for example as one doesn’t need to manually normalize money curves for different periods.

[16]:
s3 = pp.Plot(df_cr,
             pp.PlotOptions(pp.Series(compare="percent")),
             pp.TooltipPct(),
             pp.YAxisPct())
s3
[16]:

Three series on separate side-by-side Y axes

[17]:
s4 = pp.Plot([pp.Plot(a),
            pp.Plot(b, pp.YAxis(pp.Title(text="B Axis"), opposite=True)),
            pp.Plot(c, pp.YAxis(pp.Title(text="C Axis"), opposite=True, offset=40))])
s4
[17]:

Two series on separate subplots

[18]:
s5 = pp.Plot([pp.Plot(a, pp.Line(), pp.YAxis(pp.Title(text="a only"), height=150)),
               pp.Plot(b, pp.Column(), pp.YAxis(pp.Title(text="b only"),
                                                   top=200, height=100, offset=0))],
              pp.Tooltip(value_decimals=2), height="400px")
s5
[18]:

Creating a report from multiple charts and saving as HTML or PDF. Or sending it as email.

[19]:
import pandas.util.testing as pt
b = p.Block([p.Block(pt.makeTimeDataFrame().tail(10), title="A table", title_level=1),
           p.Block([s2, s3], title="Side-by-side Plots", cols=2),
           p.Block(title="Full Width Plots", styles={"page-break-before": "always"}),
           p.Block(s4, title="Side by Side Axes"),
           p.Block(s5, title="Composite Plots")], title="Dynamic Reports")
[20]:
b.save("charts_test.pdf")
b.save("charts_test.html")
['wkhtmltopdf', '--no-stop-slow-scripts', '--debug-javascript', '--javascript-delay', '200', '--page-size', 'A4', '--orientation', 'Portrait', '--enable-smart-shrinking', '/tmp/65a1f98236.html', 'charts_test.pdf'] returned:

None
[20]:
'charts_test.html'