Python bokeh.plotting.ColumnDataSource() Examples

The following are 22 code examples of bokeh.plotting.ColumnDataSource(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bokeh.plotting , or try the search function .
Example #1
Source File: interact_bls.py    From lightkurve with MIT License 6 votes vote down vote up
def prepare_bls_datasource(result, loc):
    """Prepare a bls result for bokeh plotting

    Parameters
    ----------
    result : BLS.model result
        The BLS model result to use
    loc : int
        Index of the "best" period. (Usually the max power)

    Returns
    -------
    bls_source : Bokeh.plotting.ColumnDataSource
        Bokeh style source for plotting
    """
    bls_source = ColumnDataSource(data=dict(
                                        period=result['period'],
                                        power=result['power'],
                                        depth=result['depth'],
                                        duration=result['duration'],
                                        transit_time=result['transit_time']))
    bls_source.selected.indices = [loc]
    return bls_source 
Example #2
Source File: interact_bls.py    From lightkurve with MIT License 6 votes vote down vote up
def prepare_folded_datasource(folded_lc):
    """Prepare a FoldedLightCurve object for bokeh plotting.

    Parameters
    ----------
    folded_lc : lightkurve.FoldedLightCurve
        The folded lightcurve

    Returns
    -------
    folded_source : Bokeh.plotting.ColumnDataSource
        Bokeh style source for plotting
    """
    folded_src = ColumnDataSource(data=dict(
                                  phase=np.sort(folded_lc.time),
                                  flux=folded_lc.flux[np.argsort(folded_lc.time)]))
    return folded_src


# Helper functions for help text... 
Example #3
Source File: interact.py    From lightkurve with MIT License 6 votes vote down vote up
def get_lightcurve_y_limits(lc_source):
    """Compute sensible defaults for the Y axis limits of the lightcurve plot.

    Parameters
    ----------
    lc_source : bokeh.plotting.ColumnDataSource
        The lightcurve being shown.

    Returns
    -------
    ymin, ymax : float, float
        Flux min and max limits.
    """
    with warnings.catch_warnings():  # Ignore warnings due to NaNs
        warnings.simplefilter("ignore", AstropyUserWarning)
        flux = sigma_clip(lc_source.data['flux'], sigma=5, masked=False)
    low, high = np.nanpercentile(flux, (1, 99))
    margin = 0.10 * (high - low)
    return low - margin, high + margin 
Example #4
Source File: interact.py    From lightkurve with MIT License 6 votes vote down vote up
def prepare_tpf_datasource(tpf, aperture_mask):
    """Prepare a bokeh DataSource object for selection glyphs

    Parameters
    ----------
    tpf : TargetPixelFile
        TPF to be shown.
    aperture_mask : boolean numpy array
        The Aperture mask applied at the startup of interact

    Returns
    -------
    tpf_source : bokeh.plotting.ColumnDataSource
        Bokeh object to be shown.
    """
    npix = tpf.flux[0, :, :].size
    pixel_index_array = np.arange(0, npix, 1).reshape(tpf.flux[0].shape)
    xx = tpf.column + np.arange(tpf.shape[2])
    yy = tpf.row + np.arange(tpf.shape[1])
    xa, ya = np.meshgrid(xx, yy)
    tpf_source = ColumnDataSource(data=dict(xx=xa.astype(float), yy=ya.astype(float)))
    tpf_source.selected.indices = pixel_index_array[aperture_mask].reshape(-1).tolist()
    return tpf_source 
Example #5
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def jitterCurve(phmi_breakPtsNeg,landmarks_coordi,PHMI_coordi,plot_x): #LandmarkMap_dic,PHMI_dic
    output_file("PHmi_01.html")
    source=ColumnDataSource(data=dict(
        x=landmarks_coordi[0].tolist(),
        y=landmarks_coordi[1].tolist(),
        desc=[str(i) for i in list(range(landmarks_coordi[0].shape[0]))],
    ))
    TOOLTIPS=[
        ("index", "$index"),
        ("(x,y)", "($x, $y)"),
        ("desc", "@desc"),
    ]

    p=figure(plot_width=1800, plot_height=320, tooltips=TOOLTIPS,title="partition")
    p.circle('y','x',  size=5, source=source)
    p.line(PHMI_coordi[1],PHMI_coordi[0],line_color="coral", line_dash="dotdash", line_width=2)

    colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen')
    colors=colors*5
    ScalePhmi=math.pow(10,1)
    i=0
    for val,idx in zip(phmi_breakPtsNeg, plot_x):
        p.line(idx,np.array(val)*ScalePhmi,line_color=colors[i])
        i+=1

    show(p)

#04-network show between PHMI and landmarks 网络分析
#extract landmarks corresponding to the AVs' position along a route 
Example #6
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def jitterCurve(phmi_breakPtsNeg,landmarks_coordi,PHMI_coordi,plot_x): #LandmarkMap_dic,PHMI_dic
    output_file("PHmi_01.html")
    source=ColumnDataSource(data=dict(
        x=landmarks_coordi[0].tolist(),
        y=landmarks_coordi[1].tolist(),
        desc=[str(i) for i in list(range(landmarks_coordi[0].shape[0]))],
    ))
    TOOLTIPS=[
        ("index", "$index"),
        ("(x,y)", "($x, $y)"),
        ("desc", "@desc"),
    ]

    p=figure(plot_width=1800, plot_height=320, tooltips=TOOLTIPS,title="partition")
    p.circle('y','x',  size=5, source=source)
    p.line(PHMI_coordi[1],PHMI_coordi[0],line_color="coral", line_dash="dotdash", line_width=2)

    colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen')
    colors=colors*5
    ScalePhmi=math.pow(10,1)
    i=0
    for val,idx in zip(phmi_breakPtsNeg, plot_x):
        p.line(idx,np.array(val)*ScalePhmi,line_color=colors[i])
        i+=1

    show(p)

#04-network show between PHMI and landmarks 网络分析
#extract landmarks corresponding to the AVs' position along a route 
Example #7
Source File: showMatLabFig._spatioTemporal.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def jitterCurve():
    output_file("PHmi_01.html")
    source=ColumnDataSource(data=dict(
        x=LandmarkMap_dic[1][0].tolist(),
        y=LandmarkMap_dic[1][1].tolist(),
        desc=[str(i) for i in list(range(LandmarkMap_dic[1][0].shape[0]))],
    ))
    TOOLTIPS=[
        ("index", "$index"),
        ("(x,y)", "($x, $y)"),
        ("desc", "@desc"),
    ]

    p=figure(plot_width=1800, plot_height=320, tooltips=TOOLTIPS,title="partition")
    p.circle('y','x',  size=5, source=source)
    p.line(PHMI_dic[0][1],PHMI_dic[0][0],line_color="coral", line_dash="dotdash", line_width=2)

    colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen')
    ScalePhmi=math.pow(10,1)
    i=0
    for val,idx in zip(phmi_breakPtsNeg, plot_x):
        p.line(idx,np.array(val)*ScalePhmi,line_color=colors[i])
        i+=1

    show(p)

#05-network show between PHMI and landmarks 网络分析
#extract landmarks corresponding to the AVs' position along a route 
Example #8
Source File: configurator_footprint.py    From CAVE with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _scatter(self, p, source, views, markers):
        """
        Parameters
        ----------
        p: bokeh.plotting.figure
            figure
        source: ColumnDataSource
            data container
        views: List[CDSView]
            list with views to be plotted (in order!)
        markers: List[str]
            corresponding markers to the views

        Returns
        -------
        scatter_handles: List[GlyphRenderer]
            glyph renderer per view
        """
        scatter_handles = []
        for view, marker in zip(views, markers):
            scatter_handles.append(p.scatter(x='x', y='y',
                                             source=source,
                                             view=view,
                                             color='color', line_color='black',
                                             size='size',
                                             marker=marker,
                                             ))
        return scatter_handles 
Example #9
Source File: recipe_clustering.py    From Flavor-Network with GNU General Public License v3.0 5 votes vote down vote up
def plot_bokeh(df,sublist,filename):
    lenlist=[0]
    df_sub = df[df['cuisine']==sublist[0]]
    lenlist.append(df_sub.shape[0])
    for cuisine in sublist[1:]:
        temp = df[df['cuisine']==cuisine]
        df_sub = pd.concat([df_sub, temp],axis=0,ignore_index=True)
        lenlist.append(df_sub.shape[0])
    df_X = df_sub.drop(['cuisine','recipeName'],axis=1)
    print df_X.shape, lenlist

    dist = squareform(pdist(df_X, metric='cosine'))
    tsne = TSNE(metric='precomputed').fit_transform(dist)
    #cannot use seaborn palette for bokeh
    palette =['red','green','blue','yellow']
    colors =[]
    for i in range(len(sublist)):
        for j in range(lenlist[i+1]-lenlist[i]):
            colors.append(palette[i])
    #plot with boken
    output_file(filename)
    source = ColumnDataSource(
            data=dict(x=tsne[:,0],y=tsne[:,1],
                cuisine = df_sub['cuisine'],
                recipe = df_sub['recipeName']))

    hover = HoverTool(tooltips=[
                ("cuisine", "@cuisine"),
                ("recipe", "@recipe")])

    p = figure(plot_width=1000, plot_height=1000, tools=[hover],
               title="flavor clustering")

    p.circle('x', 'y', size=10, source=source,fill_color=colors)

    show(p) 
Example #10
Source File: DatVis_Bokeh_Intr_App_Build_4.py    From Python-Scripts-Repo-on-Data-Science with GNU General Public License v3.0 5 votes vote down vote up
def update():

    # Compute new y values: y
    y = np.sin(x) + np.random.random(N)

    # Update the ColumnDataSource data dictionary
    source.data = {'x': x, 'y': y}

# Add the update callback to the button 
Example #11
Source File: interact.py    From lightkurve with MIT License 5 votes vote down vote up
def prepare_lightcurve_datasource(lc):
    """Prepare a bokeh ColumnDataSource object for tool tips.

    Parameters
    ----------
    lc : LightCurve object
        The light curve to be shown.

    Returns
    -------
    lc_source : bokeh.plotting.ColumnDataSource
    """
    # Convert time into human readable strings, breaks with NaN time
    # See https://github.com/KeplerGO/lightkurve/issues/116
    if (lc.time == lc.time).all():
        human_time = lc.time.isot
    else:
        human_time = [' '] * len(lc.flux)

    # Convert binary quality numbers into human readable strings
    qual_strings = []
    for bitmask in lc.quality:
        if isinstance(bitmask, u.Quantity):
            bitmask = bitmask.value
        flag_str_list = KeplerQualityFlags.decode(bitmask)
        if len(flag_str_list) == 0:
            qual_strings.append(' ')
        if len(flag_str_list) == 1:
            qual_strings.append(flag_str_list[0])
        if len(flag_str_list) > 1:
            qual_strings.append("; ".join(flag_str_list))

    lc_source = ColumnDataSource(data=dict(
                                 time=lc.time.value,
                                 time_iso=human_time,
                                 flux=lc.flux.value,
                                 cadence=lc.cadenceno.value,
                                 quality_code=lc.quality.value,
                                 quality=np.array(qual_strings)))
    return lc_source 
Example #12
Source File: test_interact.py    From lightkurve with MIT License 5 votes vote down vote up
def test_ylim_with_nans():
    """Regression test for #679: y limits should not be NaN."""
    lc_source = ColumnDataSource({'flux': [-1, np.nan, 1]})
    ymin, ymax = get_lightcurve_y_limits(lc_source)
    # ymin/ymax used to return nan, make sure this is no longer the case
    assert ymin == -1.176
    assert ymax == 1.176 
Example #13
Source File: interact_bls.py    From lightkurve with MIT License 5 votes vote down vote up
def prepare_f_help_source(f):
    data = dict(phase=[(np.max(f.time) - np.min(f.time)) * 0.98 + np.min(f.time)],
                flux=[(np.max(f.flux) - np.min(f.flux)) * 0.98 + np.min(f.flux)],
                helpme=['?'],
                help=["""
                        <div style="width: 375px;">
                            <div style="height: 190px;">
                            </div>
                            <div>
                                <span style="font-size: 12px; font-weight: bold;">Folded Light Curve</span>
                            </div>
                            <div>
                                <span style="font-size: 11px;"">This panel shows the folded light curve,
                                using the period currently selected in the BLS panel [left], indicated by the red line.
                                The transit model is show in red, and duration of the transit model
                                is given by the duration slider below. Update the slider to change the duration.
                                The period and transit midpoint values of the model are given above this panel.</span>
                                <br></br>
                                <span style="font-size: 11px;"">If the folded transit looks like a near miss of
                                the true period, try zooming in on the peak in the BLS Periodogram panel [right]
                                with the Box Zoom tool. This will increase the resolution of the peak, and provide
                                a better period solution. You can also vary the transit duration, for a better fit.
                                If the transit model is too shallow, it may be that you have selected a harmonic.
                                Look in the BLS Periodogram for a peak at (e.g. 0.25x, 0.5x, 2x, 4x the current period etc).</span>
                            </div>
                        </div>
                """])
    return ColumnDataSource(data=data) 
Example #14
Source File: interact_bls.py    From lightkurve with MIT License 5 votes vote down vote up
def prepare_bls_help_source(bls_source, slider_value):
    data = dict(period=[bls_source.data['period'][int(slider_value*0.95)]],
                power=[(np.max(bls_source.data['power']) - np.min(bls_source.data['power'])) * 0.98 + np.min(bls_source.data['power'])],
                helpme=['?'],
                help=["""
                             <div style="width: 375px;">
                                 <div style="height: 190px;">
                                 </div>
                                 <div>
                                     <span style="font-size: 12px; font-weight: bold;">Box Least Squares Periodogram</span>
                                 </div>
                                 <div>
                                     <span style="font-size: 11px;"">This panel shows the BLS periodogram for
                                      the light curve shown in the lower panel.
                                     The current selected period is highlighted by the red line.
                                     The selected period is the peak period within the range.
                                     The Folded Light Curve panel [right] will update when a new period
                                     is selected in the BLS Panel. You can select a new period either by
                                     using the Box Zoom tool to select a smaller range, or by clicking on the peak you want to select. </span>
                                     <br></br>
                                     <span style="font-size: 11px;"">The panel is set at the resolution
                                     given by the Resolution Slider [bottom]. This value is the number
                                     of points in the BLS Periodogram panel.
                                     Increasing the resolution will make the BLS Periodogram more accurate,
                                     but slower to render. To increase the resolution for a given peak,
                                     simply zoom in with the Box Zoom Tool.</span>

                                 </div>
                             </div>
                         """])
    return ColumnDataSource(data=data) 
Example #15
Source File: main.py    From REINVENT with MIT License 5 votes vote down vote up
def create_hist_plot(init_data, title):
    source = ColumnDataSource(data=dict(hist=[], left_edge=[], right_edge=[]))
    init_hist, init_edge = np.histogram(init_data, density=True, bins=50)
    fig = figure(title=title, plot_width=300, plot_height=300)
    fig.quad(top=init_hist, bottom=0, left=init_edge[:-1], right=init_edge[1:],
            fill_alpha=0.05)
    fig.quad(top='hist', bottom=0, left='left_edge', right='right_edge',
            fill_alpha=0.3, source=source)
    return fig, source 
Example #16
Source File: main.py    From REINVENT with MIT License 5 votes vote down vote up
def create_bar_plot(init_data, title):
    init_data = downsample(init_data, 50)
    x = range(len(init_data))
    source = ColumnDataSource(data=dict(x= [], y=[]))
    fig = figure(title=title, plot_width=300, plot_height=300)
    fig.vbar(x=x, width=1, top=init_data, fill_alpha=0.05)
    fig.vbar('x', width=1, top='y', fill_alpha=0.3, source=source)
    fig.y_range = Range1d(min(0, 1.2 * min(init_data)), 1.2 * max(init_data))
    return fig, source 
Example #17
Source File: interact_bls.py    From lightkurve with MIT License 4 votes vote down vote up
def make_folded_figure_elements(f, f_model_lc, f_source, f_model_lc_source, help_source):
    """Make a scatter plot of a FoldedLightCurve.

    Parameters
    ----------
    f : lightkurve.LightCurve
        Folded light curve to plot
    f_model_lc :  lightkurve.LightCurve
        Model folded light curve to plot
    f_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for plotting folded light curve
    f_model_lc_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for plotting model folded light curve
    help_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for rendering help button

    Returns
    -------
    fig : bokeh.plotting.figure
        Bokeh figure object
    """

    # Build Figure
    fig = figure(title='Folded Light Curve', plot_height=340, plot_width=450,
                 tools="pan,box_zoom,reset",
                 toolbar_location="below",
                 border_fill_color="#FFFFFF", active_drag="box_zoom")
    fig.title.offset = -10
    fig.yaxis.axis_label = 'Flux'
    fig.xaxis.axis_label = 'Phase'

    # Scatter point for data
    fig.circle('phase', 'flux', line_width=1, color='#191919',
               source=f_source, nonselection_line_color='#191919',
               nonselection_line_alpha=1.0, size=0.1)

    # Line plot for model
    fig.step('phase', 'flux', line_width=3, color='firebrick',
             source=f_model_lc_source, nonselection_line_color='firebrick',
             nonselection_line_alpha=1.0)

    # Help button
    question_mark = Text(x="phase", y="flux", text="helpme", text_color="grey",
                         text_align='center', text_baseline="middle",
                         text_font_size='12px', text_font_style='bold',
                         text_alpha=0.6)
    fig.add_glyph(help_source, question_mark)
    help = fig.circle('phase', 'flux', alpha=0.0, size=15, source=help_source,
                      line_width=2, line_color='grey', line_alpha=0.6)

    tooltips = help_source.data['help'][0]
    fig.add_tools(HoverTool(tooltips=tooltips, renderers=[help],
                            mode='mouse', point_policy="snap_to_data"))
    return fig 
Example #18
Source File: configurator_footprint.py    From CAVE with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _create_views(self, source, used_configs):
        """Create views in order of plotting, so more interesting views are
        plotted on top. Order of interest:
        default > final-incumbent > incumbent > candidate
          local > random
            num_runs (ascending, more evaluated -> more interesting)
        Individual views are necessary, since bokeh can only plot one
        marker-type (circle, triangle, ...) per 'scatter'-call

        Parameters
        ----------:
        source: ColumnDataSource
            containing relevant information for plotting
        used_configs: List[Configuration]
            configs that are contained in this source. necessary to plot glyphs for the independent runs so they can be
            toggled. not all configs are in every source because of efficiency: no need to have 0-runs configs

        Returns
        -------
        views: List[CDSView]
            views in order of plotting
        views_by_run: Dict[ConfiguratorRun -> List[int]]
            maps each run to a list of indices of the related glyphs in the returned 'views'-list
        markers: List[string]
            markers (to the view with the same index)
        """

        def _get_marker(t, o):
            """ returns marker according to type t and origin o """
            if t == "Default":
                shape = 'triangle'
            elif t == 'Final Incumbent':
                shape = 'inverted_triangle'
            else:
                shape = 'square' if t == "Incumbent" else 'circle'
                shape += '_x' if o.startswith("Acquisition Function") else ''
            return shape

        views, markers = [], []
        views_by_run = {run : [] for run in self.configs_in_run}
        idx = 0
        for t in ['Candidate', 'Incumbent', 'Final Incumbent', 'Default']:
            for o in ['Unknown', 'Random', 'Acquisition Function']:
                for z in sorted(list(set(source.data['zorder'])), key=lambda x: int(x)):
                    for run, configs in self.configs_in_run.items():
                        booleans = [True if c in configs else False for c in used_configs]
                        view = CDSView(source=source, filters=[
                                GroupFilter(column_name='type', group=t),
                                GroupFilter(column_name='origin', group=o),
                                GroupFilter(column_name='zorder', group=z),
                                BooleanFilter(booleans)])
                        views.append(view)  # all views
                        views_by_run[run].append(idx)  # views sorted by runs
                        idx += 1
                        markers.append(_get_marker(t, o))
        self.logger.debug("%d different glyph renderers, %d different zorder-values",
                          len(views), len(set(source.data['zorder'])))
        return (views, views_by_run, markers) 
Example #19
Source File: interact_bls.py    From lightkurve with MIT License 4 votes vote down vote up
def prepare_lc_help_source(lc):
    data = dict(time=[(np.max(lc.time) - np.min(lc.time)) * 0.98 + np.min(lc.time)],
                flux=[(np.max(lc.flux) - np.min(lc.flux)) * 0.9 + np.min(lc.flux)],
                boxicon=['https://bokeh.pydata.org/en/latest/_images/BoxZoom.png'],
                panicon=['https://bokeh.pydata.org/en/latest/_images/Pan.png'],
                reseticon=['https://bokeh.pydata.org/en/latest/_images/Reset.png'],
                tapicon=['https://bokeh.pydata.org/en/latest/_images/Tap.png'],
                hovericon=['https://bokeh.pydata.org/en/latest/_images/Hover.png'],
                helpme=['?'],
                help=["""
                             <div style="width: 550px;">
                                 <div>
                                     <span style="font-size: 12px; font-weight: bold;">Light Curve</span>
                                 </div>
                                 <div>
                                     <span style="font-size: 11px;"">This panel shows the full light curve, with the BLS model overlayed in red. The period of the model is the period
                                     currently selected in the BLS panel [top, left], indicated by the vertical red line. The duration of the transit model is given by the duration slider below..</span>
                                     <br></br>
                                 </div>
                                 <div>
                                     <span style="font-size: 12px; font-weight: bold;">Bokeh Tools</span>
                                 </div>
                                 <div>
                                     <span style="font-size: 11px;"">Each of the three panels have Bokeh tools to navigate them.
                                     You can turn off/on each tool by clicking the icon in the tray below each panel.
                                     You can zoom in using the Box Zoom Tool, move about the panel using the Pan Tool,
                                     or reset the panel back to the original view using the Reset Tool. </span>
                                     <br></br>
                                     <center>
                                         <table>
                                             <tr>
                                                 <td><img src="@boxicon" height="20" width="20"></td><td><span style="font-size: 11px;"">Box Zoom Tool</span></td>
                                             </tr>
                                             <tr>
                                                 <td><img src="@panicon" height="20" width="20"></td><td><span style="font-size: 11px;"">Pan Tool</span></td>
                                             </tr>
                                             <tr>
                                                 <td><img src="@reseticon" height="20" width="20"></td><td><span style="font-size: 11px;"">Reset Tool</span></td>
                                             </tr>
                                             <tr>
                                                 <td><img src="@tapicon" height="20" width="20"></td><td><span style="font-size: 11px;"">Tap Tool (select periods in BLS Panel only)</span></td>
                                             </tr>
                                             <tr>
                                                 <td><img src="@hovericon" height="20" width="20"></td><td><span style="font-size: 11px;"">Help Messages (click to disable/enable help)</span></td>
                                             </tr>
                                         </table>
                                     </center>
                                 </div>
                             </div>
                         """])
    return ColumnDataSource(data=data) 
Example #20
Source File: showMatLabFig._spatioTemporal.py    From python-urbanPlanning with MIT License 4 votes vote down vote up
def interactiveG(G):
    from bokeh.models.graphs import NodesAndLinkedEdges,from_networkx
    from bokeh.models import Circle, HoverTool, MultiLine,Plot,Range1d,StaticLayoutProvider
    from bokeh.plotting import figure, output_file, show, ColumnDataSource
    from bokeh.io import output_notebook, show
    output_notebook()
    # We could use figure here but don't want all the axes and titles  
    #plot=Plot(plot_width=1600, plot_height=300, tooltips=TOOLTIPS,title="PHmi+landmarks+route+power(10,-5)",x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
    
    output_file("PHMI_network")
    source=ColumnDataSource(data=dict(
        x=locations[0].tolist(),
        #x=[idx for idx in range(len(PHMIList))],
        #y=locations[1].tolist(),
        y=PHMIList,
        #desc=[str(i) for i in PHMIList],
        #PHMI_value=PHMI_dic[0][0].tolist(),    
    ))
    TOOLTIPS=[
        ("index", "$index"),
        ("(x,y)", "($x, $y)"),
        #("desc", "@desc"),
        #("PHMI", "$PHMI_value"),
    ]
    
    
    plot=figure(x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1),plot_width=2200, plot_height=500,tooltips=TOOLTIPS,title="PHMI_network")
    
    #G_position={key:(G.position[key][1],G.position[key][0]) for key in G.position.keys()}
    graph = from_networkx(G,nx.spring_layout,scale=1, center=(0,0))  
    #plot.renderers.append(graph) 
    
    fixed_layout_provider = StaticLayoutProvider(graph_layout=G.position)
    graph.layout_provider = fixed_layout_provider
    plot.renderers.append(graph)
    
    # Blue circles for nodes, and light grey lines for edges  
    graph.node_renderer.glyph = Circle(size=5, fill_color='#2b83ba')  
    graph.edge_renderer.glyph = MultiLine(line_color="#cccccc", line_alpha=0.8, line_width=2)  
      
    # green hover for both nodes and edges  
    graph.node_renderer.hover_glyph = Circle(size=25, fill_color='#abdda4')  
    graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4', line_width=4)  
      
    # When we hover over nodes, highlight adjecent edges too  
    graph.inspection_policy = NodesAndLinkedEdges()  
      
    plot.add_tools(HoverTool(tooltips=None))  
     
    colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen')
    ScalePhmi=math.pow(10,1)
    i=0
    for val,idx in zip(phmi_breakPtsNeg, plot_x):
        plot.line(idx,np.array(val)*ScalePhmi,line_color=colors[i])
        i+=1    
        
    show(plot)
    
#06-single landmarks pattern 无人车位置点与对应landmarks栅格图
#convert location and corresponding landmarks to raster data format using numpy.histogram2d 
Example #21
Source File: driverlessCityProject_spatialPointsPattern_association_basic.py    From python-urbanPlanning with MIT License 4 votes vote down vote up
def interactiveG(G):
    from bokeh.models.graphs import NodesAndLinkedEdges,from_networkx
    from bokeh.models import Circle, HoverTool, MultiLine,Plot,Range1d,StaticLayoutProvider
    from bokeh.plotting import figure, output_file, show, ColumnDataSource
    from bokeh.io import output_notebook, show
    output_notebook()
    # We could use figure here but don't want all the axes and titles  
    #plot=Plot(plot_width=1600, plot_height=300, tooltips=TOOLTIPS,title="PHmi+landmarks+route+power(10,-5)",x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
    
    output_file("PHMI_network")
    source=ColumnDataSource(data=dict(
        x=locations[0].tolist(),
        #x=[idx for idx in range(len(PHMIList))],
        #y=locations[1].tolist(),
        y=PHMIList,
        #desc=[str(i) for i in PHMIList],
        #PHMI_value=PHMI_dic[0][0].tolist(),    
    ))
    TOOLTIPS=[
        ("index", "$index"),
        ("(x,y)", "($x, $y)"),
        #("desc", "@desc"),
        #("PHMI", "$PHMI_value"),
    ]
    
    
    plot=figure(x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1),plot_width=2200, plot_height=500,tooltips=TOOLTIPS,title="PHMI_network")
    
    #G_position={key:(G.position[key][1],G.position[key][0]) for key in G.position.keys()}
    graph = from_networkx(G,nx.spring_layout,scale=1, center=(0,0))  
    #plot.renderers.append(graph) 
    
    fixed_layout_provider = StaticLayoutProvider(graph_layout=G.position)
    graph.layout_provider = fixed_layout_provider
    plot.renderers.append(graph)
    
    # Blue circles for nodes, and light grey lines for edges  
    graph.node_renderer.glyph = Circle(size=5, fill_color='#2b83ba')  
    graph.edge_renderer.glyph = MultiLine(line_color="#cccccc", line_alpha=0.8, line_width=2)  
      
    # green hover for both nodes and edges  
    graph.node_renderer.hover_glyph = Circle(size=25, fill_color='#abdda4')  
    graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4', line_width=4)  
      
    # When we hover over nodes, highlight adjecent edges too  
    graph.inspection_policy = NodesAndLinkedEdges()  
      
    plot.add_tools(HoverTool(tooltips=None))  
     
    colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen')
    ScalePhmi=math.pow(10,1)
    i=0
    for val,idx in zip(phmi_breakPtsNeg, plot_x):
        plot.line(idx,np.array(val)*ScalePhmi,line_color=colors[i])
        i+=1    
        
    show(plot)
    
#05-single landmarks pattern 无人车位置点与对应landmarks栅格图
#convert location and corresponding landmarks to raster data format using numpy.histogram2d 
Example #22
Source File: dos.py    From qmpy with MIT License 4 votes vote down vote up
def bokeh_plot(self):
        if self._bokeh_plot is None:
            spinflag = False
            if len(self.dos) == 2:
                spinflag = True

            if spinflag:
                source = bkp.ColumnDataSource(data=dict(
                    en = self.energy,
                    up = self.dos[0],
                    down = -self.dos[1],
                ))
            else:
                source = bkp.ColumnDataSource(data=dict(
                    en = self.energy,
                    dos = self.dos[0],
                ))

            p = bkp.figure(width=500, height=300,
                           x_range=(-6, 6),
                           tools=['pan', 'box_zoom', 'hover', 'reset', 'save', 'help'])

            p.title.text = 'Density of States'
            p.title.align = 'center'
            p.title.text_font_size = "15pt"

            p.xaxis.axis_label = u'E \u2212 E_Fermi (eV)'
            p.xaxis.axis_label_text_font_size = '14pt'
            p.xaxis.major_label_text_font_size = '12pt'

            p.yaxis.axis_label = '# of states (arb. units)'
            p.yaxis.axis_label_text_font_size = '14pt'
            p.yaxis.major_label_text_font_size = '12pt'

            
            vline = Span(location=0, dimension='height', 
                         line_color='gray', line_width=1.5,
                         line_dash='dashed')
            p.renderers.extend([vline])

            if spinflag:
                p.line('en', 'up',   line_width = 2, line_color = 'blue',
                       legend="Spin Up",   source=source)
                p.line('en', 'down', line_width = 2, line_color = 'orange', 
                       legend="Spin Down", source=source)
            else:
                p.line('en', 'dos',  line_width = 2, line_color = 'blue',
                       legend='total',       source=source)

            p.legend.click_policy = "hide"
            self._bokeh_plot = p

        return self._bokeh_plot