def bqstreamplot(self): Cxs = bq.DateScale() Cys = bq.LinearScale() Cx = self.CallIVtable.index.values Cy = self.CallIVtable.as_matrix().transpose() Ccol = self.CallIVtable.columns.tolist() self.Cline = bq.Lines(x=Cx, y=Cy, scales={'x': Cxs, 'y': Cys}, colors=[i.hex for i in list(Color(rgb=(0.95,0,0)).range_to(Color(rgb=(0.45,0.1,0)), len(Ccol)))], labels=Ccol, enable_hover=True, display_legend=True) Cxax = bq.Axis(scale=Cxs, label='Datetime', grid_lines='solid') Cyax = bq.Axis(scale=Cys, orientation='vertical', tick_format='0.1f', label='CallIV', grid_lines='solid') figC = bq.Figure(marks=[self.Cline], axes=[Cxax, Cyax], animation_duration=1000) Pxs = bq.DateScale() Pys = bq.LinearScale() Px = self.PutIVtable.index.values Py = self.PutIVtable.as_matrix().transpose() Pcol = self.PutIVtable.columns.tolist() self.Pline = bq.Lines(x=Px, y=Py, scales={'x': Pxs, 'y': Pys}, colors=[i.hex for i in list(Color(rgb=(0,0.75,0)).range_to(Color(rgb=(0,0,0.45)), len(Pcol)))], labels=Pcol, enable_hover=True, display_legend=True) Pxax = bq.Axis(scale=Pxs, label='Datetime', grid_lines='solid') Pyax = bq.Axis(scale=Pys, orientation='vertical', tick_format='0.1f', label='PutIV', grid_lines='solid') figP = bq.Figure(marks=[self.Pline], axes=[Pxax, Pyax], animation_duration=1000) display(HBox(([figC,figP])))
def plot_orbit(z0=0.5+0.5*1j, c=0+0*1j): sc_x = bqplot.LinearScale(min=-1.2, max=1.2) sc_y = bqplot.LinearScale(min=-1.2, max=1.2) c_point = bqplot.Scatter(x=[c.real], y=[c.imag], scales={'x': sc_x, 'y': sc_y}, colors=['red'], enable_move=True, default_size=200) c_point.update_on_move = True z_point = bqplot.Scatter(x=[z0.real], y=[z0.imag], scales={'x': sc_x, 'y': sc_y}, colors=['green'], enable_move=True, default_size=200) z_point.update_on_move = True c_label = bqplot.Label(x=[c.real+.05], y=[c.imag+.05], scales={'x': sc_x, 'y': sc_y}, colors=['red'], text=['c'], default_size=26, font_weight='bolder') z_label = bqplot.Label(x=[z0.real+.05], y=[z0.imag+.05], scales={'x': sc_x, 'y': sc_y}, colors=['green'], text=['z0'], default_size=26, font_weight='bolder') scatt = bqplot.Scatter(x=[], y=[], scales={'x': sc_x, 'y': sc_y}, colors=['black'], default_size=20) theta = np.linspace(0, 2.*np.pi, 1000) x = np.cos(theta) y = np.sin(theta) circle = bqplot.Lines(x=x, y=y, scales={'x': sc_x, 'y': sc_y}, colors=['black']) lin = bqplot.Lines(x=[], y=[], scales={'x': sc_x, 'y': sc_y}, colors=['black'], stroke_width=1) def update_line(change=None): out = orbit(z_point.x + 1j*z_point.y, c_point.x + 1j*c_point.y) c_label.x = c_point.x + 0.05 c_label.y = c_point.y + 0.05 z_label.x = z_point.x + 0.05 z_label.y = z_point.y + 0.05 lin.x = out.real lin.y = out.imag scatt.x = out.real.flatten() scatt.y = out.imag.flatten() update_line() # update line on change of x or y of scatter c_point.observe(update_line, names=['x']) c_point.observe(update_line, names=['y']) z_point.observe(update_line, names=['x']) z_point.observe(update_line, names=['y']) ax_x = bqplot.Axis(scale=sc_x, offset=dict(value=0.5), grid_lines='none') ax_y = bqplot.Axis(scale=sc_y, orientation='vertical', offset=dict(value=0.5), grid_lines='none') fig = bqplot.Figure(marks=[scatt, lin, circle, c_point, z_point, c_label, z_label], axes=[ax_x, ax_y], min_aspect_ratio=1, max_aspect_ratio=1) fig.layout.height = '800px' return fig
def test_lines(scales): # since lines can have 2d data, with irregularly shaped data, binary serialization # doesn't work or is trickier with pytest.raises(TraitError, match='.*type object.*'): lines = bqplot.Lines(x=[[0, 1], [0, 1, 2]], y=[[0, 1], [1, 0, -1]], scales=scales) lines = bqplot.Lines(x=[[0, 1], [0, 1]], y=[[0, 1], [1, 0]], scales=scales) state = lines.get_state() lines2 = bqplot.Lines(scales=scales) lines2.set_state(state) assert lines.x[0][0] == 0 assert lines.x[0][1] == 1 assert lines.x[1][1] == 1
def draw_graph(graph, pos=None): from numpy import array import networkx as nx import bqplot as bq if pos is None: pos = nx.spring_layout(graph) nodes = graph.nodes() x = [pos[n][0] for n in nodes] y = [pos[n][1] for n in nodes] lines_x = [] lines_y = [] for k, v in graph.edges(): i1 = graph.nodes().index(k) i2 = graph.nodes().index(v) lines_x.append([x[i1], x[i2]]) lines_y.append([y[i1], y[i2]]) lines_x = array(lines_x) lines_y = array(lines_y) x_sc = bq.LinearScale() y_sc = bq.LinearScale() points = bq.Scatter(x=x, y=y, scales={'x': x_sc, 'y': y_sc}) lines = bq.Lines(x=lines_x, y=lines_y, scales={ 'x': x_sc, 'y': y_sc }, colors=['red']) ax_x = bq.Axis(scale=x_sc) ax_y = bq.Axis(scale=y_sc, orientation='vertical') fig = bq.Figure(marks=[lines, points], axes=[ax_x, ax_y]) return fig
def init_elements(self): self.xscale = bq.LinearScale( min=np.min(self.xvals), max=np.max(self.xvals) ) self.yscale = bq.LinearScale( min=self.ylim[0], max=self.ylim[1] ) self.xax = bq.Axis( scale=self.xscale, label=self.labels['xlabel'], grid_lines='none' ) self.yax = bq.Axis( scale=self.yscale, label=self.labels['ylabel'], orientation='vertical', grid_lines='none' ) self.line = bq.Lines( x=self.xvals, y=self.yvals, scales={'x': self.xscale, 'y': self.yscale}, colors=[self.color], interpolation='cardinal' ) self.handdraw = bqi.HandDraw(lines=self.line) super().__init__( marks=[self.line], axes=[self.xax, self.yax], interaction=self.handdraw )
def make_bq_plot(plot_type, x, y, scales, size, interactions, selected_style, unselected_style, display_legend=False, labels=[''], colors=['#43a2ca'], stroke_width=3, marker='circle'): if plot_type == 'scatter': chart = bqplot.Scatter(x=x, y=y, scales=scales, size=size, interactions=interactions, selected_style=selected_style, unselected_style=unselected_style, display_legend=display_legend, labels=labels, marker=marker, colors=colors) elif plot_type == 'lines': chart = bqplot.Lines(x=x, y=y, colors=colors, stroke_width=stroke_width, scales=scales, size=size) return chart
def make_pixel_intensities_pane(self): FULL_HEIGHT = 800 scales = { 'x': bq.LinearScale(min=0), 'y': bq.LinearScale(min=0, max=255) } self.pixel_intensities_mark = bq.Lines(scales=scales, colors=['blue', 'green', 'red'], display_legend=True, opacities=[0.7] * 3) axes = [bq.Axis(scale=scales['y'], orientation='vertical')] self.pixel_intensities_fig = bq.Figure( marks=[self.pixel_intensities_mark], axes=axes) self.pixel_intensities_fig.layout.width = '100%' self.pixel_intensities_fig.layout.height = str( self.display_pane.size * FULL_HEIGHT) + 'px' self.pixel_intensities_fig.layout.margin = '0' self.pixel_intensities_fig.title = 'Pixel Intensities Along Segment' self.update_pixel_intensities_mark() return ipy.VBox([ self.pixel_intensities_fig, bq.toolbar.Toolbar(figure=self.pixel_intensities_fig) ])
def scatter_drag(x_points: 'Array', y_points: 'Array', *, show_eqn=True, options={}): """ Generates an interactive scatter plot with the best fit line plotted over the points. The points can be dragged by the user and the line will automatically update. Args: x_points (Array Number): x-values of points to plot y_points (Array Number): y-values of points to plot Kwargs: show_eqn (bool): If True (default), displays the best fit line's equation above the scatterplot. {options} Returns: None >>> xs = np.arange(10) >>> ys = np.arange(10) + np.random.rand(10) >>> scatter_drag(xs, ys) VBox(...) """ params = { 'mark': { 'x': x_points, 'y': y_points, 'enable_move': True, } } scat, fig = _create_plot(mark=bq.Scatter, options=options, params=params) # Add line to figure lin = bq.Lines(scales=scat.scales, animation_duration=5000, colors=[GOLDENROD]) fig.marks = [scat, lin] # equation label label = widgets.Label() # create line fit to data and display equation def update_line(change=None): x_sc = scat.scales['x'] lin.x = [x_sc.min if x_sc.min is not None else np.min(scat.x), x_sc.max if x_sc.max is not None else np.max(scat.x)] poly = np.polyfit(scat.x, scat.y, deg=1) lin.y = np.polyval(poly, lin.x) if show_eqn: label.value = 'y = {:.2f} + {:.2f}x'.format(poly[1], poly[0]) update_line() scat.observe(update_line, names=['x', 'y']) layout = widgets.VBox([label, fig]) display(layout)
def __init__(self, model=None, *args, **kwargs): super(GeneratorCostView, self).__init__(*args, **kwargs) if model is not None: self.model = model else: self.model = Generator() self._scale_x = bq.LinearScale(min=self.model.minimum_real_power, max=self.model.maximum_real_power) self._scale_y = bq.LinearScale( min=0, max=(max(self.model.cost_curve_values) * 1.5 + 50)) self._scales = { 'x': self._scale_x, 'y': self._scale_y, } self._scatter = bq.Scatter(x=self.model.cost_curve_points, y=self.model.cost_curve_values, scales=self._scales) self._lines = bq.Lines(x=self.model.cost_curve_points, y=self.model.cost_curve_values, scales=self._scales) self._axes_x = bq.Axis(scale=self._scale_x) self._axes_y = bq.Axis(scale=self._scale_y, orientation='vertical', padding_x=0.025) f = bq.Figure(marks=[ self._lines, self._scatter, ], axes=[ self._axes_x, self._axes_y, ]) children = [f] self.children = children t.link((self.model, 'maximum_real_power'), (self._scale_x, 'max')) t.link((self.model, 'cost_curve_points'), (self._scatter, 'x')) t.link((self.model, 'cost_curve_values'), (self._scatter, 'y')) t.link((self._lines, 'x'), (self._scatter, 'x')) t.link((self._lines, 'y'), (self._scatter, 'y')) # self._scatter.observe(self._callback_ydata, names=['y']) with self._scatter.hold_sync(): self._scatter.enable_move = True self._scatter.update_on_move = True self._scatter.interactions = {'click': None}
def get_input_form(self, figure_title, no_users=100): if self.fig: return self.fig self.figure_title = figure_title max_hours = 24 + 1 max_users = no_users # Define scales x_scale = bqplot.LinearScale(min=0, max=max_hours) y_scale = bqplot.LinearScale(min=0, max=max_users) # Initialize data for our line line = bqplot.Lines( x=np.arange(0, max_hours), y=np.zeros(max_hours), scales={"x": x_scale, "y": y_scale}, fill="bottom", fill_opacities=[0.5], ) # Layout only - axes (plural of axis) x_axis = bqplot.Axis(scale=x_scale, label="Hour", grid_lines="none") y_axis = bqplot.Axis( scale=y_scale, label="Number of Users", grid_lines="none", orientation="vertical", ) def _fix_input_callback(change): # ensures we draw integer values 0 or greater and that # 00:00 [0] and 24:00 [24] represent the same value. with line.hold_sync(): if change["old"][-1] != change["new"][-1]: line.y[0] = line.y[-1] elif change["old"][0] != change["new"][0]: line.y[-1] = line.y[0] line.y = np.fmax(0, np.rint(line.y)) line.observe(_fix_input_callback, names=["y"]) handdraw_interaction = bqplot.interacts.HandDraw(lines=line) self.fig = bqplot.Figure( marks=[line], axes=[x_axis, y_axis], interaction=handdraw_interaction, animation_duration=150, title=self.figure_title, ) return self.fig
def test_bars(scales): with pytest.raises(TraitError, match='.*type object.*'): lines = bqplot.Bars(x=[0, 1], y=[[0, 1], [1, 0, -1]], scales=scales) lines = bqplot.Bars(x=[0, 1], y=[[1, 2], [3, 4]], scales=scales) state = lines.get_state() lines2 = bqplot.Lines(scales=scales) lines2.set_state(state) assert lines.x[0] == 0 assert lines.x[1] == 1 assert lines.y[0][0] == 1 assert lines.y[0][1] == 2 assert lines.y[1][0] == 3 assert lines.y[1][1] == 4
def create_plot(): index = pd.date_range(start='2000-06-01', end='2001-06-01', freq='30min') + timedelta(minutes=15) s = pd.Series(np.full(len(index), np.nan), index=index) x = index.values y = s x_sc = bq.DateScale() y_sc = bq.LinearScale(min=0) line = bq.Lines( x=x, y=y, scales={ 'x': x_sc, 'y': y_sc }, #display_legend=True, labels=["line 1"], #fill='bottom', # opacity does work with this option #fill_opacities = [0.5] *len(x) ) panzoom = bq.PanZoom(scales={'x': [x_sc], 'y': [y_sc]}) #p = bq.Scatter(x=x, y=y, scales= {'x': x_sc, 'y': y_sc}) ax_x = bq.Axis(scale=x_sc) ax_y = bq.Axis(scale=y_sc, orientation='vertical', tick_format='0.2f') #fig = bq.Figure(marks=[line, p], axes=[ax_x, ax_y]) fig = bq.Figure(marks=[line], axes=[ax_x, ax_y], interaction=panzoom) fig.layout.width = '95%' #p.interactions = {'click': 'select', 'hover': 'tooltip'} #p.selected_style = {'opacity': 1.0, 'fill': 'DarkOrange', 'stroke': 'Red'} #p.unselected_style = {'opacity': 0.5} #p.tooltip = bq.Tooltip(fields=['x', 'y'], formats=['', '.2f']) #sel = bq.interacts.IndexSelector(scale=p.scales['x']) # #def update_range(*args): # if sel.selected: # print(sel.selected[0]) # #sel.observe(update_range, 'selected') #fig.interaction = sel return fig, line
def get_marks(self): marks = [] data = self.datafunction() for d, c in zip(data, self.colors): marks.append( bq.Lines( x=[], y=[], icon="line-chart", scales=self.scales, stroke_width=2, fill='bottom', fill_opacities=[0.2], colors=[c], labels=d["labels"], display_legend=True, )) return marks
def make_pred_bqplot(): x_sc = bq.LinearScale() y_sc = bq.LinearScale() ax_x = bq.Axis(label="Feature", scale=x_sc) # , tick_format="0.0f" ax_y = bq.Axis( label="Target", scale=y_sc, orientation="vertical" # , tick_format="0.0e" ) line = bq.Lines( x=[0], y=[0], scales={ "x": x_sc, "y": y_sc }, colors=["darkblue"], opacities=[1], ) scatter = bq.Scatter( x=[0], y=[0], scales={ "x": x_sc, "y": y_sc }, colors=["red"], opacities=[1], ) out_plot = bq.Figure( axes=[ax_x, ax_y], marks=[line, scatter], # interaction=interval_selector, # animation_duration=100, ) out_plot.legend_style = {"stroke-width": 0} out_plot.layout.width = "flex" return {k: v for k, v in locals().items()}
def plot(): co2_conc = in_dd1.value key_x = in_dd2.value key_y = in_dd3.value dir_name = Path(co2_dict[co2_conc]) df = get_df(dir_name) sc_x = bq.LinearScale(min=5, max=25) sc_y = bq.LinearScale() da_x = df[key_x] da_y = df[key_y] ax_x = bq.Axis(scale=sc_x, grid_lines='solid', label=key_x) ax_y = bq.Axis(scale=sc_y, orientation='vertical', label=key_y) lines = bq.Lines(x=da_x, y=da_y, scales={ 'x': sc_x, 'y': sc_y }, stroke_width=3, colors=['blue']) #ax.plot('wavlen_um','total_trans',data=df) #ax.set_title(key) #ax.set_xlim([5,25]) grid[:, 1:2] = bq.Figure(marks=[lines], axes=[ax_x, ax_y], layout=Layout(width='auto', height='auto'), fig_margin=dict(top=60, bottom=40, left=40, right=0), title=key_x + ' vs ' + key_y + ' with CO2 conc. = ' + co2_conc)
def make_segment_mark_and_drawer(self): mark = bq.Lines(scales=self.display_pane.image_plot_scales, x=[0.45, 0.55], y=[0.45, 0.55]) drawer = bq.interacts.BrushSelector( x_scale=self.display_pane.image_plot_scales['x'], y_scale=self.display_pane.image_plot_scales['y'], color='blue') def on_interaction(change): if change['name'] == 'selected_x': mark.x = change['new'] elif change['name'] == 'selected_y': if self.segment_draw_diagonal: mark.y = list(reversed(change['new'])) else: mark.y = change['new'] self.update_observers() drawer.observe(on_interaction, ['selected_x', 'selected_y']) return mark, drawer