コード例 #1
0
    def __init__(self,
                 root,
                 gene_data,
                 condition_data,
                 samples,
                 genes,
                 conditions,
                 color_pickers={}):
        self._gene_data = gene_data
        self._condition_data = condition_data
        self._genes = genes
        self._conditions = conditions
        self._samples = samples

        self._color_pickers = color_pickers

        self._maxvalue = max(max(gene_data["R1"]), max(gene_data["R2"]),
                             max(gene_data["R3"]))
        self._width = 25
        self._height = 25
        self._linear_color_mapper = None

        self._condition_height = 25

        self._root = Column()
        self._draw()

        root.children.append(self._root)
コード例 #2
0
ファイル: plot.py プロジェクト: chrinide/holoviews
    def initialize_plot(self, ranges=None, plots=[]):
        ranges = self.compute_ranges(self.layout, self.keys[-1], None)
        passed_plots = list(plots)
        plots = [[] for r in range(self.cols)]
        for i, coord in enumerate(self.layout.keys(full_grid=True)):
            r = i % self.cols
            subplot = self.subplots.get(wrap_tuple(coord), None)
            if subplot is not None:
                plot = subplot.initialize_plot(ranges=ranges,
                                               plots=passed_plots)
                plots[r].append(plot)
                passed_plots.append(plots[r][-1])
            else:
                plots[r].append(None)
                passed_plots.append(None)
        if bokeh_version < '0.12':
            plot = BokehGridPlot(children=plots[::-1])
        else:
            plot = gridplot(plots[::-1])
        title = self._get_title(self.keys[-1])
        if title:
            self.handles['title'] = title
            plot = Column(title, plot)
        self.handles['plot'] = plot
        self.handles['plots'] = plots
        if self.shared_datasource:
            self.sync_sources()
        self.drawn = True

        return self.handles['plot']
コード例 #3
0
    def __init__(self,
                 root,
                 gene_data,
                 condition_data,
                 samples,
                 genes,
                 conditions,
                 color_pickers={}):
        self._gene_data = gene_data
        self._condition_data = condition_data
        self._genes = genes
        self._conditions = conditions
        self._samples = samples

        self._color_pickers = color_pickers

        self._width = 25
        self._height = 25
        self._linear_color_mapper = None

        self._condition_height = 25

        self._root = Column()
        self._draw_everything()

        root.children.append(self._root)
コード例 #4
0
ファイル: plot.py プロジェクト: yerfdogyrag/holoviews
    def initialize_plot(self, ranges=None, plots=[]):
        ranges = self.compute_ranges(self.layout, self.keys[-1], None)
        passed_plots = list(plots)
        plots = [[None for c in range(self.cols)] for r in range(self.rows)]
        for i, coord in enumerate(self.layout.keys(full_grid=True)):
            r = i % self.rows
            c = i // self.rows
            subplot = self.subplots.get(wrap_tuple(coord), None)
            if subplot is not None:
                plot = subplot.initialize_plot(ranges=ranges,
                                               plots=passed_plots)
                plots[r][c] = plot
                passed_plots.append(plot)
            else:
                passed_plots.append(None)

        plot = gridplot(plots[::-1],
                        toolbar_position=self.toolbar,
                        merge_tools=self.merge_tools)
        plot = self._make_axes(plot)

        title = self._get_title(self.keys[-1])
        if title:
            plot = Column(title, plot)
            self.handles['title'] = title

        self._update_callbacks(plot)
        self.handles['plot'] = plot
        self.handles['plots'] = plots
        if self.shared_datasource:
            self.sync_sources()
        self.drawn = True

        return self.handles['plot']
コード例 #5
0
ファイル: monitor.py プロジェクト: It4innovations/hyperqueue
 def render(title: str, key: str) -> Column:
     (source, tooltips) = create_global_resource_datasource_and_tooltips(
         time_index, df, key
     )
     figure = prepare_time_range_figure(range, tooltips=tooltips)
     render_global_percent_resource_usage(figure, source, report, hostnames)
     return Column(children=[Div(text=title), figure])
コード例 #6
0
ファイル: test_title.py プロジェクト: sheykholeslam/bokeh
def test_the_default_titles_settings_and_ensure_outside_any_axes(output_file_url, selenium, screenshot):
    # Testing title rendering of background and border is covered in the
    # label test. The title added to plot as the primary title
    #  should always be outside axes and other side renderers.

    source = ColumnDataSource(data=dict(x=[1, 2], y=[1, 2]))

    def make_plot(location, title_align, two_axes=True):
        plot = Plot(
            plot_width=400, plot_height=200,
            x_range=Range1d(0, 2), y_range=Range1d(0, 2),
            toolbar_location=None,
            title="Title %s - %s" % (location, title_align),
            title_location=location,
        )
        plot.title.title_align = title_align
        plot.add_glyph(source, Circle(x='x', y='y', radius=0.4))
        plot.add_layout(LinearAxis(), location)
        if two_axes:
            plot.add_layout(LinearAxis(), location)
        return plot

    layout = Column(
        make_plot('above', 'left', two_axes=False),  # This is a workaround top doesn't like two axes
        make_plot('right', 'right'),
        make_plot('below', 'center'),
        make_plot('left', 'left')
    )

    # Save the plot and start the test
    save(layout)
    selenium.get(output_file_url)

    # Take screenshot
    assert screenshot.is_valid()
コード例 #7
0
def get_checkboxes_with_filter(labels: List[str],
                               column_label: str,
                               source,
                               select_all_btn=True,
                               clear_all_btn=True):
    """
    :param labels: names for checkbox labels as list (dataframe must contain it as value to filter)
    :param column_label: name of column in dataframe
    :param source: dataframe
    :return: checkboxes and filter for graph
    """
    # routes checkboxes
    checkboxes = CheckboxGroup(labels=labels, active=list(range(len(labels))))
    filter = CustomJSFilter(code='''
    var selected = checkboxes.active.map(i=>checkboxes.labels[i]);
    var indices = [];
    var column = source.data[column_label];

    // iterate through rows of data source and see if each satisfies some constraint
    for (var i = 0; i < column.length; i++){
        if(selected.includes(column[i])){
            indices.push(true);
        } else {
            indices.push(false);
        }
    }
    console.log("filter completed");
    return indices;
    ''',
                            args=dict(checkboxes=checkboxes,
                                      column_label=column_label))
    checkboxes.js_on_change(
        "active",
        CustomJS(code="source.change.emit();", args=dict(source=source)))

    widgets = [checkboxes]

    if select_all_btn:
        select_all = Button(label="выбрать все", width=65, height=30)
        select_all.js_on_click(
            CustomJS(args=dict(checkboxes=checkboxes,
                               all_active=list(range(len(labels)))),
                     code="""
            checkboxes.active = all_active
        """))
        widgets.append(select_all)

    if clear_all_btn:
        clear_all = Button(label="отчистить все", width=65, height=30)
        clear_all.js_on_click(
            CustomJS(args=dict(checkboxes=checkboxes),
                     code="""
            checkboxes.active = []
        """))
        widgets.append(clear_all)

    return Column(*widgets), filter
コード例 #8
0
ファイル: cluster_view.py プロジェクト: lumc-pgx/CCS-Amplicon
def make_plot(data, title):
    clusterplot = make_cluster_plot(data)
    phaseplot = make_phase_plot(data)
    add_phaseplot_callback(clusterplot, phaseplot)
    title_div = Div(text=title)

    return Column(
        title_div,
        Row(clusterplot, phaseplot)
    )
コード例 #9
0
def generate_cluster_plot(cluster):
    data = json.loads(cluster.intensity_image)
    bbox = json.loads(cluster.bbox)
    length = bbox[2] - bbox[0]
    width = bbox[3] - bbox[1]

    img = np.array(data)
    source = ColumnDataSource(data={'data': img.flatten()})

    plot = figure(match_aspect=True,
                  width=350,
                  height=350,
                  tools='hover,box_zoom,crosshair,reset,save',
                  tooltips=[("x", "$x"), ("y", "$y"), ("value", "@image")],
                  title="Cluster View")
    im = plot.image(image=[img],
                    x=0,
                    y=0,
                    dw=width,
                    dh=length,
                    palette="Inferno11")

    range_slider_callback = CustomJS(args=dict(source=source, im=im),
                                     code="""
                var image_source = im.data_source;
                var d = image_source.data['image'][0];
                var f = slider.value


                for (var i = 0; i < d.length; i++) {

                        if( source.data['data'][i] >= f[1]){
                            d[i] = f[1];
                        }else if(source.data['data'][i] <= f[0]){
                            d[i] = f[0];
                        } 
                        else{
                            d[i] = source.data['data'][i];
                        }

                }
                image_source.change.emit();
            """)

    # plot.sizing_mode = "fixed"
    plot.toolbar.logo = None
    slider = RangeSlider(start=1,
                         end=np.max(img) + 2,
                         step=1,
                         title="View Window",
                         value=(1, np.max(img)))
    slider.js_on_change('value', range_slider_callback)
    range_slider_callback.args['slider'] = slider

    return Column(slider, plot)
コード例 #10
0
def generate_frame_plot(frame):
    sparse_data = json.loads(frame.frame_data)

    img = np.array(sparse_to_dense(sparse_data))
    source = ColumnDataSource(data={'data': img.flatten()})
    plot = figure(x_range=(0, 256),
                  y_range=(0, 256),
                  width=750,
                  height=750,
                  tools='hover,box_zoom,crosshair,reset,save',
                  tooltips=[("x", "$x"), ("y", "$y"), ("value", "@image")],
                  title="Frame {}".format(frame.id))
    im = plot.image(image=[img], x=0, y=0, dw=256, dh=256, palette="Viridis11")

    range_slider_callback = CustomJS(args=dict(source=source, im=im),
                                     code="""
                var image_source = im.data_source;
                var d = image_source.data['image'][0];
                var f = slider.value


                for (var i = 0; i < d.length; i++) {

                        if( source.data['data'][i] >= f[1]){
                            d[i] = f[1];
                        }else if(source.data['data'][i] <= f[0]){
                            d[i] = f[0];
                        } 
                        else{
                            d[i] = source.data['data'][i];
                        }

                }
                image_source.change.emit();
            """)

    for i, cluster in enumerate(frame.clusters):
        bbox = json.loads(cluster.bbox)
        label = Label(x=bbox[3],
                      y=bbox[2],
                      text=str(i + 1),
                      text_color='red',
                      text_font_size="8pt")
        plot.add_layout(label)
    slider = RangeSlider(start=1,
                         end=np.max(img) + 2,
                         step=1,
                         title="View Window",
                         value=(1, np.max(img)))
    slider.js_on_change('value', range_slider_callback)
    range_slider_callback.args['slider'] = slider
    plot.toolbar.logo = None
    layout = Column(slider, plot)

    return layout
コード例 #11
0
    def __initialize_bokeh_graphics(self):
        """
        Bokeh grafikonok alap elrendezese.
        """
        self.line1_color = "#FF4242"
        self.line2_color = "#0A284B"
        self.line3_color = "#0072B2"

        self.select_widget = Select(title="Valutapár",
                                    options=list(self.__asset_pairs.keys()),
                                    value="XBTUSD")
        self.select_widget.on_change("value", self.__change_asset_pair)
        self.__asset_pair = self.__asset_pairs[self.select_widget.value]

        self.title_div = Div(text="<b>Kriptovaluta árfolyamok</b>",
                             style={
                                 "font-size": "150%",
                                 "height": "50px"
                             })

        self.price_div = Div(text="<b> </b>",
                             style={
                                 "font-size": "200%",
                                 "color": self.line1_color
                             })
        self.avg10_div = Div(text="<b> </b>",
                             style={
                                 "font-size": "150%",
                                 "color": self.line2_color
                             })
        self.avg40_div = Div(text="<b> </b>",
                             style={
                                 "font-size": "150%",
                                 "color": self.line3_color
                             })

        self.controls = Column(self.title_div, self.select_widget,
                               self.price_div, self.avg10_div, self.avg40_div)

        self.__make_plot()
        self.layout = Row(self.controls, Column(self.plot1, self.plot2))
        curdoc().theme = "light_minimal"
コード例 #12
0
ファイル: transit_fitter.py プロジェクト: golmschenk/ramjet
 def bokeh_application(self, bokeh_document):
     light_curve_figure = self.create_light_curve_figure()
     folded_figure = self.create_folded_figured_based_on_clicks_in_unfolded_figure(
         light_curve_figure)
     run_fitting_button = Button(label='Run fitting')
     initial_fit_figure, parameters_table = self.create_mcmc_fit_figures(
         run_fitting_button)
     column = Column(light_curve_figure, folded_figure, run_fitting_button,
                     initial_fit_figure, parameters_table)
     column.sizing_mode = 'stretch_width'
     bokeh_document.add_root(column)
コード例 #13
0
def index():
    p = figure(plot_height=350, plot_width=400, title="", toolbar_location=None,
             tools="reset,box_zoom,pan,wheel_zoom,box_select,save", 
             webgl=True, responsive=True)

    #add some data like a line, circles, etc to p

    plot = Column(p,width=400,height=350)
    
    script, div = components(plot)
    return render_template('graph_tdi.html',script=script,div=div)
コード例 #14
0
def plot(df, feauture):
    def create_plot(source,country, feauture):
        hover = HoverTool(tooltips=[("Date", "@date{%F}"), (feauture, str('@'+feauture))],
                      formatters = {'@date':'datetime'})
        p = figure(plot_width=900, plot_height=500,x_axis_type="datetime",
                   title="Total Covid-19 {} in {} by date".format(feauture, country),
                    toolbar_location='above')
        p.line(x='date', y=feauture, line_width=1, source=source,
               line_color="black")
        p.vbar(x='date', top=feauture, line_width=1, source=source, fill_color='orange', hover_fill_color='grey',
               hover_fill_alpha=1)

        p.add_tools(hover)
        p.xaxis.axis_label = 'Date'
        p.yaxis.axis_label = 'Number of {}'.format(feauture)
        p.axis.axis_label_text_font_style = 'bold'
        p.yaxis.formatter = NumeralTickFormatter(format = '0.0a')
        p.background_fill_color = "beige"

        return p

    def update(attr, old, new):
        country = country_select.value
        new_df = df[df['location'] == country]
        start = datetime.fromtimestamp(date_select.value[0] / 1000)
        end = datetime.fromtimestamp(date_select.value[1] / 1000)
        new_df = new_df[new_df['date'] >= start]
        new_df = new_df[new_df['date'] <= end]
        new_src = ColumnDataSource(new_df)
        source.data.update(new_src.data)
        p.title.text = 'Total covid-19 {} in {}'.format(feauture, country)




    countries = list(df['location'].unique())

    country_select = Select(title = 'Country', value = 'world', options = countries)
    country_select.on_change('value', update)

    date_select = DateRangeSlider(title = 'Date Range', start = min(df['date']), end = max(df['date']),
                              value = (min(df['date']), max(df['date'])), step = 15)
    date_select.on_change('value', update)

    initial_country = country_select.value
    source = ColumnDataSource(df[df['location'] == initial_country])

    p = create_plot(source, initial_country, feauture)

    controls = Column(country_select, date_select)

    layout = row(controls, p)
    return layout
コード例 #15
0
ファイル: overview.py プロジェクト: fredykoci/hyperqueue
def render_environment(
    level: int,
    entry_map: EntryMap,
    environment: str,
    environment_params: str,
    data: pd.DataFrame,
) -> LayoutDOM:
    content = [Div(text="<h3>Aggregated durations</h3>", **style())]

    durations = data["duration"]
    with pd_print_all():
        table = durations.describe().to_frame().transpose()
        content.append(Div(text=table.to_html(justify="center"), **style()))

    content.append(render_durations("Durations", durations=durations))

    runs = []
    items = sorted(data.itertuples(index=False), key=lambda v: v.index)

    content.append(Div(text="<h3>Individual runs</h3>"))
    for item in items:
        entry = entry_map.get(item.key)
        if entry is not None:
            benchmark_content = render_benchmark(entry)
            runs.append(Panel(child=benchmark_content, title=str(item.index)))

    content.append(Tabs(tabs=runs, **style()))

    return Column(
        children=[
            Div(
                text=
                f"<div style='font-size: 16px; font-weight: bold;'>{environment}: "
                f"{environment_params}</div>",
                **style(),
            ),
            Column(children=content, **style(level=level + 1)),
        ],
        **style(level=level),
    )
コード例 #16
0
ファイル: monitor.py プロジェクト: fredykoci/hyperqueue
        def render_process(pid: int) -> Optional[Model]:
            process_data = node_data[node_data[PID_KEY] == pid]
            max_rss = process_data[RSS_KEY].max()
            avg_cpu = process_data[AVG_CPU_KEY].mean()
            process = [
                p for p in report.cluster.nodes[node.hostname].processes if p.pid == pid
            ]
            if not process:
                logging.warning(f"Process {node.hostname}/{pid} not found in cluster")
                return
            process = process[0]

            range = get_time_range(process_data[DATETIME_KEY])

            mib_divisor = 1024.0 * 1024
            mem = resample(
                process_data[RSS_KEY] / mib_divisor, process_data[DATETIME_KEY]
            )
            mem_figure = prepare_time_range_figure(range)
            mem_figure.yaxis[0].formatter = NumeralTickFormatter()
            mem_figure.yaxis.axis_label = "RSS (MiB)"
            mem_figure.y_range = Range1d(0, max_rss / mib_divisor + 100.0)
            mem_figure.add_tools(HoverTool(tooltips=[("RSS (MiB)", "@rss")]))

            data = ColumnDataSource(dict(rss=mem, x=mem.index))
            mem_figure.line(
                x="x", y="rss", color="red", legend_label="Memory", source=data
            )

            cpu = resample(process_data[AVG_CPU_KEY], process_data[DATETIME_KEY])
            cpu_figure = prepare_time_range_figure(range)
            cpu_figure.yaxis[0].formatter = NumeralTickFormatter(format="0 %")
            cpu_figure.yaxis.axis_label = "Avg. CPU usage (%)"
            cpu_figure.y_range = Range1d(0, 1)
            cpu_figure.add_tools(HoverTool(tooltips=[("Avg. CPU usage", "@cpu")]))

            data = ColumnDataSource(dict(cpu=cpu / 100.0, x=cpu.index))
            cpu_figure.line(
                x="x", y="cpu", color="blue", legend_label="CPU usage (%)", source=data
            )

            summary = PreText(
                text=f"""
PID: {pid}
Key: {process.key}
Max. RSS: {humanize.naturalsize(max_rss, binary=True)}
Avg. CPU: {avg_cpu:.02f} %
""".strip()
            )

            columns = [summary, mem_figure, cpu_figure]
            return Panel(child=Column(children=columns), title=process.key)
コード例 #17
0
 def _make_axes(self, plot):
     width, height = self.renderer.get_size(plot)
     x_axis, y_axis = None, None
     kwargs = dict(sizing_mode=self.sizing_mode)
     keys = self.layout.keys(full_grid=True)
     if self.xaxis:
         flip = self.shared_xaxis
         rotation = self.xrotation
         lsize = self._fontsize('xlabel').get('fontsize')
         tsize = self._fontsize('xticks', common=False).get('fontsize')
         xfactors = list(unique_iterator([wrap_tuple(k)[0] for k in keys]))
         x_axis = make_axis('x',
                            width,
                            xfactors,
                            self.layout.kdims[0],
                            flip=flip,
                            rotation=rotation,
                            label_size=lsize,
                            tick_size=tsize)
     if self.yaxis and self.layout.ndims > 1:
         flip = self.shared_yaxis
         rotation = self.yrotation
         lsize = self._fontsize('ylabel').get('fontsize')
         tsize = self._fontsize('yticks', common=False).get('fontsize')
         yfactors = list(unique_iterator([k[1] for k in keys]))
         y_axis = make_axis('y',
                            height,
                            yfactors,
                            self.layout.kdims[1],
                            flip=flip,
                            rotation=rotation,
                            label_size=lsize,
                            tick_size=tsize)
     if x_axis and y_axis:
         plot = filter_toolboxes(plot)
         r1, r2 = ([y_axis, plot], [None, x_axis])
         if self.shared_xaxis:
             r1, r2 = r2, r1
         if self.shared_yaxis:
             r1, r2 = r1[::-1], r2[::-1]
         models = layout_padding([r1, r2], self.renderer)
         plot = gridplot(models, **kwargs)
     elif y_axis:
         models = [y_axis, plot]
         if self.shared_yaxis: models = models[::-1]
         plot = Row(*models, **kwargs)
     elif x_axis:
         models = [plot, x_axis]
         if self.shared_xaxis: models = models[::-1]
         plot = Column(*models, **kwargs)
     return plot
コード例 #18
0
def time_series(grouper):
    def make_plot(src):
        pp = figure(title='Rating Time Series: CAM CORPORATE', title_location='above', plot_width=500, plot_height=500,
                    x_axis_label='Date',
                    y_axis_label='Number Rated', x_axis_type='datetime')

        pp.line('time', 'NVF', line_color='purple', line_width=3, source=src)
        hover = HoverTool(tooltips=[('Date', '@time{%Y-%m}'), ('NB Rated', '@NVF')],
                          formatters={'@time': 'datetime', '@NVF': 'numeral'})
        pp.add_tools(hover)
        pp.title.align = "center"
        pp.title.text_font_size = "12px"
        pp.axis.axis_label_text_font_style = 'bold'
        pp.axis.axis_label_text_font_size = '20pt'
        pp.axis.major_label_text_font_size = '10pt'

        return pp

    def update_plot(attr, old, new):
        # read the current value of the dropdown
        cmr = camr_select.value
        # set new_data
        new_data = {
            'time': grouper[grouper['CAMR'] == cmr]['date'],
            'NVF': grouper[grouper['CAMR'] == cmr]['NVF']
        }

        # Assign new_data to the original source
        src.data = new_data

        # add the title
        p.title.text = 'Rating Time Series: %s' % cmr

    camr_select = Select(options=sorted(list(grouper['CAMR'].unique())), value='CAM CORPORATE', title='CAM Region')
    # attach the update to the value
    camr_select.on_change('value', update_plot)

    # Data
    data = {'time': grouper[grouper['CAMR'] == 'DOMAINE GRC']['date'],
            'NVF': grouper[grouper['CAMR'] == 'DOMAINE GRC']['NVF']}
    src = ColumnDataSource(data=data)

    # Plot
    p = make_plot(src)

    layout = column([Column(camr_select, width = 500), p])

    tab = Panel(child=layout, title='Rating Times series per CAMR')

    return tab
コード例 #19
0
def plot_church_data():

    args = parse_args()
    load_saved_visible_categories()

    conn = sql.connect(app.config['DB_LOCATION'])
    church_info = pd.read_sql("select * from churches", conn)

    if not validate_filters(church_info, args['filter_by'][0],
                            args['filter_choice'][0]):
        raise LegacyException("Invalid filter parameters %s %s" %
                              (args['filter_by'][0], args['filter_choice'][0]))
    filter_widget, selected = make_filter_widget(church_info,
                                                 args['filter_by'][0],
                                                 args['filter_choice'][0])

    for prop in args['properties']:
        if not is_valid_category(prop):
            raise LegacyException("Invalid property %s" % prop)
        set_category_visibility(prop)

    if args['plot_type'][0] not in PLOT_TYPES:
        raise LegacyException("Invalid plot type %s" % args['plot_type'][0])

    if args['plot_type'][0] == "Time Series":
        church_data = load_churches_data(conn, args['properties'][:1],
                                         args['filter_by'][0], selected)
        plot = make_time_series_plot(church_data, args['properties'][0])
    elif args['plot_type'][0] == "Histogram":
        church_data = load_churches_data(conn, args['properties'][:1],
                                         args['filter_by'][0], selected)
        plot = make_histogram_plot(church_data, args['properties'][0])
    elif args['plot_type'][0] == "Comparison":
        church_data = load_churches_data(conn, args['properties'],
                                         args['filter_by'][0], selected)
        plot = make_comparison_plot(church_data, args['properties'])

    plot_app = Column(
        make_plot_type_buttons(args['plot_type'][0]),
        Row(plot, filter_widget),
    )

    script, div = components(plot_app)

    html = flask.render_template('index.html',
                                 plot_script=script,
                                 plot_div=div,
                                 **args)

    return html
コード例 #20
0
def large_plot(n):
    from bokeh.models import (
        Plot, LinearAxis, Grid, GlyphRenderer,
        ColumnDataSource, DataRange1d, PanTool, ZoomInTool, ZoomOutTool, WheelZoomTool, BoxZoomTool,
        BoxSelectTool, SaveTool, ResetTool
    )
    from bokeh.models import Column, Line

    col = Column()
    objects = set([col])

    for i in range(n):
        source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1]))
        xdr = DataRange1d()
        ydr = DataRange1d()
        plot = Plot(x_range=xdr, y_range=ydr)
        xaxis = LinearAxis()
        plot.add_layout(xaxis, "below")
        yaxis = LinearAxis()
        plot.add_layout(yaxis, "left")
        xgrid = Grid(dimension=0)
        plot.add_layout(xgrid, "center")
        ygrid = Grid(dimension=1)
        plot.add_layout(ygrid, "center")
        tickers = [xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter]
        glyph = Line(x='x', y='y')
        renderer = GlyphRenderer(data_source=source, glyph=glyph)
        plot.renderers.append(renderer)
        pan = PanTool()
        zoom_in = ZoomInTool()
        zoom_out = ZoomOutTool()
        wheel_zoom = WheelZoomTool()
        box_zoom = BoxZoomTool()
        box_select = BoxSelectTool()
        save = SaveTool()
        reset = ResetTool()
        tools = [pan, zoom_in, zoom_out, wheel_zoom, box_zoom, box_select, save, reset]
        plot.add_tools(*tools)
        col.children.append(plot)
        objects |= set([
            xdr, ydr,
            xaxis, yaxis,
            xgrid, ygrid,
            renderer, renderer.view, glyph,
            source, source.selected, source.selection_policy,
            plot, plot.x_scale, plot.y_scale, plot.toolbar, plot.title,
            box_zoom.overlay, box_select.overlay,
        ] + tickers + tools)

    return col, objects
コード例 #21
0
    def slider_plot(self, fig, x, y, hue):
        def update_plot(attr, old, new):
            time = slider.value
            new_data = {'x' : self.dataframe.loc[time][x], 'y' : self.dataframe.loc[time][y], hue : self.datafram.loc[time][hue]}
            self.source.data = new_data





        slider = Slider(start=20200224, end=20210415, step=1, value=20200224, title='Time')
        slider.on_change('value', update_plot)
        layout = row(Column(slider), fig)
        return layout
コード例 #22
0
ファイル: nc_plot.py プロジェクト: NorDataNet/metsis-deploy
def create_page(data):
    plot = create_plot(data)
    title = data.variable_metadata['long_name']
    summary = data.dataset_metadata['summary']
    dataset_metadata = json2html.convert(json=data.dataset_metadata)
    variable_metadata = json2html.convert(json=data.variable_metadata)
    title_div = Div(text="""<h1>
                                <b>
                                    {title}
                                </b>
                            </h1>""".format(title=title))

    abstract_text = Div(text="""<details>
                                    <summary>
                                        Summary
                                    </summary>
                                    <p>
                                        {summary}
                                    </p>
                                </details>""".format(summary=summary),
                        width=400,
                        height=200)

    dataset_metadata_div = Div(text="""<details>
                                           <summary>
                                               Dataset Metadata
                                           </summary>
                                           <p>
                                               {dataset_metadata}
                                           </p>
                                        </details>""".format(dataset_metadata=dataset_metadata),
                               width=300,
                               height=100)

    variable_metadata_div = Div(text="""<details>
                                            <summary>
                                                Variable Metadata
                                            </summary>
                                            <p>
                                                {variable_metadata}
                                            </p>
                                        </details>""".format(variable_metadata=variable_metadata),
                                width=200,
                                height=100)

    plot_caption = Paragraph(text="""This text can be a figure caption.""",
                             width=200,
                             height=100)
    return Column(title_div, abstract_text, plot, plot_caption, variable_metadata_div, dataset_metadata_div)
コード例 #23
0
    def __init__(self,
                 root,
                 columns=8,
                 conditions=tuple(),
                 colors={},
                 app=None):
        self.app = app
        self._conditions = conditions.copy()
        self.colors = colors
        self._root_widget = Column()
        self._columns = columns
        self.color_pickers = {}
        root.children.append(self._root_widget)

        self._redraw_conditions()
コード例 #24
0
ファイル: overview.py プロジェクト: fredykoci/hyperqueue
def generate_summary_html(database: Database, directory: Path) -> Path:
    entry_map = pregenerate_entries(database, directory)
    df = create_database_df(database)

    columns = []
    for (group, group_data) in groupby_workload(df):
        columns.append(
            render_workload(0, entry_map, group[0], group[1], group_data))

    page = Column(children=columns, **style())
    ensure_directory(directory)

    result_path = directory / "index.html"
    save(page, result_path, title="Benchmarks", resources=CDN)
    return result_path
コード例 #25
0
ファイル: monitor.py プロジェクト: It4innovations/hyperqueue
def render_nodes_resource_usage(
    report: ClusterReport, resources_df: pd.DataFrame
) -> LayoutDOM:
    items = sorted(resources_df.groupby(HOSTNAME_KEY), key=lambda item: item[0])
    rows = []
    for (hostname, node_data) in items:
        utilization = render_node_utilization(node_data)

        header_text = get_node_description(report, hostname)
        header = Div(
            text=header_text,
            render_as_text=True,
            style={"font-size": "20px", "font-weight": "bold"},
        )
        rows.append(Column(children=[header, utilization]))
    return column(rows)
コード例 #26
0
ファイル: visual.py プロジェクト: nanthony21/mc_app
 def __init__(self):
     self.idLabel = Paragraph(text='ID = ')
     self.speciesLabel = Paragraph(text='Species = ')
     self.typeLabel = Paragraph(text='Type = ')
     self.birthDateLabel = Paragraph(text='Birth Date = ')
     self.notesLabel = PreText(text='Notes = ')
     self.addNoteButton = Button(label='Add Note')
     self.imagesLabel = Paragraph(text='# of Images = ')
     self.loadImageButton = Button(label='Upload Image',
                                   button_type='success')
     self.deleteButton = Button(label='Delete Sample!!',
                                button_type='danger')
     self.widget = Column(self.idLabel, self.speciesLabel, self.typeLabel,
                          self.birthDateLabel, self.notesLabel,
                          self.addNoteButton, self.imagesLabel,
                          self.loadImageButton, self.deleteButton)
コード例 #27
0
    def make_document(self, doc):
        doc.title = "Connor's MACD autotrader"
        doc.add_periodic_callback(self.update, 5000)

        #https://stackoverflow.com/questions/56137866/how-to-display-plot-in-bokeh-div

        #stuff on the side of graph
        external = Column()
        external.children.append(self.priceDIV)
        external.children.append(self.positionDIV)
        external.children.append(self.lastTradeDIV)

        layout = Row()
        layout.children.append(self.plot)
        layout.children.append(external)
        doc.add_root(layout)
コード例 #28
0
def _export_plots_and_layout(title, plots, outdir_path):
    """Save all plots as png and the layout as html.

    Args:
        title (bokeh.Div): title element.
        plots (list): list of bokeh plots
        outdir_path (pathlib.Path): base path to which to append the plot name to build
            the path where to save each plot.

    """
    for p in plots:
        outpath = outdir_path / f"{p.name}.png"
        output_file(outpath)
        export_png(p, filename=outpath)

    output_file(outdir_path / "overview.html")
    save(Column(title, *plots))
コード例 #29
0
ファイル: overview.py プロジェクト: fredykoci/hyperqueue
def render_workload(
    level: int,
    entry_map: EntryMap,
    workload: str,
    workload_params: str,
    data: pd.DataFrame,
) -> LayoutDOM:
    columns = [
        Div(text=f"""<div style='font-size: 18px; font-weight: bold;'>
{workload}: {workload_params}
</div>""")
    ]
    for (group, group_data) in groupby_environment(data):
        columns.append(
            render_environment(level + 1, entry_map, group[0], group[1],
                               group_data))
    return Column(children=columns, **style(level=level))
コード例 #30
0
def add_count_toggle(plot):
    from bokeh.layouts import widgetbox
    from bokeh.models import (CustomJS, Column, Circle, Rect, ColumnDataSource,
                              LinearColorMapper, ColorBar, Label)
    from bokeh.models.widgets import RadioButtonGroup

    args = dict(
        circle=None,
        rect=None,
    )
    for r in plot.references():
        if isinstance(r, Circle):
            args['circle'] = r
        elif isinstance(r, Rect):
            args['rect'] = r
        elif isinstance(r, LinearColorMapper):
            args['cmapper'] = r
        elif isinstance(r, ColorBar):
            args['cbar'] = r
        elif isinstance(r, ColumnDataSource):
            args['ds'] = r
        elif isinstance(r, Label):
            args['title'] = r

    callback = CustomJS(args=args,
                        code="""
       var label = cb_obj.labels[cb_obj.active];
       var selection = {Observations: 'count', Subjects: 'subjects'}[label];
       if (circle !== null) {circle.fill_color.field = selection};
       if (rect !== null && rect.fill_color) {rect.fill_color.field = selection };
       var max_val = Math.max.apply(null, ds.data[selection]);
       cmapper.high = max_val;
       cbar.ticker.ticks = [0, max_val];
       split_title = title.text.split(' ');
       split_title[2] = label.toLowerCase();
       title.text = split_title.join(' ');
       ds.trigger("change");
    """)

    plot.min_border_top = 50
    radio_button_group = RadioButtonGroup(labels=["Observations", "Subjects"],
                                          active=0)
    radio_button_group.callback = callback
    widgets = widgetbox(radio_button_group, width=300)
    return Column(widgets, plot)