示例#1
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")
 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))
示例#3
0
 def portfolio_text(ds):
     arr = ds.array()
     ret, vol, sharpe = get_ret_vol_sr(arr[0, 2:])
     text = """
     The selected portfolio has a volatility of %.2f, a return of %.2f
     and Sharpe ratio of %.2f.
     """ % (vol, ret, sharpe)
     return hv.Div(text).opts(height=40)
 def display(
     self,
     defaultpath: Optional[str] = None,
     match: Optional[str] = None,
     callback: Optional[Callable[['_BasePathSelector'], Any]] = None
 ) -> pn.Column:
     "create the view"
     if defaultpath is not None:
         self.paths.value = defaultpath
     if match is not None:
         self.match.value = match
     if callback is not None:
         self._cback = callback
     self._col = pn.Column(pn.Row(self.paths, self.match), self.selector,
                           pn.Pane(hv.Div("")))
     self._on_update()
     return self._col
    def _on_newtracks(self, *_):
        "update the values"
        old = self._col.objects[:-1]
        obj = hv.Div("No tracks selected"
                     ) if not self.selector.value else self._new_display()
        if self._cback:
            self._cback(self)
        if obj is None:
            return

        try:
            self._col.pop(-1)
            self._col.append(pn.Pane(obj))
        except KeyError:  # panel bug
            for _ in range(5):
                try:
                    self._col.clear()
                    self._col.extend(old + [pn.Pane(obj)])
                    break
                except KeyError:  # panel bug
                    pass
    def _new_display(self):
        track = self.track
        beads = list(track.beads.keys())
        if not beads:
            return pn.Pane("No beads in this track")

        sel = pnw.Select(
            name="Plot",
            value="cleancycles",
            options=["cleanbeads", "cleancycles", "cycles", "peaks"])
        lst = pnw.DiscreteSlider(name="Beads", value=beads[0], options=beads)
        pane = pn.Pane(hv.Div(""))

        def _show(_):
            dmap = getattr(track, sel.value).display.display()
            pane.object = dmap[lst.value]

        lst.param.watch(_show, "value")
        sel.param.watch(_show, "value")
        col = pn.Column(pn.Row(lst, sel), pane)
        _show(None)
        return col
示例#7
0
"""

import math
import time

import holoviews as hv
import hvplot.pandas  # pylint: disable=unused-import
import pandas as pd
import panel as pn
import param

from application.config import site

COLOR = "#E1477E"
EMPTY_DATAFRAME = pd.DataFrame(columns=["x", "y"])
EMPTY_PLOT = hv.Div("Click UPDATE to load!")
SPINNER_URL = (
    "https://github.com/MarcSkovMadsen/awesome-panel/blob/master/"
    "application/pages/gallery/dataexplorer_loading/spinner.gif?raw=true")
SPINNER_HTML = f"<img application='{SPINNER_URL}' style='width:100%'"
APPLICATION = site.create_application(
    url="data-explorer-loading",
    name="Data Explorer Loading",
    author="Marc Skov Madsen",
    introduction=
    "Shows how to provide progress information to a user during computation",
    description=__doc__,
    thumbnail_url="dataexplorer_loading.png",
    documentation_url="",
    code_url="dataexplorer_loading/dataexplorer_loading.py",
    gif_url="",
示例#8
0
imgs_pv = ds_sel['p_values'].hvplot.contour(**hvc_opts)
temp = xr.apply_ufunc(combine_pvalues_ufunc, ds_sel['p_values'], input_core_dims=[['ens']], \
               output_core_dims = [[]], vectorize = True, dask = 'allowed')

hvc_opts = dict(width=300, dynamic=True, \
                                         x = 'x', y = 'y',  colorbar = False, \
                                      logy = True, cmap = ['black', 'gray'], \
                                                levels=[0.01,0.05])
imgs_pv2 = temp.hvplot.contour(**hvc_opts)
# -

# ## Layout
# By combining every panel in a layout, we get clear interactive dashboard

hl = hv.HLine(0).opts(color='gray', line_dash='dotted')
dmap = dmap.opts(xticks=[(i, ens_name) for i, ens_name in enumerate(ens_ls)])
first_panel = im * imgs_pv * polys
second_panel = (dmap * hl * hlines).relabel('ROI drawer')
hv_div = hv.Div(
    f"""<h1>{invar} response to {sel_reg} for {month_names[sel_month-1]}</h1>"""
)
second_row = (
    (im2 * imgs_pv2).relabel('Model average (p-values combined using Z-score)')
    + hv_div)
layout = ((first_panel + second_panel).opts(
    opts.Curve(width=400, framewise=True),
    opts.Polygons(fill_alpha=0.2, line_color='green', fill_color='green'),
    opts.VLine(color='black')) + second_row).cols(2)

layout
示例#9
0
def plot():
    #################################################################333333
    # Final plot.
    # High Significant

    from shapely.geometry import Point, Polygon
    import pandas as pd

    import numpy as np
    import geoviews as gv

    import bokeh

    import panel as pn

    import holoviews as hv
    from holoviews import opts
    from holoviews.operation.datashader import datashade, rasterize
    hv.extension("bokeh")

    import math

    from bokeh.models import HoverTool

    from scipy.interpolate import griddata
    from scipy.io import loadmat

    import datetime

    from dateutil.parser import parse

    from datetime import timedelta
    import time
    strtt = time.time()

    datamat = loadmat('IOEC_ECM_noDA_20190703_masked.mat')
    # datamat = loadmat('IOEC_ECM_DA_20191121_masked.mat')

    Xp = datamat['Xp']
    Yp = datamat['Yp']

    # Xp=np.where(((Xp>= 85) & (Xp<=88) & (Yp>=19) & (Yp<=22)),Xp,88)
    # Yp=np.where(((Xp>= 85) & (Xp<=88) & (Yp>=19) & (Yp<=22)),Yp,22)

    strt = datetime.datetime(2019, 7, 4, 0, 0)
    end = datetime.datetime(2019, 1, 13, 0, 0)
    from bokeh.models.callbacks import CustomJS

    def perdelta(strt, end, delta):
        curr = strt
        while curr < end:
            yield curr
            curr += delta

    # Read element file

    tri_new = pd.read_csv('fort.ele',
                          delim_whitespace=True,
                          names=('A', 'B', 'C', 'D'),
                          usecols=[1, 2, 3],
                          skiprows=1,
                          dtype={'D': np.int})

    dateList = []

    def plotsecond(datetime, regions='Whole_East_Coast'):
        dat = datetime
        # datetostr=result.strftime("%Y%b%d%H")
        dt = parse(str(dat))
        yr = dt.year
        mn = dt.month
        d = dt.day
        hr = dt.hour
        mi = dt.minute

        if hr < 10:

            hr = '0' + str(hr)
        else:
            d = str(d)
            hr = str(hr)
        if int(d) < 10:
            d = '0' + str(d)
        else:
            d = str(d)
        #     varname = 'Hsig_' + str(yr) + '0' + str(mn) + str(d) + '_' + hr + '0000'

        Xp = datamat['Xp']
        Yp = datamat['Yp']
        x = Xp.flatten()
        y = Yp.flatten()

        Longitude = x
        Latitude = y

        pkname = 'PkDir_' + str(yr) + '0' + str(mn) + str(
            d) + '_' + hr + '0000'

        pkvalue = datamat[pkname]

        if regions is 'Odisha':
            pkvalue = np.where(
                ((Xp >= 85) & (Xp <= 88) & (Yp >= 19) & (Yp <= 22)), pkvalue,
                np.nan).flatten()
        elif regions is 'Andra_Pradesh':
            pkvalue = np.where(
                ((Xp >= 79) & (Xp <= 85) & (Yp >= 13) & (Yp <= 19)), pkvalue,
                np.nan).flatten()
        elif regions is 'Tamil_Nadu':
            pkvalue = np.where(
                ((Xp >= 77) & (Xp <= 83) & (Yp >= 7) & (Yp <= 14)), pkvalue,
                np.nan).flatten()
        elif regions is 'Whole_East_Coast':
            pkvalue = pkvalue.flatten()
        else:
            #         data = get_data4region(data,**odisha)
            pkvalue = pkvalue.flatten()

        pkvalue = pkvalue.flatten()
        d = pkvalue * (math.pi / 180)

        # target grid to interpolate to
        xt = np.arange(76.937, 92.008, 0.1)
        yt = np.arange(1.482, 22.461, 0.1)
        xi, yi = np.meshgrid(xt, yt)
        di = griddata((Longitude, Latitude), d, (xi, yi))

        dfcoast = pd.read_csv('ECpolygonTwoDegreeOffsetBorder.txt',
                              delim_whitespace=True,
                              names=('X', 'Y'))
        dfcoast['geometry'] = dfcoast.apply(lambda row: Point(row.X, row.Y),
                                            axis=1)
        poly = Polygon([(p.x, p.y) for p in dfcoast.geometry])

        arr = np.zeros((len(yt), len(xt)))
        for i in range(len(xt)):
            for j in range(len(yt)):
                point = Point(xt[i], yt[j])
                arr[j, i] = poly.contains(point)

        mask = (xi > 79.7817) & (xi < 81.2718) & (yi > 7.6951) & (yi < 9.7406)
        di[mask] = np.nan
        di[arr == False] = np.nan
        U = np.cos(di)
        V = np.sin(di)

        mag = np.sqrt(U**2 + V**2)
        angle = (np.pi / 2.) - np.arctan2(U / mag, V / mag)

        vec = gv.VectorField(
            (xi[::5, ::5], yi[::5, ::5], angle[::5, ::5], mag[::5, ::5]))
        return vec

    def plotthis(datetime, regions='Whole_East_Coast'):
        dat = datetime
        # datetostr=result.strftime("%Y%b%d%H")
        dt = parse(str(dat))
        yr = dt.year
        mn = dt.month
        d = dt.day
        hr = dt.hour
        mi = dt.minute

        if hr < 10:

            hr = '0' + str(hr)
        else:
            d = str(d)
            hr = str(hr)
        if int(d) < 10:
            d = '0' + str(d)
        else:
            d = str(d)
        varname = 'Hsig_' + str(yr) + '0' + str(mn) + str(
            d) + '_' + hr + '0000'

        x = Xp.flatten()
        y = Yp.flatten()
        z = datamat[varname]

        if regions is 'Odisha':
            z = np.where(((Xp >= 85) & (Xp <= 88) & (Yp >= 19) & (Yp <= 22)),
                         z, np.nan).flatten()
        elif regions is 'Andra_Pradesh':
            z = np.where(((Xp >= 79) & (Xp <= 85) & (Yp >= 13) & (Yp <= 19)),
                         z, np.nan).flatten()
        elif regions is 'Tamil_Nadu':
            z = np.where(((Xp >= 77) & (Xp <= 83) & (Yp >= 7) & (Yp <= 14)), z,
                         np.nan).flatten()
        elif regions is 'Whole_East_Coast':
            z = z.flatten()

        else:
            #         data = get_data4region(data,**odisha)
            z = z.flatten()

        # z = z.flatten()
        Longitude = x
        Latitude = y
        High_Significant = z

        pts = np.stack((Longitude, Latitude, High_Significant)).T
        verts = pd.DataFrame(
            np.stack((Longitude, Latitude, High_Significant)).T,
            columns=['Longitude', 'Latitude', ' High_Significant'])

        # openStreet Background.
        tri_sub = tri_new.apply(lambda x: x - 1)
        ggpoints = gv.Points(verts, vdims=[' High_Significant'])
        ggsubraster = rasterize(gv.TriMesh((tri_sub, gv.Points(verts))))

        tri = gv.TriMesh((tri_sub, gv.Points(verts)))

        return tri

    allplot = {
        (k.strftime("%Y-%m-%d %H:%M:%S"), r): plotthis(k, r)
        for k in perdelta(strt, strt + timedelta(days=2), timedelta(hours=18))
        for r in ['Odisha', 'Andra_Pradesh', 'Whole_East_Coast', 'Tamil_Nadu']
    }
    allplot2 = {
        (k.strftime("%Y-%m-%d %H:%M:%S"), r): plotsecond(k, r)
        for k in perdelta(strt, strt + timedelta(days=2), timedelta(hours=18))
        for r in ['Odisha', 'Andra_Pradesh', 'Whole_East_Coast', 'Tamil_Nadu']
    }

    df_div = hv.Div("""
        <figure>
        <img src="https://i.ibb.co/S0t5GWb/imglogo.png" height='80' width='90' vspace='-10'>
        """)

    df_div1 = hv.Div("""
        &nbsp<center><b><p style="color:#B22222";font-size:80px;font-family:Times new roman><h1 style=font-size:20px;margin-left:2.5em;margin-top:-1em;color:#B22222>Indian National Center for Ocean Information Services<br />
        (INCOIS)</h1></p></b></center>

        """)

    colorbar_opts = {
        'major_label_overrides': {
            0: '0',
            0.5: '0.5',
            1: '1',
            1.5: '1.5',
            2: '2',
            2.5: '2.5',
            3: '3',
            3.5: '>3.5',
            3.8: '>4 ',
            3.9: '>3.9',
        },
        'major_label_text_align': 'left',
        'major_label_text_font_style': 'bold',
    }
    levels = [
        0,
        0.2,
        0.4,
        0.6,
        0.8,
        1,
        1.2,
        1.4,
        1.6,
        1.8,
        2,
        2.2,
        2.5,
        3,
    ]

    def disable_logo(plot, element):
        plot.state.toolbar.logo = None

    hv.plotting.bokeh.ElementPlot.finalize_hooks.append(disable_logo)

    # logo1 = hv.RGB.load_image("imglogo.png")

    logo1 = hv.RGB.load_image("https://i.ibb.co/7VXRPCS/logo1.png")

    def absolute_position(plot, element):
        glyph = plot.handles['glyph']
        x_range, y_range = plot.handles['x_range'], plot.handles['y_range']
        glyph.dh_units = 'screen'
        glyph.dw_units = 'screen'
        glyph.dh = 60
        glyph.dw = 90
        glyph.x = x_range.start
        glyph.y = y_range.start
        xcode = CustomJS(code="glyph.x = cb_obj.start", args={'glyph': glyph})
        plot.handles['x_range'].js_on_change('start', xcode)
        ycode = CustomJS(code="glyph.y = cb_obj.start", args={'glyph': glyph})
        plot.handles['y_range'].js_on_change('start', ycode)

    def plot_limits(plot, element):
        plot.handles['x_range'].min_interval = 100
        plot.handles['x_range'].max_interval = 55000000
        # 3000000
        plot.handles['y_range'].min_interval = 500
        plot.handles['y_range'].max_interval = 900000

    opts = dict(
        width=700,
        height=700,
        tools=['hover', 'save', 'wheel_zoom'],
        active_tools=['wheel_zoom'],
        hooks=[plot_limits, disable_logo],
        colorbar=True,
        color_levels=15,
        colorbar_opts=colorbar_opts,
        cmap=[
            '#000080',
            '#0000cd',
            '#0008ff',
            '#004cff',
            '#0090ff',
            '#00d4ff',
            '#29ffce',
            '#60ff97',
            '#97ff60',
            '#ceff29',
            '#ffe600',
            '#ffa700',
            # '#ff6800',
            '#ff2900',
            '#cd0000',
            '#800000',
        ],
        clim=(0, 3.76),
        title="\tSignificant Wave Height (m) and Direction (°) ",
        fontsize={
            'title': 18,
            'xlabel': 15,
            'ylabel': 15,
            'ticks': 12
        })

    tiles = gv.tile_sources.Wikipedia
    hmap1 = hv.HoloMap(allplot,
                       kdims=['Select Date and Time :', 'Select Indian State'])
    hmap2 = hv.HoloMap(allplot2,
                       kdims=['Select Date and Time :', 'Select Indian State'])

    dd = df_div.opts(width=70, height=70)
    dd1 = df_div1.opts(width=600, height=90)

    finalplot = pn.Column(
        pn.Row(dd, dd1),
        tiles * rasterize(hmap1).options(**opts) * hmap2 *
        logo1.opts(hooks=[absolute_position], apply_ranges=False)).servable()
    # print("--- %s seconds ---" % (time.time() - strtt))
    from bokeh.embed import components
    from bokeh.resources import CDN
    from bokeh.io import curdoc
    doc = curdoc()
    script, div = components(finalplot.get_root(doc))
    cdn_js0 = CDN.js_files[0]
    cdn_js = CDN.js_files[1]
    cdn_css = CDN.css_files
    print("cdn_js:", cdn_js)
    print("cdn_css", cdn_css)

    return render_template("plot.html",
                           script=script,
                           div=div,
                           cdn_css=cdn_css,
                           cdn_js=cdn_js,
                           cdn_js0=cdn_js0)
示例#10
0
    verts = pd.DataFrame(np.stack((x, y, z)).T, columns=['X', 'Y', 'Z'])

    # #openStreet Background.
    # tri_sub = cf.apply(lambda x: x - 1)
    # tri_sub=tri_sub[:10]

    tri = gv.TriMesh((triangles, gv.Points(verts)))

    return tri


allplot = {(k, r): plotthis(k, r) for k, r in zip(z, ['O', 'A', 'T'])}

df_div = hv.Div("""
    <figure>
    <img src="https://i.ibb.co/S0t5GWb/imglogo.png" height='80' width='90' vspace='-10'>

    """)
colorbar_opts = {
    'major_label_overrides': {
        0: '0',
        1: '1',
        2: '2',
        3: '3',
        4: '4',
        5: '5',
        6: '6',
        7: '7',
        8: '8',
        9: '9',
        10: '10',
示例#11
0
def plot():
    #################################################################333333
    # Final plot.
    # High Significant

    from shapely.geometry import Point, Polygon
    import pandas as pd

    import numpy as np
    import geoviews as gv

    import bokeh

    import panel as pn

    import holoviews as hv
    from holoviews import opts
    from holoviews.operation.datashader import datashade, rasterize
    hv.extension("bokeh")

    import math

    from bokeh.models import HoverTool

    from scipy.interpolate import griddata
    from scipy.io import loadmat

    import datetime

    from dateutil.parser import parse

    from datetime import timedelta
    import time
    strtt = time.time()

    datamat = loadmat('IOEC_ECM_noDA_20190703_masked.mat')
    # datamat = loadmat('IOEC_ECM_DA_20191121_masked.mat')

    Xp = datamat['Xp']
    Yp = datamat['Yp']

    # Xp=np.where(((Xp>= 85) & (Xp<=88) & (Yp>=19) & (Yp<=22)),Xp,88)
    # Yp=np.where(((Xp>= 85) & (Xp<=88) & (Yp>=19) & (Yp<=22)),Yp,22)

    strt = datetime.datetime(2019, 7, 4, 0, 0)
    end = datetime.datetime(2019, 1, 13, 0, 0)
    from bokeh.models.callbacks import CustomJS

    def perdelta(strt, end, delta):
        curr = strt
        while curr < end:
            yield curr
            curr += delta

    # Read element file

    tri_new = pd.read_csv('fort.ele',
                          delim_whitespace=True,
                          names=('A', 'B', 'C', 'D'),
                          usecols=[1, 2, 3],
                          skiprows=1,
                          dtype={'D': np.int})

    dateList = []

    def plotthis(datetime, regions='Whole_East_Coast'):
        dat = datetime
        # datetostr=result.strftime("%Y%b%d%H")
        dt = parse(str(dat))
        yr = dt.year
        mn = dt.month
        d = dt.day
        hr = dt.hour
        mi = dt.minute

        if hr < 10:

            hr = '0' + str(hr)
        else:
            d = str(d)
            hr = str(hr)
        if int(d) < 10:
            d = '0' + str(d)
        else:
            d = str(d)
        varname = 'Steepn_' + str(yr) + '0' + str(mn) + str(
            d) + '_' + hr + '0000'

        x = Xp.flatten()
        y = Yp.flatten()
        z = datamat[varname]

        if regions is 'Odisha':
            z = np.where(((Xp >= 85) & (Xp <= 88) & (Yp >= 19) & (Yp <= 22)),
                         z, np.nan).flatten()
        elif regions is 'Andra_Pradesh':
            z = np.where(((Xp >= 79) & (Xp <= 85) & (Yp >= 13) & (Yp <= 19)),
                         z, np.nan).flatten()
        elif regions is 'Tamil_Nadu':
            z = np.where(((Xp >= 77) & (Xp <= 83) & (Yp >= 7) & (Yp <= 14)), z,
                         np.nan).flatten()
        elif regions is 'Whole_East_Coast':
            z = z.flatten()

        else:
            #         data = get_data4region(data,**odisha)
            z = z.flatten()

        # z = z.flatten()
        Longitude = x
        Latitude = y
        HS = z

        pts = np.stack((Longitude, Latitude, HS)).T
        verts = pd.DataFrame(np.stack((Longitude, Latitude, HS)).T,
                             columns=['Longitude', 'Latitude', 'HS'])

        # openStreet Background.
        tri_sub = tri_new.apply(lambda x: x - 1)
        ggpoints = gv.Points(verts, vdims=['HS'])
        ggsubraster = rasterize(gv.TriMesh((tri_sub, gv.Points(verts))))

        tri = gv.TriMesh((tri_sub, gv.Points(verts)))

        return tri

    allplot = {
        (k.strftime("%Y-%m-%d %H:%M:%S"), r): plotthis(k, r)
        for k in perdelta(strt, strt + timedelta(days=9), timedelta(hours=3))
        for r in ['Odisha', 'Andra_Pradesh', 'Whole_East_Coast', 'Tamil_Nadu']
    }
    # allplot2={(k.strftime("%Y-%m-%d %H:%M:%S"),r):plotsecond(k,r)for k in perdelta(strt, strt + timedelta(days=1), timedelta(hours=18)) for r in ['Odisha','Andra_Pradesh','Whole_East_Coast','Tamil_Nadu']}

    df_div = hv.Div("""
        <figure>
        <img src="https://i.ibb.co/S0t5GWb/imglogo.png" height='80' width='90' vspace='-10'>
        """)

    df_div1 = hv.Div("""
        &nbsp<center><b><p style="color:#B22222";font-size:80px;font-family:Times new roman><h1 style=font-size:20px;margin-left:2.5em;margin-top:-1em;color:#B22222>Indian National Center for Ocean Information Services<br />
        (INCOIS)</h1></p></b></center>

        """)
    df_div2 = hv.Div("""
            <html>
            <head>
            <style>
            input[type=button], input[type=submit], input[type=reset] {
              background-color: #C6E2FF;
              color: DARKVIOLET;
              padding: 10px 22px;
              text-decoration: none;
              margin: 4px 2px;
              cursor: pointer;
              font-weight: bold;
              font-size: 15px;
              border: 2px solid light slateblue
            }
            </style>
            </head>
            <body>

            <input type="button" value=" PRINT " onClick="window.print()">


            </body>
            </html>

            """)

    colorbar_opts = {
        'major_label_overrides': {
            0.00: '0.00',
            0.02: '0.02',
            0.04: '0.04',
            0.06: '0.06',
            0.08: '0.08',
            0.10: '0.10',
            0.12: '0.12',
            0.14: '> 0.14',
            0.15: '0.15',
            0.16: ' ',
            0.17: '>0.17',
        },
        'major_label_text_align': 'left',
        'major_label_text_font_style': 'bold',
    }
    levels = [0.00, 0.02, 0.04, 0.06, 0.08, 0.10, 0.12, 0.14, 0.15, 0.16, 0.17]

    def disable_logo(plot, element):
        plot.state.toolbar.logo = None

    hv.plotting.bokeh.ElementPlot.finalize_hooks.append(disable_logo)

    def plot_limits(plot, element):
        plot.handles['x_range'].min_interval = 100
        plot.handles['x_range'].max_interval = 55000000
        # 3000000
        plot.handles['y_range'].min_interval = 500
        plot.handles['y_range'].max_interval = 900000

    opts = dict(
        width=700,
        height=700,
        logz=False,
        logx=False,
        logy=False,
        responsive=True,
        active_tools=['wheel_zoom'],
        tools=['save', 'wheel_zoom', 'hover'],
        hooks=[plot_limits, disable_logo],
        colorbar=True,
        color_levels=15,
        colorbar_opts=colorbar_opts,
        cmap=[
            '#000080',
            '#0000cd',
            '#0008ff',
            '#004cff',
            '#0090ff',
            '#00d4ff',
            '#29ffce',
            '#60ff97',
            '#97ff60',
            '#ceff29',
            '#ffe600',
            '#ffa700',
            # '#ff6800',
            '#ff2900',
            '#cd0000',
            '#800000',
        ],
        clim=(0.00, 0.15),
        title="\t\t\t\t\t\t\t\t Wave Steepness  . ",
        fontsize={
            'title': 18,
            'xlabel': 15,
            'ylabel': 15,
            'ticks': 12
        })

    tiles = gv.tile_sources.Wikipedia
    tiles = gv.tile_sources.Wikipedia
    hmap1 = hv.HoloMap(
        allplot, kdims=['Select Date and Time :', 'Select Indian States'])
    # hmap2 = hv.HoloMap(allplot2, kdims=['Date and Time :','region'])
    logo1 = hv.RGB.load_image("https://i.ibb.co/7VXRPCS/logo1.png")

    def absolute_position(plot, element):
        glyph = plot.handles['glyph']
        x_range, y_range = plot.handles['x_range'], plot.handles['y_range']
        glyph.dh_units = 'screen'
        glyph.dw_units = 'screen'
        glyph.dh = 60
        glyph.dw = 90
        #     x_range.start=+85
        #     y_range.start=+20
        glyph.x = x_range.start
        glyph.y = y_range.start
        xcode = CustomJS(code="glyph.x = cb_obj.start", args={'glyph': glyph})
        plot.handles['x_range'].js_on_change('start', xcode)
        ycode = CustomJS(code="glyph.y = cb_obj.start", args={'glyph': glyph})
        plot.handles['y_range'].js_on_change('start', ycode)

    # finalplot=tiles*rasterize(hmap1.redim.range(Latitude=(13, 19), Longitude=(79, 85))).options(**opts)*hmap2

    dd = df_div.opts(width=90, height=80)
    dd1 = df_div1.opts(width=600, height=90)
    dd2 = df_div2.opts(width=100, height=10)

    finalplot = pn.Column(
        pn.Row(dd, dd1),
        tiles * rasterize(hmap1).options(**opts) *
        logo1.opts(hooks=[absolute_position], apply_ranges=False))
    # print("--- %s seconds ---" % (time.time() - strtt))
    from bokeh.embed import components
    from bokeh.resources import CDN
    from bokeh.io import curdoc
    doc = curdoc()
    script, div = components(finalplot.get_root(doc))
    cdn_js0 = CDN.js_files[0]
    cdn_js = CDN.js_files[1]
    cdn_css = CDN.css_files
    print("cdn_js:", cdn_js)
    print("cdn_css", cdn_css)

    return render_template("plot.html",
                           script=script,
                           div=div,
                           cdn_css=cdn_css,
                           cdn_js=cdn_js,
                           cdn_js0=cdn_js0)
示例#12
0
文件: timeseries.py 项目: desihub/qlf
        else:
            tooltips = [
                ('Exposure', '@exposure_id'),
                ('camera', '@camera'),
                ('Date', '@datef'),
                (yaxis, '@{}'.format(yaxis)),
            ]
            hover = HoverTool(tooltips=tooltips)
            points = hv.Points(df, ['mjd', yaxis],
                               ['exposure_id', 'camera', 'datef', 'dateobs'],
                               label=yaxis).opts(tools=[hover], size=3)
            plot = plot * points
    layout = plot.redim.label(x='mjd',
                              y=yaxis).opts(sizing_mode='scale_width',
                                            height=150,
                                            padding=0.1,
                                            fontsize='1.2vw',
                                            toolbar='above',
                                            active_tools=["box_zoom"],
                                            title='Camera: {}'.format(camera))
    doc = renderer.server_doc(layout)
    doc.title = 'Time Series'
except Exception as e:
    renderer = hv.renderer('bokeh')
    print('error', e)
    doc = renderer.server_doc(
        hv.Div("""
        <p style="font-size: 2.2vw"> Couldn't Load Time Series </p>
    """))
    doc.title = 'Time Series Error'
示例#13
0
def plot():
    import numpy as np
    import pandas as pd
    import geoviews as gv
    import holoviews as hv
    import panel as pn
    from holoviews.operation.datashader import rasterize
    hv.extension("bokeh")
    from bokeh.models.callbacks import CustomJS
    # Some points defining a triangulation over (roughly) Britain.
    xy = np.asarray([
        [-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], [-0.054, 0.890],
        [-0.045, 0.897], [-0.057, 0.895], [-0.073, 0.900], [-0.087, 0.898],
        [-0.090, 0.904], [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919],
        [-0.073, 0.928], [-0.052, 0.930], [-0.048, 0.942], [-0.062, 0.949],
        [-0.054, 0.958], [-0.069, 0.954], [-0.087, 0.952], [-0.087, 0.959],
        [-0.080, 0.966], [-0.085, 0.973], [-0.087, 0.965], [-0.097, 0.965],
        [-0.097, 0.975], [-0.092, 0.984], [-0.101, 0.980], [-0.108, 0.980],
        [-0.104, 0.987], [-0.102, 0.993], [-0.115, 1.001], [-0.099, 0.996],
        [-0.101, 1.007], [-0.090, 1.010], [-0.087, 1.021], [-0.069, 1.021],
        [-0.052, 1.022], [-0.052, 1.017], [-0.069, 1.010], [-0.064, 1.005],
        [-0.048, 1.005], [-0.031, 1.005], [-0.031, 0.996], [-0.040, 0.987],
        [-0.045, 0.980], [-0.052, 0.975], [-0.040, 0.973], [-0.026, 0.968],
        [-0.020, 0.954], [-0.006, 0.947], [0.003, 0.935], [0.006, 0.926],
        [0.005, 0.921], [0.022, 0.923], [0.033, 0.912], [0.029, 0.905],
        [0.017, 0.900], [0.012, 0.895], [0.027, 0.893], [0.019, 0.886],
        [0.001, 0.883], [-0.012, 0.884], [-0.029, 0.883], [-0.038, 0.879],
        [-0.057, 0.881], [-0.062, 0.876], [-0.078, 0.876], [-0.087, 0.872],
        [-0.030, 0.907], [-0.007, 0.905], [-0.057, 0.916], [-0.025, 0.933],
        [-0.077, 0.990], [-0.059, 0.993]])
    # Make lats + lons
    x = abs(xy[:, 0] * 180 / 3.14159)
    y = xy[:, 1] * 180 / 3.14159

    # A selected triangulation of the points.
    triangles = np.asarray([
        [67, 66, 1], [65, 2, 66], [1, 66, 2], [64, 2, 65], [63, 3, 64],
        [60, 59, 57], [2, 64, 3], [3, 63, 4], [0, 67, 1], [62, 4, 63],
        [57, 59, 56], [59, 58, 56], [61, 60, 69], [57, 69, 60], [4, 62, 68],
        [6, 5, 9], [61, 68, 62], [69, 68, 61], [9, 5, 70], [6, 8, 7],
        [4, 70, 5], [8, 6, 9], [56, 69, 57], [69, 56, 52], [70, 10, 9],
        [54, 53, 55], [56, 55, 53], [68, 70, 4], [52, 56, 53], [11, 10, 12],
        [69, 71, 68], [68, 13, 70], [10, 70, 13], [51, 50, 52], [13, 68, 71],
        [52, 71, 69], [12, 10, 13], [71, 52, 50], [71, 14, 13], [50, 49, 71],
        [49, 48, 71], [14, 16, 15], [14, 71, 48], [17, 19, 18], [17, 20, 19],
        [48, 16, 14], [48, 47, 16], [47, 46, 16], [16, 46, 45], [23, 22, 24],
        [21, 24, 22], [17, 16, 45], [20, 17, 45], [21, 25, 24], [27, 26, 28],
        [20, 72, 21], [25, 21, 72], [45, 72, 20], [25, 28, 26], [44, 73, 45],
        [72, 45, 73], [28, 25, 29], [29, 25, 31], [43, 73, 44], [73, 43, 40],
        [72, 73, 39], [72, 31, 25], [42, 40, 43], [31, 30, 29], [39, 73, 40],
        [42, 41, 40], [72, 33, 31], [32, 31, 33], [39, 38, 72], [33, 72, 38],
        [33, 38, 34], [37, 35, 38], [34, 38, 35], [35, 37, 36]])
    z = np.random.uniform(0, 16, 74)

    # print("x",x)
    # print("y",y)
    # print("z",z)

    def plotthis(z, regions='w'):

        if regions is 'O':
            z = np.where(((x >= 0) & (x <= 4) & (y >= 50) & (y <= 56)), z, np.nan).flatten()

        elif regions is 'A':
            z = np.where(((x >= 3) & (x <= 4) & (y >= 54) & (y <= 57)), z, np.nan).flatten()

        elif regions is 'T':
            z = np.where(((x >= -2) & (x <= 3) & (y >= 50) & (y <= 57)), z, np.nan).flatten()

        #         else:
        #         #         data = get_data4region(data,**odisha)
        #             z=z.flatten()
        print("lx:", len(x), "ly:", len(y), "lz:", len(z))
        print("z", z)
        verts = pd.DataFrame(np.stack((x, y, z)).T, columns=['X', 'Y', 'Z'])

        # #openStreet Background.
        # tri_sub = cf.apply(lambda x: x - 1)
        # tri_sub=tri_sub[:10]

        tri = gv.TriMesh((triangles, gv.Points(verts)))

        return tri

    allplot = {(k, r): plotthis(k, r) for k, r in zip(z, ['O', 'A', 'T'])}

    df_div = hv.Div("""
        <figure>
        <img src="https://i.ibb.co/5h74S9n/python.png" height='80' width='90' vspace='-10'>

        """)
    colorbar_opts = {
        'major_label_overrides': {
            0: '0',

            1: '1',

            2: '2',

            3: '3',

            4: '4',

            5: '5',
            6: '6',

            7: '7',
            8: '8',
            9: '9',
            10: '10',
            11: '11',
            12: '12',
            13: '13',
            14: '>14',
            15: '15'

        },
        'major_label_text_align': 'left', 'major_label_text_font_style': 'bold', }

    logo1 = hv.RGB.load_image("https://i.ibb.co/5h74S9n/python.png")

    def absolute_position(plot, element):
        glyph = plot.handles['glyph']
        x_range, y_range = plot.handles['x_range'], plot.handles['y_range']
        glyph.dh_units = 'screen'
        glyph.dw_units = 'screen'
        glyph.dh = 60
        glyph.dw = 90
        glyph.x = x_range.start
        glyph.y = y_range.start
        xcode = CustomJS(code="glyph.x = cb_obj.start", args={'glyph': glyph})
        plot.handles['x_range'].js_on_change('start', xcode)
        ycode = CustomJS(code="glyph.y = cb_obj.start", args={'glyph': glyph})
        plot.handles['y_range'].js_on_change('start', ycode)

    def plot_limits(plot, element):
        plot.handles['x_range'].min_interval = 100
        plot.handles['x_range'].max_interval = 55000000
        # 3000000
        plot.handles['y_range'].min_interval = 500
        plot.handles['y_range'].max_interval = 900000

    opts = dict(width=700, height=700, tools=['hover', 'save', 'wheel_zoom'], active_tools=['wheel_zoom'],
                hooks=[plot_limits], colorbar=True, color_levels=15,
                colorbar_opts=colorbar_opts, cmap=['#000080',
                                                   '#0000cd',

                                                   '#0008ff',
                                                   '#004cff',
                                                   '#0090ff',
                                                   '#00d4ff',
                                                   '#29ffce',
                                                   '#60ff97',
                                                   '#97ff60',
                                                   '#ceff29',
                                                   '#ffe600',
                                                   '#ffa700',

                                                   '#ff2900',
                                                   '#cd0000',
                                                   '#800000',

                                                   ], clim=(0, 15), title="\t\t\t\t\t\t\t\t\t Mean Period (s) ",
                fontsize={'title': 18, 'xlabel': 15, 'ylabel': 15, 'ticks': 12})

    #tiles = gv.tile_sources.Wikipedia
    hmap1 = hv.HoloMap(allplot, kdims=['Select D :', 'Select State'])

    dd = df_div.opts(width=70, height=70)
    finalplot = pn.Column(pn.Row(dd),  rasterize(hmap1).options(**opts) * logo1.opts(hooks=[absolute_position],
                                                                                            apply_ranges=False))
    from bokeh.embed import components
    from bokeh.resources import CDN
    from bokeh.io import curdoc
    doc = curdoc()

    def modify_doc(doc):
        sea = (name='Sea Surface')
        doc.add_root(sea.panel().get_root(doc))
    # Put all the tabs into one application
    #tabs = Tabs(tabs=[tab1, tab2, tab3, tab4, tab5])  # Put the tabs in the current document for display
   # doc=curdoc().add_root(finalplot)
    script, div = components(finalplot.get_root(doc))
    cdn_js0=CDN.js_files[0]
    cdn_js = CDN.js_files[1]
    cdn_css=CDN.css_files
    print("cdn_js:",cdn_js)
    print("cdn_css",cdn_css)

    return render_template("plot.html",
                           script=script,
                           div=div,
                           cdn_css=cdn_css,
                           cdn_js=cdn_js,
                           cdn_js0=cdn_js0)
示例#14
0
    def set_hv_loading_message(self, message: str):
        """Replaces the plot with a loading message"""
        message_plot = hv.Div(
            SPINNER_HTML + f"<p align='center'><strong>{message}<strong></p>")

        self.plot_pane.object = message_plot
示例#15
0
文件: regression.py 项目: desihub/qlf
                                                     camera,
                                                     begin_date=start_date,
                                                     end_date=end_date)

    df_y = pd.DataFrame(list(outputs_y))
    df_x = pd.DataFrame(list(outputs_x))

    plot = hv.Curve([])
    df_x[yaxis] = df_y['value'].apply(lambda x: x[0])
    df_x[xaxis] = df_x['value'].apply(lambda x: x[0])
    plot = hv.Points(df_x, [xaxis, yaxis],
                     ['exposure_id', 'camera', 'datef', 'dateobs'])
    layout = plot.redim.label(x=xaxis,
                              y=yaxis).opts(sizing_mode='scale_width',
                                            height=150,
                                            padding=0.1,
                                            fontsize='1.2vw',
                                            toolbar='above',
                                            active_tools=["box_zoom"],
                                            title='Camera: {}'.format(camera))
    doc = renderer.server_doc(layout)
    doc.title = 'Time Series'
except Exception as e:
    renderer = hv.renderer('bokeh')
    print('error', e)
    doc = renderer.server_doc(
        hv.Div("""
        <p style="font-size: 2.2vw"> Couldn't Load Regression </p>
    """))
    doc.title = 'Regression Error'
示例#16
0
def modify_doc(doc):
    import pandas as pd

    import numpy as np
    import geoviews as gv

    import bokeh

    import panel as pn

    import holoviews as hv
    from holoviews import opts
    from holoviews.operation.datashader import datashade, rasterize
    hv.extension("bokeh")

    import math

    from bokeh.models import HoverTool

    from scipy.interpolate import griddata
    from scipy.io import loadmat

    import datetime

    from dateutil.parser import parse

    from datetime import timedelta
    import time
    strtt = time.time()

    # datamat = loadmat('IOEC_ECM_noDA_20190703_masked.mat')

    datamat = loadmat('newtest_Tm02.mat')
    source = ColumnDataSource(data=datamat)
    Xp = datamat['Xp']
    Yp = datamat['Yp']

    # Xp=np.where(((Xp>= 85) & (Xp<=88) & (Yp>=19) & (Yp<=22)),Xp,88)
    # Yp=np.where(((Xp>= 85) & (Xp<=88) & (Yp>=19) & (Yp<=22)),Yp,22)

    strt = datetime.datetime(2019, 7, 4, 0, 0)
    end = datetime.datetime(2019, 1, 13, 0, 0)
    from bokeh.models.callbacks import CustomJS

    def perdelta(strt, end, delta):
        curr = strt
        while curr < end:
            yield curr
            curr += delta

    # Read element file

    tri_new = pd.read_csv('fort.ele', delim_whitespace=True, names=('A', 'B', 'C', 'D'), usecols=[1, 2, 3], skiprows=1,
                          dtype={'D': np.int})

    dateList = []

    def plotthis(datetime, regions='Whole_East_Coast'):
        dat = datetime
        # datetostr=result.strftime("%Y%b%d%H")
        dt = parse(str(dat))
        yr = dt.year
        mn = dt.month
        d = dt.day
        hr = dt.hour
        mi = dt.minute

        if hr < 10:

            hr = '0' + str(hr)
        else:
            d = str(d)
            hr = str(hr)
        if int(d) < 10:
            d = '0' + str(d)
        else:
            d = str(d)
        varname = 'Tm02_' + str(yr) + '0' + str(mn) + str(d) + '_' + hr + '0000'

        x = Xp.flatten()
        y = Yp.flatten()
        z = datamat[varname]

        if regions is 'Odisha':
            z = np.where(((Xp >= 85) & (Xp <= 88) & (Yp >= 19) & (Yp <= 22)), z, np.nan).flatten()
        elif regions is 'Andra_Pradesh':
            z = np.where(((Xp >= 79) & (Xp <= 85) & (Yp >= 13) & (Yp <= 19)), z, np.nan).flatten()
        elif regions is 'Tamil_Nadu':
            z = np.where(((Xp >= 77) & (Xp <= 83) & (Yp >= 7) & (Yp <= 14)), z, np.nan).flatten()
        elif regions is 'Whole_East_Coast':
            z = z.flatten()

        else:
            #         data = get_data4region(data,**odisha)
            z = z.flatten()

        # z = z.flatten()
        Longitude = x
        Latitude = y
        MeanWavePeriod = z

        pts = np.stack((Longitude, Latitude, MeanWavePeriod)).T
        verts = pd.DataFrame(np.stack((Longitude, Latitude, MeanWavePeriod)).T,
                             columns=['Longitude', 'Latitude', ' MeanWavePeriod'])

        # openStreet Background.
        tri_sub = tri_new.apply(lambda x: x - 1)
        ggpoints = gv.Points(verts, vdims=[' MeanWavePeriod'])
        ggsubraster = rasterize(gv.TriMesh((tri_sub, gv.Points(verts))))

        tri = gv.TriMesh((tri_sub, gv.Points(verts)))

        return tri

    allplot = {(k.strftime("%Y-%m-%d %H:%M:%S"), r): plotthis(k, r) for k in
               perdelta(strt, strt + timedelta(days=2), timedelta(hours=18)) for r in
               ['Odisha', 'Andra_Pradesh', 'Whole_East_Coast', 'Tamil_Nadu']}

    df_div = hv.Div("""
            <figure>
            <img src="https://i.ibb.co/S0t5GWb/imglogo.png" height='80' width='90' vspace='-10'>
            """)

    df_div1 = hv.Div("""
            &nbsp<center><b><p style="color:#B22222";font-size:80px;font-family:Times new roman><h1 style=font-size:20px;margin-left:2.5em;margin-top:-1em;color:#B22222>Indian National Center for Ocean Information Services<br />
            (INCOIS)</h1></p></b></center>

            """)

    colorbar_opts = {
        'major_label_overrides': {
            0: '0',

            1: '1',

            2: '2',

            3: '3',

            4: '4',

            5: '5',
            6: '6',

            7: '7',
            8: '8',
            9: '9',
            10: '10',
            11: '11',
            12: '12',
            13: '13',
            14: '>14',
            15: '15'

        },
        'major_label_text_align': 'left', 'major_label_text_font_style': 'bold', }
    levels = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ]

    def disable_logo(plot, element):
        plot.state.toolbar.logo = None

    hv.plotting.bokeh.ElementPlot.finalize_hooks.append(disable_logo)

    # logo1 = hv.RGB.load_image("imglogo.png")

    logo1 = hv.RGB.load_image("https://i.ibb.co/7VXRPCS/logo1.png")

    def absolute_position(plot, element):
        glyph = plot.handles['glyph']
        x_range, y_range = plot.handles['x_range'], plot.handles['y_range']
        glyph.dh_units = 'screen'
        glyph.dw_units = 'screen'
        glyph.dh = 60
        glyph.dw = 90
        glyph.x = x_range.start
        glyph.y = y_range.start
        xcode = CustomJS(code="glyph.x = cb_obj.start", args={'glyph': glyph})
        plot.handles['x_range'].js_on_change('start', xcode)
        ycode = CustomJS(code="glyph.y = cb_obj.start", args={'glyph': glyph})
        plot.handles['y_range'].js_on_change('start', ycode)

    def plot_limits(plot, element):
        plot.handles['x_range'].min_interval = 100
        plot.handles['x_range'].max_interval = 55000000
        # 3000000
        plot.handles['y_range'].min_interval = 500
        plot.handles['y_range'].max_interval = 900000

    opts = dict(width=700, height=700, tools=['hover', 'save', 'wheel_zoom'], active_tools=['wheel_zoom'],
                hooks=[plot_limits, disable_logo], colorbar=True, color_levels=15,
                colorbar_opts=colorbar_opts, cmap=['#000080',
                                                   '#0000cd',

                                                   '#0008ff',
                                                   '#004cff',
                                                   '#0090ff',
                                                   '#00d4ff',
                                                   '#29ffce',
                                                   '#60ff97',
                                                   '#97ff60',
                                                   '#ceff29',
                                                   '#ffe600',
                                                   '#ffa700',
                                                   # '#ff6800',
                                                   '#ff2900',
                                                   '#cd0000',
                                                   '#800000',

                                                   ], clim=(0, 15), title="\t\t\t\t\t\t\t\t\t Mean Wave Period (s) ",
                fontsize={'title': 18, 'xlabel': 15, 'ylabel': 15, 'ticks': 12})

    tiles = gv.tile_sources.Wikipedia
    print("type(allplot):", type(allplot))
    print("allplot :", allplot)
    # for k,v in allplot.items():
    #     print("current key:",k)
    #     print("current value:",v)

    print("allplot.keys()[1]:", list(allplot.keys())[1])
    print("allplot.keys()[2]:", list(allplot.keys())[2])
    hmap1 = hv.HoloMap(allplot, kdims=['Select Date and Time :', 'Select Indian State'])
    print("type(hmap1):", type(hmap1))
    print("list(hmap1)[1]", list(hmap1)[1])
    dd = df_div.opts(width=70, height=70)
    dd1 = df_div1.opts(width=600, height=90)

    def callback(attr, old, new):
        if new == 0:
            finalplot = pn.Column(pn.Row(dd, dd1),
                                  tiles * rasterize(list(hmap1)[1]).options(**opts) * logo1.opts(
                                      hooks=[absolute_position],
                                      apply_ranges=False))
        else:
            #data = df.rolling('{0}D'.format(new)).mean()
            finalplot = pn.Column(pn.Row(dd, dd1),
                                  tiles * rasterize(list(hmap1)[1]).options(**opts) * logo1.opts(
                                      hooks=[absolute_position],
                                      apply_ranges=False))
        source.data = ColumnDataSource(data=finalplot).data

    slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days")
    slider.on_change('value', callback)

    doc.add_root(column(slider, finalplot))
示例#17
0
文件: app.py 项目: TimoRoth/glaciers
def count(data):
    return hv.Div('<p style="font-size:20px">Glaciers selected: {}'.format(len(data)) + "<br>" +
                  'Area: {:.0f} km² ({:.1f}%)</font>'.format(np.sum(data['area_km2']), np.sum(data['area_km2']) / total_area * 100)).options(height=40)
示例#18
0
def count(data):
    return hv.Div('<p style="font-size:20px">Glaciers selected: ' +
                  str(data.dframe().n_glaciers.sum()) +
                  "</font>").options(height=40)
示例#19
0
                         width=500))

    if f == 'year':
        yearHisto = np.histogram(to_years(dob), bins=200)
        histograms.append(
            hv.Histogram(yearHisto,
                         kdims=['Year of Birth'],
                         height=500,
                         width=500))

    if f == 'date':
        dateHisto = np.histogram(to_date(dob), bins=200)
        histograms.append(
            hv.Histogram(dateHisto,
                         kdims=['Dates of Birth'],
                         height=500,
                         width=500))

layout = hv.Layout()
#%%
for h in histograms:
    layout = layout + h

df_html = df[['DOB']].describe().to_html()
df_div = hv.Div("<div align='right'>" + df_html + "<div>")

layout = layout + df_div

#%%
hv.save(layout, 'dobHistogram.html')