コード例 #1
0
    def plot_ripple_grid(self, num_x=3, num_y=None, return_list=True):
        if num_y is None:
            num_y = int(math.ceil(len(self.riptimes) / float(num_x)))

        plt_grp_size = num_x * num_y
        plt_num_grps = int(math.ceil(self.riptimes.get_num_events()/plt_grp_size))
        plot_list = []

        rip_ids = self.riptimes.index.get_level_values('event')
        rip_plt_grps = [[rip_ids[(grp_id * plt_grp_size) + entry_ind] for entry_ind in
                         range(min([len(rip_ids) - plt_grp_size * grp_id, plt_grp_size]))]
                         for grp_id in range(plt_num_grps)]

        if (len(rip_plt_grps) > 1) and (return_list is False):
            raise VisualizationConfigError("Can't set return_list=False when grid cannot hold all plots.")

        if return_list:
            for rip_plt_grp in rip_plt_grps:
                lay = hv.Layout([self.plot_ripple_all(rip_id) for rip_id in rip_plt_grp]).cols(num_x)

                plot_list.append(lay)

            return plot_list

        else:
            lay = hv.Layout({rip_id: self.plot_ripple_all(rip_id) for rip_id in rip_plt_grps[0]}).cols(num_x)
            return lay
コード例 #2
0
    def plot_view(self):

        data = self.df[self.feature.value]
        data = data.loc[data.first_valid_index():]

        if self.log_scale.value:
            data = pd.Series(np.log(data.values), index=data.index)
            data.name = f"{self.feature.value}  - log of closing price"
        else:
            data.name = f"{self.feature.value}  - closing price"

        df_ma_15 = data.rolling(window=15).mean()
        df_ma_30 = data.rolling(window=30).mean()

        df_ma_15.name = "moving average - 15 days"
        df_ma_30.name = "moving average - 30 days"

        tag_plot = data.hvplot.line(title=self.feature.value,
                                    xlabel="Timestamp",
                                    height=self.plot_height,
                                    width=self.plot_width)

        ma_15 = df_ma_15.hvplot.line(title=self.feature.value,
                                     xlabel="Timestamp",
                                     height=self.plot_height,
                                     width=self.plot_width)
        ma_30 = df_ma_30.hvplot.line(title=self.feature.value,
                                     xlabel="Timestamp",
                                     height=self.plot_height,
                                     width=self.plot_width)

        min_ = self.tag_bounds[self.feature.value][0]
        max_ = self.tag_bounds[self.feature.value][1]

        if self.log_scale.value:
            min_, max_ = data.min(), data.max()

        histogram = data.hvplot.hist(bins=100,
                                     bin_range=(min_, max_),
                                     muted_alpha=0,
                                     legend="top",
                                     height=400,
                                     width=200,
                                     title="Histogram")
        right_col = [histogram]

        frame = data.describe().reset_index()
        description_table = hv.Table(frame).opts(height=250, width=400)

        second_plot = hv.Layout(histogram + description_table).cols(2)

        plots = hv.Layout(((tag_plot * ma_15 * ma_30) << histogram) +
                          description_table).cols(1)

        return plots
コード例 #3
0
    def write_histogram_for_annotation_worktime_by_user(self, df: pandas.DataFrame) -> None:
        """
        教師付者ごとに教師付時間のヒストグラムを出力する。

        Args:
            df: タスク一覧のDataFrame

        """

        if len(df) == 0:
            logger.info("タスク一覧が0件のため出力しません。")
            return

        output_file_worktime = f"{self.histogram_outdir}/ヒストグラム-1回目の教師付者ごと-教師付時間"
        logger.debug(f"{output_file_worktime}.html を出力します。")
        output_file_first_worktime = f"{self.histogram_outdir}/ヒストグラム-1回目の教師付者ごと-1回目の教師付時間"
        logger.debug(f"{output_file_first_worktime}.html を出力します。")

        first_annotation_user_id_list = df["first_annotation_user_id"].dropna().unique().tolist()
        if len(first_annotation_user_id_list) == 0:
            logger.info("教師付したタスクが1つもないので、出力しません。")
            return

        histograms_worktime = []
        histograms_first_worktime = []
        for user_id in first_annotation_user_id_list:

            filtered_df = df[df["first_annotation_user_id"] == user_id]
            username = filtered_df.iloc[0]["first_annotation_username"]
            histograms_worktime.append(
                self._create_histogram_by_user(
                    filtered_df, "annotation_worktime_hour", "教師付時間[hour]", user_id=user_id, username=username
                )
            )
            histograms_first_worktime.append(
                self._create_histogram_by_user(
                    filtered_df, "first_annotation_worktime_hour", "1回目の教師付時間[hour]", user_id=user_id, username=username
                )
            )

        layout_worktime = (
            hv.Layout(histograms_worktime).cols(3).opts(hv.opts.Histogram(width=500), hv.opts.Layout(shared_axes=True))
        )
        hv.renderer("bokeh").save(layout_worktime, output_file_worktime)

        layout_first_worktime = (
            hv.Layout(histograms_first_worktime)
            .cols(3)
            .opts(hv.opts.Histogram(width=500), hv.opts.Layout(shared_axes=True))
        )
        hv.renderer("bokeh").save(layout_first_worktime, output_file_first_worktime)
コード例 #4
0
def fermi_surface_slices(arr: xr.DataArray,
                         n_slices=9,
                         ev_per_slice=0.02,
                         bin=0.01,
                         out=None,
                         **kwargs):
    import holoviews as hv  # pylint: disable=import-error
    slices = []
    for i in range(n_slices):
        high = -ev_per_slice * i
        low = high - bin
        image = hv.Image(arr.sum([
            d for d in arr.dims
            if d not in ['theta', 'beta', 'phi', 'eV', 'kp', 'kx', 'ky']
        ]).sel(eV=slice(low, high)).sum('eV'),
                         label='%g eV' % high)

        slices.append(image)

    layout = hv.Layout(slices).cols(3)
    if out is not None:
        renderer = hv.renderer('matplotlib').instance(fig='svg', holomap='gif')
        filename = path_for_plot(out)
        renderer.save(layout, path_for_holoviews(filename))
        return filename
    else:
        return layout
コード例 #5
0
def plotQC(df, value, title, size=10, jitter=0.35, factor_reduce=0.5):
    df_i = df.dropna(subset=[value])
    df_i = df_i.reset_index(drop=True)
    key_dimensions = [(value, title)]
    value_dimensions = [('Gene', 'Gene'), ('Metadata_X', 'Position')]
    macro = hv.Table(df_i, key_dimensions, value_dimensions)
    options = dict(color_index='Position',
                   legend_position='left',
                   jitter=jitter,
                   width=1000,
                   height=600,
                   scaling_method='width',
                   scaling_factor=2,
                   size_index=2,
                   show_grid=True,
                   tools=['hover', 'box_select', 'lasso_select'],
                   line_color='k',
                   cmap='Category20',
                   size=size,
                   nonselection_color='lightskyblue')
    quality_scatter = macro.to.scatter('Gene', [title]).options(**options)
    sel = streams.Selection1D(source=quality_scatter)

    image_name = df_i.loc[0, "img_name_raw"]
    img = cv2.imread(image_name, 0)
    h, w = img.shape
    w = int(factor_reduce * w)
    h = int(factor_reduce * h)
    pad = int(2.2 * w)

    def selection_callback(index):
        if not index:
            return hv.Div("")
        divtext = f'<table width={pad}  border=1 cellpadding=10 align=center valign=center>'
        for i, j in grouped(index, 2):
            value_s = '{:f}'.format(df_i[value][i])
            value_s2 = '{:f}'.format(df_i[value][j])
            divtext += '<tr>'
            divtext += f'<td align=center valign=center><br> {i} Value: {value_s}</br></td>' + "\n"
            divtext += f'<td align=center valign=center><br> {j} Value: {value_s2}</br></td>' + "\n"
            divtext += '</tr><tr>'
            divtext += f'<td align=center valign=center><img src={df_i.loc[i, "img_name_raw"]} width={w} height={h}></td>'
            divtext += f'<td align=center valign=center><img src={df_i.loc[j, "img_name_raw"]} width={w} height={h}></td>'
            divtext += '</tr>'
        if len(index) % 2 == 1:
            value_s = '{:f}'.format(df_i[value][index[-1]])
            divtext += '<tr>'
            divtext += f'<td align=center valign=center><br> {index[-1]} Value: {value_s}</br></td>' + "\n"
            divtext += f'<td align=center valign=center><br> </br></td>' + "\n"
            divtext += '</tr><tr>'
            divtext += f'<td align=center valign=center><img src={df_i.loc[index[-1], "img_name_raw"]} width={w} height={h}></td>'
            divtext += f'<td align=center valign=center></td>'
            divtext += '</tr>'
        divtext += '</table>'
        return hv.Div(str(divtext))

    div = hv.DynamicMap(selection_callback, streams=[sel])
    hv.streams.PlotReset(source=quality_scatter,
                         subscribers=[lambda reset: sel.event(index=[])])
    return hv.Layout(quality_scatter + div).cols(1), sel
コード例 #6
0
def main(data_sequence_folder: str, limit: int, start: int, out: str):
    root = Path(data_sequence_folder)
    img_folder_path = root.joinpath("imgs/")
    npz_filepath = root.joinpath("rendered.npz")

    data = np.load(npz_filepath)
    datasource = {key: data[key] for key in data.files}

    images_filepaths = list(img_folder_path.glob("*.png"))
    images_filepaths.sort()

    limit = min(start + limit, len(images_filepaths) - 1)

    with_slides = {}
    for idx, filepath in enumerate(tqdm(images_filepaths[start:limit])):
        dataframe = dict([(key, str(value[start + idx]))
                          for key, value in datasource.items()])

        image = hv.RGB.load_image(str(filepath))
        image.opts(title=f"Frame #{idx+1}")
        table = hv.Div(pformat(dataframe).replace("\n", "</br>"))
        fig = image + table
        with_slides[idx + 1] = fig

    data.close()
    hmap = hv.HoloMap(with_slides, "frame")
    hmap = hmap.collate()

    path_info = hv.Div(f"Sequence from {str(img_folder_path.parent)}")

    layout = hv.Layout([path_info] + [hmap])

    hv.save(layout, "holomap.html")
コード例 #7
0
ファイル: plot.py プロジェクト: jvivian/aristeia-calculator
def plot_exp_val(a, d):
    a_bar = hv.Bars(exp_val(a), label='A-Exp-Val')
    d_bar = hv.Bars(exp_val(d), label='D-Exp-Val')
    opts = dict(Bars=dict(plot=dict(
        xrotation=45, legend_position='left', width=750, tools=['hover']),
                          style=dict(cmap='Set1')))
    return hv.Layout([a_bar, d_bar]).opts(opts)
コード例 #8
0
def swatches(*args, group=None, not_group=None, only_aliased=False, cols=None, **kwargs):
    """Show swatches for given names or names in group"""
    args = args or all_original_names(group=group, not_group=not_group,
                                      only_aliased=only_aliased)
    if not cols:
        cols = 3 if len(args) >= 3 else 1

    backends = hv.Store.loaded_backends()
    if 'matplotlib' in backends:
        if 'aspect' not in kwargs:
            kwargs['aspect'] = 12 // cols
        if 'fig_size' not in kwargs:
            kwargs['fig_size'] = 500 // cols
    if 'bokeh' in backends:
        if 'height' not in kwargs:
            kwargs['height'] = 100
        if 'width' not in kwargs:
            kwargs['width'] = (9 * kwargs['height']) // cols

    images = [swatch(arg, **kwargs) if isinstance(arg, str) else
              swatch(*arg, **kwargs) for
              arg in args]

    plot = hv.Layout(images).opts(plot=dict(transpose=True)).cols(int(np.ceil(len(images)*1.0/cols)))

    if 'matplotlib' in backends:
        plot.opts(opts.Layout(backend='matplotlib', sublabel_format=None,
                              fig_size=kwargs.get('fig_size', 150)))
    return plot
コード例 #9
0
ファイル: plotting.py プロジェクト: pyviz/contrib_colormaps
def swatches(names=None, cols=None, **kwargs):
    """Show swatches for all names or given names"""
    if not names:
        names = sorted([name for name in palette.keys()])

    if not cols:
        cols = 2 if len(names) >= 2 else 1

    backends = hv.Store.loaded_backends()
    if 'matplotlib' in backends:
        if 'aspect' not in kwargs:
            kwargs['aspect'] = 12 // cols
        if 'fig_size' not in kwargs:
            kwargs['fig_size'] = 500 // cols
    if 'bokeh' in backends:
        if 'height' not in kwargs:
            kwargs['height'] = 100
        if 'width' not in kwargs:
            kwargs['width'] = (9 * kwargs['height']) // cols

    images = [swatch(name, **kwargs) for name in names]
    plot = hv.Layout(images).opts(plot=dict(transpose=True)).cols(int(np.ceil(len(images)*1.0/cols)))

    if 'matplotlib' in backends:
        plot.opts(opts.Layout(backend='matplotlib', sublabel_format=None,
                              fig_size=kwargs.get('fig_size', 150)))
    return plot
コード例 #10
0
def displayVideo(rowID=1):
    # Open database
    rowID = int(rowID)
    db = Database()
    db.open()
    # import detection table
    df = pd.read_sql('select * from audio_detections', con=db.connection)
    # Name of the table
    tablename = 'video_data'
    # time of the detection
    t1, t2 = getDetecTimes(rowID, df)
    # ID of file for that detection
    ID = getRecordID(db, tablename, t1)
    # Get info for that record
    info = getVideoRecord(db, tablename, ID)
    #faxis, taxis, S, df3 = getVideoFrame(info, t1,t2)
    filename = os.path.join(info['dirpath'], info['filename'])
    frameTime = t1 - info['startdate_unix']
    video = cv2.VideoCapture(filename)
    video.set(0,
              frameTime * 1000)  # set pointer to requested frame time (in ms)
    grabbed, frame = video.read()
    frame_GS = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    video.release()
    img = hv.Image(frame_GS)
    return hv.Layout([img.opts(cmap='gray', xaxis=None, yaxis=None)])
コード例 #11
0
    def write_histogram_for_annotation_count_by_label(self, df: pandas.DataFrame) -> None:
        """
        アノテーションラベルごとのアノテーション数をヒストグラムで出力する。
        """
        if len(df) == 0:
            logger.info("タスク一覧が0件のため出力しない")
            return

        renderer = hv.renderer("bokeh")

        output_file = f"{self.histogram_outdir}/ヒストグラム-ラベルごとのアノテーション数"
        logger.debug(f"{output_file}.html を出力します。")

        histograms = []
        label_columns = [e for e in df.columns if e.startswith("label_")]

        for column in label_columns:
            label_name = column[len("label_") :]
            histogram_name = HistogramName(
                column=column, x_axis_label=f"'{label_name}'のアノテーション数", title=f"{label_name}"
            )
            hist = self._create_histogram(df, histogram_name=histogram_name)

            histograms.append(hist)

        # 軸範囲が同期しないようにする
        layout = hv.Layout(histograms).options(shared_axes=False).cols(3)
        renderer.save(layout, output_file)
 def show_plot2(self):
     tn = self.table_selector2
     l = []
     grid_style = {
         "grid_line_color": "olive",
         "minor_grid_line_color": None
     }
     def_opt = dict(gridstyle=grid_style, show_grid=True)
     for i, y in enumerate(self.y_selec2):
         p = self.dfs[tn].hvplot(kind=self.plot_kind,
                                 x='msg_ts',
                                 y=y,
                                 rot=20,
                                 xformatter=XFORMATTER,
                                 responsive=True,
                                 min_height=150,
                                 min_width=300)
         if i == 0:
             p.opts(xaxis='top', **def_opt)
         else:
             p.opts(xaxis=None, **def_opt)
         l.append(p)
     o = hv.Layout(l).cols(1)
     return pn.pane.HoloViews(o,
                              sizing_mode="stretch_both",
                              min_width=600,
                              min_height=800)
コード例 #13
0
ファイル: plot.py プロジェクト: gokceneraslan/scPlot
def violin(adata: AnnData, keys: Union[str, List[str], Tuple[str]], by: str = None,
           width: int = 300, cmap: Union[str, List[str], Tuple[str]] = None, cols: int = None,
           use_raw: bool = None, **kwds) -> hv.core.element.Element:
    """
    Generate a violin plot.

    Args:
        adata: Annotated data matrix.
        keys: Keys for accessing variables of adata.var_names, field of adata.var, or field of adata.obs
        by: Group plot by specified observation.
        width: Plot width.
        cmap: Color map name (hv.plotting.list_cmaps()) or a list of hex colors. See http://holoviews.org/user_guide/Styling_Plots.html for more information.
        cols: Number of columns for laying out multiple plots
        use_raw: Use `raw` attribute of `adata` if present.
    """
    if cols is None:
        cols = 3
    adata_raw = __get_raw(adata, use_raw)
    if cmap is None:
        cmap = colorcet.b_glasbey_category10
    plots = []
    keywords = dict(padding=0.02, cmap=cmap, rot=90)
    keywords.update(kwds)
    keys = __to_list(keys)
    df = __get_df(adata, adata_raw, keys + ([] if by is None else [by]))
    __fix_color_by_data_type(df, by)

    for key in keys:
        p = df.hvplot.violin(key, width=width, by=by, violin_color=by, **keywords)
        plots.append(p)

    return hv.Layout(plots).cols(cols)
コード例 #14
0
def plot_stats_distribution(data: pd.DataFrame, plot_cols: list) -> hv.Layout:
    hist_plots = {}
    for col in plot_cols:
        hist_plots[col] = data[col].hvplot.hist(
            normed=True) * data[col].hvplot.kde()
    stats_distribution = hv.Layout(list(hist_plots.values())).cols(1)
    return stats_distribution
コード例 #15
0
def activity_plots(
    data: Union[pd.DataFrame, None, ],
    x_series: Optional[List[str]] = None,
    y_series: Optional[List[str]] = None,
) -> hv.Layout:
    """A layout of plots

    Args:
        data (pd.DataFrame): The Activity Data
        x_series (Optional[List[str]]): The series to show on the x-axis. Defaults to \
            DEFAULT_X_SERIES.
        y_series (Optional[List[str]]): The series to show on the y-axis. Defaults to \
            DEFAULT_Y_SERIES.

    Returns:
        hv.Layout: A layout of plots
    """
    if data is None or data.empty:
        return None
    if not x_series:
        x_series = DEFAULT_X_SERIES
    if not y_series:
        y_series = DEFAULT_Y_SERIES

    layout = hv.Layout()

    for xss in x_series:
        for yss in y_series:
            layout.items.append(activity_plot(
                data,
                xss,
                yss,
            ))
    return layout
コード例 #16
0
def dist_compare_grid(
        df1,
        df2,
        columns=None,
        max_bar_categories: int = 40,
        grid_size: Tuple[int, int] = (900, 900),
):
    if columns is None:
        columns = [c for c in df1.columns if c in df2.columns]
    else:
        for c in columns:
            if c not in df1.columns:
                raise ValueError("%s is not in df1.columns" % str(c))
            if c not in df2.columns:
                raise ValueError("%s is not in df2.columns" % str(c))
    grid_cols = int(np.ceil(np.sqrt(len(columns))))
    grid_rows = int(np.ceil(len(columns) / grid_cols))
    plots = [
        dist_compare_plot(df1[c], df2[c], max_bar_categories).opts(title=c)
        for c in columns
    ]
    grid = hv.Layout(plots).opts(shared_axes=False, normalize=False)
    grid.cols(grid_cols)
    # set sizes
    subplot_size = (int(grid_size[0] / grid_cols),
                    int(grid_size[1] / grid_rows))
    grid.opts(
        opts.Histogram(width=subplot_size[0], height=subplot_size[1]),
        opts.Bars(width=subplot_size[0], height=subplot_size[1]),
    )
    return grid
コード例 #17
0
def test_holoviews_link_within_pane(document, comm):
    from bokeh.models.tools import RangeTool
    from holoviews.plotting.links import RangeToolLink

    c1 = hv.Curve([])
    c2 = hv.Curve([])

    RangeToolLink(c1, c2)

    pane = Pane(Pane(hv.Layout([c1, c2]), backend='bokeh'))
    column = pane.get_root(document, comm=comm)

    assert len(column.children) == 1
    subcolumn = column.children[0]
    assert isinstance(subcolumn, BkColumn)
    assert len(subcolumn.children) == 2
    toolbar, subsubcolumn = subcolumn.children
    assert isinstance(subsubcolumn, GridBox)
    assert len(subsubcolumn.children) == 2
    (p1, _, _), (p2, _, _) = subsubcolumn.children

    assert isinstance(p1, Figure)
    assert isinstance(p2, Figure)

    range_tool = subsubcolumn.select_one({'type': RangeTool})
    assert isinstance(range_tool, RangeTool)
    assert range_tool.x_range == p2.x_range
コード例 #18
0
ファイル: measure.py プロジェクト: dgglab/QDotsPythonCode
 def marker(x, y):
     x_dim = {image.kdims[0].label: x}
     y_dim = {image.kdims[1].label: y}
     crosssection1 = image.sample(**x_dim).opts(norm=dict(framewise=True))
     crosssection1y = image.sample(**y_dim).opts(norm=dict(framewise=True))
     return hv.Layout(image * hv.VLine(x) * hv.HLine(y) + crosssection1 +
                      crosssection1y).cols(2).opts(norm=dict(axiwise=True))
コード例 #19
0
ファイル: test_holoviews.py プロジェクト: xyicheng/panel
def test_holoviews_link_within_pane(document, comm):
    from bokeh.models.tools import RangeTool
    from holoviews.plotting.links import RangeToolLink

    c1 = hv.Curve([])
    c2 = hv.Curve([])

    RangeToolLink(c1, c2)

    pane = Pane(hv.Layout([c1, c2]))
    column = pane._get_root(document, comm=comm)

    assert len(column.children) == 1
    subcolumn = column.children[0]
    assert isinstance(subcolumn, BkColumn)
    assert len(subcolumn.children) == 2
    toolbar, subsubcolumn = subcolumn.children
    assert isinstance(subsubcolumn, BkColumn)
    assert len(subsubcolumn.children) == 1
    row = subsubcolumn.children[0]
    assert isinstance(row, BkRow)
    assert len(row.children) == 2
    p1, p2 = row.children

    assert isinstance(p1, Figure)
    assert isinstance(p2, Figure)

    range_tool = row.select_one({'type': RangeTool})
    assert isinstance(range_tool, RangeTool)
    range_tool.x_range = p2.x_range
コード例 #20
0
def plotNselect_tSNE(df_feat, features, size=10, perplexity=80, ncomp=2):
    df_i = df_feat.dropna()
    df_i = df_i.reset_index(drop=True)

    Y = TSNE(perplexity=perplexity,
             n_components=ncomp).fit_transform(df_i[features])

    options = dict(legend_position='left',
                   width=1000,
                   height=600,
                   scaling_method='width',
                   scaling_factor=2,
                   size_index=2,
                   show_grid=True,
                   tools=['hover', 'box_select', 'lasso_select'],
                   line_color='k',
                   cmap='Accent',
                   size=size,
                   nonselection_color='lightskyblue')
    quality_scatter = hv.Scatter(Y).options(**options)
    sel = streams.Selection1D(source=quality_scatter)

    image_name = df_i.loc[0, "img_name_raw"]
    img = cv2.imread(image_name, 0)
    h, w = img.shape
    w = int(0.8 * w)
    h = int(0.8 * h)
    pad = int(2.2 * w)

    def selection_callback(index):
        if not index:
            return hv.Div("")
        divtext = f'<table width={pad}  border=1 cellpadding=10 align=center valign=center>'
        for i, j in grouped(index, 2):
            value_s = '{:f}'.format(df_i[value][i])
            value_s2 = '{:f}'.format(df_i[value][j])
            divtext += '<tr>'
            divtext += f'<td align=center valign=center><br> {i} Value: {value_s}</br></td>' + "\n"
            divtext += f'<td align=center valign=center><br> {j} Value: {value_s2}</br></td>' + "\n"
            divtext += '</tr><tr>'
            divtext += f'<td align=center valign=center><img src={df_i.loc[i, "img_name_raw"]} width={w} height={h}></td>'
            divtext += f'<td align=center valign=center><img src={df_i.loc[j, "img_name_raw"]} width={w} height={h}></td>'
            divtext += '</tr>'
        if len(index) % 2 == 1:
            value_s = '{:f}'.format(df_i[value][index[-1]])
            divtext += '<tr>'
            divtext += f'<td align=center valign=center><br> {index[-1]} Value: {value_s}</br></td>' + "\n"
            divtext += f'<td align=center valign=center><br> </br></td>' + "\n"
            divtext += '</tr><tr>'
            divtext += f'<td align=center valign=center><img src={df_i.loc[index[-1], "img_name_raw"]} width={w} height={h}></td>'
            divtext += f'<td align=center valign=center></td>'
            divtext += '</tr>'
        divtext += '</table>'
        return hv.Div(str(divtext))

    div = hv.DynamicMap(selection_callback, streams=[sel])
    hv.streams.PlotReset(source=quality_scatter,
                         subscribers=[lambda reset: sel.event(index=[])])
    return hv.Layout(quality_scatter + div).cols(1), sel
コード例 #21
0
ファイル: bokeh.py プロジェクト: synw/dataswim
 def layout_(self, chart_objs, cols=3):
     """
     Returns a Holoview Layout from chart objects
     """
     try:
         return hv.Layout(chart_objs).cols(cols)
     except Exception as e:
         self.err(e, self.layout_, "Can not build layout")
コード例 #22
0
def chart_for_metric(state:Dict, metric:str, viz_opts=opts()):
    bar_charts = []
    for g in state[M1][metric].keys():
        chart_data = [(state[model]["label"], state[model][metric][g]) for model in state.keys()]
        bar_chart = hv.Bars(chart_data, hv.Dimension(f'Models for {g}'), " ").opts(common_opts).opts(viz_opts)
        bar_charts.append(bar_chart)

    return hv.Layout(bar_charts).opts(shared_axes=False, title=metric).cols(1) # TODO: Title disturbs the layout
コード例 #23
0
    def combined(self, lon, lat):
        """Combines the temperature and precipitation holoviews objects.

        Parameters
        ----------
        lon : int or float
            The longitutde of the point.

        lat : int or float
            The latitude of the point.

        Returns
        -------
        out : holoviews Layout or Overlay
            Layout or overlay depends on how the object was initialized.

        Raises
        ------
        ValueError
            If either longitude or latitude or both are out of bounds.

        See Also
        --------
        out_of_bounds : Checks if longitude and latitude are out of bounds.

        """
        out_of_bounds(lon, lat, 'ClimvisHVPlot.combined')
        self.reinitialize(lon, lat, self._overlay)

        real_coords = real_lon_lat(lon, lat)
        real_lon = real_coords['lon']
        real_lat = real_coords['lat']

        # Creating the holoviews Curve and Bars objects for temperature and
        # precipitation respectively
        tmp = hv.Curve(annual_cycle_for_hv(lon, lat, variable='tmp'),
                       label='Real lon, lat: {} {}'.format(
                           real_lon, real_lat)).opts(color='red',
                                                     tools=['hover'])
        pre = hv.Bars(annual_cycle_for_hv(
            lon, lat, variable='pre'), ).opts(tools=['hover'])

        # Formatting xlables and ylabels
        if self._overlay:
            out = hv.Overlay([pre, tmp.relabel('')],
                             label='Real lon, lat: {} {}'.format(
                                 real_lon, real_lat))
            out.opts(xlabel='Month',
                     ylabel='Prec. and Temp. '
                     '(°C and mm mth^-1)')

        else:
            out = hv.Layout([
                tmp.opts(xlabel='Month', ylabel='Temperature (°C)'),
                pre.opts(xlabel='Month', ylabel='Precipitation (mm mth^-1)')
            ])

        return out
コード例 #24
0
def filter_layout(butler, tract=9813, description='mag_modelfit_CModel', style='psfMagHist', 
                    visit=None, kind='coadd', scale=0.66, columns=3):
    if tract==9813:
        filters = cosmos_filters
    else:
        filters = wide_filters
        
    return hv.Layout([get_plot(butler, tract, f, description, style, kind, scale=scale)
                               for f in filters]).cols(columns)
コード例 #25
0
ファイル: cometml_plt.py プロジェクト: matech96/cifar10
def grid_plot_experiments(comet_api: comet_ml.API, experiments: APIExperiments, p1_name: str, p2_name: str,
                          metrics: List[str] = ['train_acc', 'dev_acc', 'test_acc'], parameters: List[str] = [],
                          fig_size: int = 220) -> hv.core.layout.Layout:
    targets_data = _download_data(comet_api, experiments, p1_name, p2_name, metrics, parameters)

    layout = hv.Layout()
    for k, v in targets_data.items():
        layout += hv.HeatMap(v, kdims=[p1_name, p2_name], vdims=k).sort().opts(title=k, cmap='greens').redim.range(z=(0, None))
    return layout.opts(fig_size=fig_size, framewise=True)
コード例 #26
0
ファイル: catalog.py プロジェクト: yutaozhou/isochrones
 def hr(self):
     if self._hr is None:
         layout = []
         opts = dict(invert_yaxis=True, tools=["hover"])
         for b1, b2 in band_pairs(self.bands):
             kdims = ["{}-{}".format(b1, b2), "{}_mag".format(b1)]
             layout.append(hv.Points(self.ds, kdims=kdims, vdims=self.ds.kdims).options(**opts))
         self._hr = hv.Layout(layout)
     return self._hr
コード例 #27
0
ファイル: timeline.py プロジェクト: kujaku11/DoZen
    def time_series(self):
        empty_curve = hv.Curve([]).options(xaxis=None,
                                           yaxis=None,
                                           show_frame=True,
                                           height=200,
                                           width=800)
        print('Plotting time series')
        tx_path = self.filenames[0]
        rx_path = self.filenames[1]
        #rx_path = []
        #print(tx_path,rx_path)
        if tx_path and rx_path:
            #print('tx and rx!')
            # get plot time limits
            fi = z3dio.get_file_info(tx_path[0])
            [tstart, tend] = timeio.get_start_and_end_times_mountain(
                fi, include_final_second=True, astype='timestamp')
            #tstart=pd.Timestamp(tstart.replace(tzinfo=None))
            #tend=pd.Timestamp(tend.replace(tzinfo=None))

            d1 = viz.plot_ts(tx_path[0], time_range=[tstart, tend])
            d1rd = d1.redim(signal='TX Signal')
            #d2 = viz.plot_ts(rx_path[0])
            d2 = viz.plot_ts(rx_path[0], time_range=[tstart, tend])
            d2rd = d2.redim(signal='RX Signal')
            d1rd.opts(height=200, width=800)
            d2rd.opts(height=200, width=800)
            q = hv.Layout(d1rd + d2rd).cols(1)
            #print('I did it')
        elif rx_path:
            #print('only rx.')
            d2 = viz.plot_ts(rx_path[0])
            d2rd = d2.redim(signal='RX Signal')
            #print('redimensioned!')
            #print(type(d2rd))
            q = hv.Layout((empty_curve, d2rd.opts(height=200,
                                                  width=800))).cols(1)
            #print('I did it')
        else:
            #print('I got nuthin.')
            q = hv.Layout((empty_curve, empty_curve)).cols(1)
        #print('Shootin back a q atchu')
        #print(type(q))
        return q
コード例 #28
0
 def show_images(self, image_urls, labels=None, col_num=4):
   images = []
   for index, url in enumerate(image_urls):
     img = self.url_to_image(url)
     if img is None:
       continue
     img_ = hv.Image(img, label=labels[index]) if labels is not None else hv.Image(img)
     images.append(img_)
   obj = hv.Layout(images).cols(col_num).display('all')
   return obj
コード例 #29
0
 def __call__(self, dset, **params):
     self.p = param.ParamOverrides(self, params)
     return hv.Layout([
         scattersky(dset,
                    filter_stream=self.p.filter_stream,
                    xdim=self.p.xdim,
                    ydim=ydim,
                    height=self.p.height,
                    width=self.p.width) for ydim in self._get_ydims(dset)
     ]).cols(3).opts(plot={'merge_tools': False})
コード例 #30
0
 def plot_unit(uid, scl):
     trace = (hv.Curve(Y_r[uid, :], kdims='frame #').opts(framewise=True) *
              (hv.Curve(C[uid, :], kdims='frame #').opts(
                  color=denoised_color, framewise=True))).opts(
                      aspect=3, frame_height=200)
     A_scl = norm(Ad[:, :, uid], (scl, 1))
     im_hsv_scl = im_hsv.copy()
     im_hsv_scl[:, :, 2] = im_hsv[:, :, 2] * A_scl
     im_u = (hv.HSV(im_hsv_scl, kdims=['height',
                                       'width']).opts(aspect='equal',
                                                      frame_height=200))
     return hv.Layout([im_u] + [trace]).cols(1)  #im_u + trace