def plot_timeseries(server, e, dataset_id): """This defines the initial bqplot time series plot""" dt_x = bq.DateScale() sc_y = bq.LinearScale() constraints = { "time>=": server.get("min_time"), "time<=": server.get("max_time") } df, var = get_timeseries( e=e, dataset=dataset_id, standard_name=server.get("standard_name"), constraints=constraints, ) def_tt = bq.Tooltip(fields=["y"], formats=[".2f"], labels=["value"]) time_series = bq.Lines( x=df.index, y=df[var], scales={ "x": dt_x, "y": sc_y }, tooltip=def_tt, ) ax_x = bq.Axis(scale=dt_x, label="Time") ax_y = bq.Axis(scale=sc_y, orientation="vertical") figure = bq.Figure(marks=[time_series], axes=[ax_x, ax_y]) figure.title = f"{dataset_id[:18]} - {var}" figure.layout.height = "300px" figure.layout.width = "800px" return figure
def create_line(self, y, display_legend=False): try: color = self.colors[self.num_lines % len(self.colors)] self.lines.append( bq.Lines(x=[], y=[], scales={ 'x': self.xscale, 'y': self.yscale }, interpolation='linear', display_legend=display_legend, colors=[color], labels=[y], enable_hover=True)) self.scatters.append( bq.Scatter(x=[], y=[], scales={ 'x': self.xscale, 'y': self.yscale }, colors=[color], enable_hover=True)) self.labels.append(y) self.num_lines += 1 self.lines[-1].tooltip = bq.Tooltip(fields=['name'], show_labels=True) self.lines[-1].interactions = { 'hover': 'tooltip', 'click': 'tooltip' } self.scatters[-1].tooltip = bq.Tooltip(fields=['y', 'x'], labels=[y, self.xlabel], formats=['.4f', ''], show_labels=True) self.scatters[-1].interactions = { 'hover': 'tooltip', 'click': 'tooltip' } except Exception as e: self.debug.append_stdout( "Exception when adding a line and points to plot: {}".format( e.args))
def display(self): pos = networkx.nx_pydot.graphviz_layout(self._graph, prog='dot') x, y = zip(*(pos[node] for node in self._graph.nodes())) fw_id_to_node_index = { self._fw_workflow.fws[i].fw_id: i for i in range(len(self._fw_workflow.fws)) } node_data = [{ 'label': str(node.fw_id), 'name': node.name, 'state': node.state, 'tasks': [str(t) for t in node.tasks], 'shape': 'rect', } for node in self._fw_workflow.fws] link_data = [{ 'source': fw_id_to_node_index[source], 'target': fw_id_to_node_index[target] } for source, target in self._graph.edges()] xs = bqplot.LinearScale(min=min(x), max=max(x)) ys = bqplot.LinearScale(min=min(y), max=max(y)) scales = {'x': xs, 'y': ys} graph = bqplot.Graph(node_data=node_data, link_data=link_data, scales=scales, colors=['white'], link_type='line', highlight_links=False, x=x, y=y, selected_style={ 'stroke': 'yellow', 'stroke-width': '4', 'opacity': '0.5' }) tooltip = bqplot.Tooltip(fields=['name', 'state', 'tasks'], format=['', '', '']) graph.tooltip = tooltip layout = ipywidgets.Layout(min_width='50%', width='auto', min_height='200px', height='auto') fig = bqplot.Figure(marks=[graph], layout=layout) #toolbar = bqplot.Toolbar(figure=fig) #return ipywidgets.VBox([fig, toolbar]) return ipywidgets.VBox([fig])
def display(self): pos = networkx.nx_pydot.graphviz_layout(self._graph, prog='dot') x, y = zip(*(pos[node] for node in self._graph.nodes())) node_data = [{ 'label': str(node._id), 'shape': 'rect', 'tasks': [str(t) for t in node._tasks] } for node in self._graph.nodes()] link_data = [{ 'source': source.index[self], 'target': target.index[self] } for source, target in self._graph.edges()] xs = bqplot.LinearScale() ys = bqplot.LinearScale() scales = {'x': xs, 'y': ys} graph = bqplot.Graph(node_data=node_data, link_data=link_data, scales=scales, colors=['white'], link_type='line', highlight_links=False, x=x, y=y, selected_style={ 'stroke': 'yellow', 'stroke-width': '4', 'opacity': '0.5' }) tooltip = bqplot.Tooltip(fields=['tasks']) graph.tooltip = tooltip layout = ipywidgets.Layout(min_width='50%', width='auto', min_height='200px', height='auto') fig = bqplot.Figure(marks=[graph], layout=layout) return ipywidgets.VBox([fig])
def plot_scatter(self, x=[], y=[], color='red', filt=''): '''Create and return Scatter plot''' #TODO: tooltip format with all data tooltip = bq.Tooltip(fields=['x', 'y'], formats=['.2f', '.2f']) scatt = bq.Scatter(default_size=3, scales={ 'x': self.sc_x, 'y': self.sc_y }, tooltip=tooltip, tooltip_style={'opacity': 0.5}, interactions={'hover': 'tooltip'}, unhovered_style={'opacity': 0.5}, display_legend=True) scatt.colors = [color] scatt.label = filt if ((y != [])): scatt.x = x scatt.y = y scatt.on_element_click(self.plot_images) return scatt
def create_fig(self, *args): logger.info('Creating figure.') tooltip_widget = plt.Tooltip(fields=['size', 'label']) pie = plt.Pie(tooltip=tooltip_widget, interactions={ 'click': 'select', 'hover': 'tooltip' }) pie.radius = 110 pie.inner_radius = 65 pie.font_weight = 'bold' pie.selected_style = { "opacity": "1", "stroke": "white", "stroke-width": "4" } pie.unselected_style = {"opacity": "0.5"} logger.info('Returning figure.') return plt.Figure(marks=[pie])
widget_dsnames = ipyw.Dropdown(options=datasets, value=dataset_id) # This defines the intitial `bqplot` time series plot # In[33]: dt_x = bq.DateScale() sc_y = bq.LinearScale() constraints = {'time>=': search_min_time, 'time<=': search_max_time} df, var = get_data(dataset=dataset_id, standard_name=standard_name, constraints=constraints) def_tt = bq.Tooltip(fields=['y'], formats=['.2f'], labels=['value']) time_series = bq.Lines(x=df.index, y=df[var], scales={ 'x': dt_x, 'y': sc_y }, tooltip=def_tt) ax_x = bq.Axis(scale=dt_x, label='Time') ax_y = bq.Axis(scale=sc_y, orientation='vertical') figure = bq.Figure(marks=[time_series], axes=[ax_x, ax_y]) figure.title = '{} - {}'.format(dataset_id[:18], var) figure.layout.height = '300px' figure.layout.width = '800px' # In[34]:
# Set up axes x_time = bq.LinearScale(min = 0, max=max_half_lifes) y_number = bq.LinearScale(min = 0, max=N_parent) y_fraction = bq.LinearScale(min = 0, max=1) # Labels and scales for Axes ax_x_time = bq.Axis(label=species['timeunits'][init_species_ind], scale=x_time, num_ticks = time_ticks, tick_values = half_life_ticks ) ax_y_number = bq.Axis(label='Number of atoms', scale=y_number, orientation='vertical') ax_y_fraction = bq.Axis(label='Fraction of atoms', scale=y_fraction, orientation='vertical') # Define tooltip (Bug: doesn't allow relabeling Tooltips, also needs to apply to Scatter, not Lines) #def_tt_parent = bq.Tooltip(fields=['x', 'y'], formats=['.2f', '3.0f'], labels=['time', species['parent_short'][init_species_ind]]) #def_tt_daughter = bq.Tooltip(fields=['x', 'y'], formats=['.2f', '3.0f'], labels=['time', species['daughter_short'][init_species_ind]]) def_tt_parent = bq.Tooltip(fields=['x', 'y'], formats=['.2f', '.3f'], labels=['time', 'amount of parent isotope']) def_tt_daughter = bq.Tooltip(fields=['x', 'y'], formats=['.2f', '.3f'], labels=['time', 'amount of daughter isotope']) # Define the Lines and Scatter plots # NOTE: Scatter only necessary to allow tooltips to function. init_x = decay_data['time']*species['half-lives'][init_species_ind] if Plot_all_times: init_parent = decay_data['Parent'] init_daughter = decay_data['Daughter'] else: init_parent = decay_data['Parent'][0:init_time_idx] init_daughter = decay_data['Daughter'][0:init_time_idx] pts_parent = bq.Scatter(x=init_x, y=init_parent, scales={'x': x_time, 'y': y_number}, marker='circle', default_size=2, display_legend=False, colors=['red'], labels=[species['parent_short'][init_species_ind]],
'x': x_ord, 'y': y_sc }, orientation="horizontal", display_legend=True, labels=[ 'Initial Weights', 'Mkt Efficient Portfolio (Max Sharpe)', 'Efficient Portfolio with Views (BL)' ], #orientation decides whether the bars are horizontal or vertical colors=['#4fa110', '#1B84ED', '#F39F41'], opacities=[0.8, 0.9, 1], type='grouped') #bar.type='grouped' bar.tooltip = bqp.Tooltip( fields=['y'], labels=['Weight of Asset'], formats=['.3f']) #this displays the weight placed on each asset. ax_x = bqp.Axis(scale=x_ord, orientation="vertical") ax_y = bqp.Axis(scale=y_sc, label='Weight') #fig_bar = bqp.Figure(marks=[bar], axes=[ax_x, ax_y], padding_x=0.025, padding_y=0.025, #layout=Layout(width='800px'), legend_location='top-right', #fig_margin={'top':20, 'bottom':30, 'left':80, 'right':20}) #fig_bar = bqp.Figure(marks=[bar,bar_labels], axes=[ax_x, ax_y], padding_x=0.025, padding_y=0.025, # layout=Layout(width='600px'), legend_location='top', # fig_margin={'top':20, 'bottom':30, 'left':110, 'right':20}) ax_x = bqp.Axis(scale=x_ord, orientation="vertical", color='Black') ax_y = bqp.Axis(scale=y_sc, tick_format='0.2f', color='White')
class NetworkViewBase(ipyw.VBox): """An interactive, navigable display of the network. The NetworkViewBase class simply generates an interactive figure, without ipywidget buttons and dropdown menus. The NetworkModel extends this class, adding widget controls. Parameters ---------- case : PSSTCase An instance of a PSST case. model : NetworkModel An instance of NetworkModel can be passed instead of a case. (Should not pass both.) Attributes ---------- model : NetworkModel An instance of NetworkModel, containing state information for network. show_gen : Bool Display the points representing generators and connected lines. show_load : Bool Display the points representing loads and connected lines. show_bus_names : Bool Display names next to buses. show_gen_names : Bool Display names next to generators. show_load_names : Bool Display names next to loads. """ model = t.Instance(NetworkModel) show_gen = t.Bool(default_value=True) show_load = t.Bool(default_value=True) show_background_lines = t.Bool(default_value=True) show_bus_names = t.Bool(default_value=True) show_gen_names = t.Bool(default_value=True) show_load_names = t.Bool(default_value=True) def __init__(self, case=None, model=None, *args, **kwargs): super(NetworkViewBase, self).__init__(*args, **kwargs) ################## # Load and Store Model ################## if model and case: warnings.warn( 'You should pass a case OR a model, not both. The case argument you passed is being ignored.' ) if not model: self.model = NetworkModel(case) else: self.model = model ################## # Scale Marks ################## self._scale_x = bq.LinearScale(min=self.model.x_min_view, max=self.model.x_max_view) self._scale_y = bq.LinearScale(min=self.model.y_min_view, max=self.model.y_max_view) self._scales = { 'x': self._scale_x, 'y': self._scale_y, } # Temp/experimental. self._my_scales = { 'x': self._scale_x, 'y': self._scale_y, 'color': bq.ColorScale(colors=['Red', 'Green']), } ################## # Scatter Marks ################## # Tooltip scatter_tooltip = bq.Tooltip(fields=['name']) # Create Bus Scatter self._bus_scatter = bq.Scatter( x=self.model.bus_x_vals, y=self.model.bus_y_vals, scales=self._scales, names=self.model.bus_names, marker='rectangle', default_size=180, colors=[style.graph_main_1], default_opacities=[0.6], selected_style={ 'opacity': 0.8, 'fill': style.graph_selected_1, 'stroke': style.graph_accent_1 }, selected=self._get_indices_view_buses(), tooltip=scatter_tooltip, ) # Create Gen Scatter self._gen_scatter = bq.Scatter( x=self.model.gen_x_vals, y=self.model.gen_y_vals, scales=self._scales, names=self.model.gen_names, marker='circle', default_size=150, colors=[style.graph_main_2], default_opacities=[0.6], selected_style={ 'opacity': 0.8, 'fill': style.graph_selected_2, 'stroke': style.graph_accent_2 }, tooltip=scatter_tooltip, ) # Create Load Scatter self._load_scatter = bq.Scatter( x=self.model.load_x_vals, y=self.model.load_y_vals, scales=self._scales, names=self.model.load_names, marker='triangle-up', default_size=140, colors=[style.graph_main_3], default_opacities=[0.6], selected_style={ 'opacity': 0.8, 'fill': style.graph_selected_3, 'stroke': style.graph_accent_3 }, tooltip=scatter_tooltip, ) ################## # Line Marks ################## # import numpy as np # self.vals = np.random.randint(0, 2, size=len(self.model.bus_x_edges)) # Create Bus Lines self._bus_lines = bq.Lines( x=self.model.bus_x_edges, y=self.model.bus_y_edges, scales=self._scales, # colors=vals. colors=[style.graph_line_1], stroke_width=2, line_style='solid', opacities=[0.8], ) # Create Gen Lines self._gen_lines = bq.Lines( x=self.model.gen_x_edges, y=self.model.gen_y_edges, scales=self._scales, # colors=['black'], colors=[style.graph_line_2], stroke_width=1.5, line_style='solid', opacities=[0.8]) # Create Load Lines self._load_lines = bq.Lines( x=self.model.load_x_edges, y=self.model.load_y_edges, scales=self._scales, # colors=['black'], colors=[style.graph_line_3], stroke_width=1.5, line_style='solid', opacities=[0.8], ) # All lines, in background self._background_lines = bq.Lines( x=self.model.x_edges, y=self.model.y_edges, scales=self._scales, colors=['gray'], stroke_width=1, line_style='dotted', opacities=[0.05], marker='circle', marker_size=30, ) ################## # Bqplot Figure ################## self._all_marks = OrderedDict({ 'background_lines': self._background_lines, 'bus_lines': self._bus_lines, 'gen_lines': self._gen_lines, 'load_lines': self._load_lines, 'bus_scatter': self._bus_scatter, 'gen_scatter': self._gen_scatter, 'load_scatter': self._load_scatter, }) fig_margin = {'top': 0, 'bottom': 0, 'left': 0, 'right': 0} self._figure = bq.Figure( marks=list(self._all_marks.values()), animation_duration=0, fig_margin=fig_margin, ) # Set as children of VBox self.children = [self._figure] # Set defaults, triggering callback functions (setting proper children) self.show_background_lines = False self.show_gen_names = False self.show_load_names = False ################## # Link Traits ################## # Link Scales t.link((self.model, 'x_min_view'), (self._scale_x, 'min')) t.link((self.model, 'x_max_view'), (self._scale_x, 'max')) t.link((self.model, 'y_min_view'), (self._scale_y, 'min')) t.link((self.model, 'y_max_view'), (self._scale_y, 'max')) # Link Bus Scatter t.link((self.model, 'bus_x_vals'), (self._bus_scatter, 'x')) t.link((self.model, 'bus_y_vals'), (self._bus_scatter, 'y')) t.link((self.model, 'bus_names'), (self._bus_scatter, 'names')) # Link Gen Scatter t.link((self.model, 'gen_x_vals'), (self._gen_scatter, 'x')) t.link((self.model, 'gen_y_vals'), (self._gen_scatter, 'y')) t.link((self.model, 'gen_names'), (self._gen_scatter, 'names')) # Link Load Scatter t.link((self.model, 'load_x_vals'), (self._load_scatter, 'x')) t.link((self.model, 'load_y_vals'), (self._load_scatter, 'y')) t.link((self.model, 'load_names'), (self._load_scatter, 'names')) # Link Bus Lines t.link((self.model, 'bus_x_edges'), (self._bus_lines, 'x')) t.link((self.model, 'bus_y_edges'), (self._bus_lines, 'y')) # Link Gen Lines t.link((self.model, 'gen_x_edges'), (self._gen_lines, 'x')) t.link((self.model, 'gen_y_edges'), (self._gen_lines, 'y')) # Link Load Lines t.link((self.model, 'load_x_edges'), (self._load_lines, 'x')) t.link((self.model, 'load_y_edges'), (self._load_lines, 'y')) # Link names to show t.link((self, 'show_bus_names'), (self._bus_scatter, 'display_names')) t.link((self, 'show_gen_names'), (self._gen_scatter, 'display_names')) t.link((self, 'show_load_names'), (self._load_scatter, 'display_names')) # Set callbacks for clicking a bus # Click -> updates `model.view_buses` -> updates `bus_scatter.selected` self._bus_scatter.on_element_click(self._callback_bus_clicked) self.model.observe(self._callback_view_buses_change, names='view_buses') # Callbacks for clicking a load/gen node (Simply flashes selected) self._gen_scatter.on_element_click(self._callback_nonebus_clicked) self._load_scatter.on_element_click(self._callback_nonebus_clicked)