Exemple #1
0
def histogram(arr, xlbl, xrng=None, nbins=20, alpha=1.):
    """ Generate a bokeh histogram

    Parameters
    ----------
    arr : ndarray
    xlbl : str
      Label for the x-axis
    xrng : tuple, optional
      xmin, xmax
    nbins : int, optional
      number of bins
    alpha : float, optional
      alpha for
    """
    if xrng is None:
        xrng = (np.min(arr),np.max(arr))
    p = figure(plot_width=600, plot_height=400)
    # Histogram
    hist, edges = np.histogram(arr, range=xrng, density=True, bins=nbins)
    p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color='blue', alpha=alpha)
    # Label
    p.xaxis.axis_label = xlbl
    # Show
    show(p)
Exemple #2
0
def test_show_doesnt_duplicate_if_already_there(m):
    io._state.document.clear()
    p = Plot()
    io.show(p)
    assert io._state.document.roots == [p]
    io.show(p)
    assert io._state.document.roots == [p]
def df_plot(dfD, xCol, yCols, width=600, height=600):

    hover1 = HoverTool(tooltips=[("x,y", "(@x, @y)")])
    tools1 = ["pan,resize,box_zoom,wheel_zoom,crosshair",hover1,"reset,save"]
    hover2 = HoverTool(tooltips=[("x,y", "(@x, @y)")])
    tools2 = ["pan,resize,box_zoom,wheel_zoom,crosshair",hover2,"reset,save"]
    
    plot1 = figure(width=width, height=height, tools=tools1)
    plot2 = figure(width=width, height=height, tools=tools2,
            x_range=plot1.x_range, y_range=plot1.y_range)
   
    tab1 = Panel(child=plot1, title="line + points")
    tab2 = Panel(child=plot2, title="points only")
 
    for i in yCols:
    	if dfD.iloc[:,i].count() > 0:
    		plot1.line(dfD.iloc[:,xCol],dfD.iloc[:,i], line_color=colors[i], line_width=1, legend=dfD.columns[i])
    		plot1.scatter(dfD.iloc[:,xCol],dfD.iloc[:,i], marker="+", line_color=colors[i], line_width=1, legend=dfD.columns[i])
    		plot2.scatter(dfD.iloc[:,xCol],dfD.iloc[:,i], marker="+", line_color=colors[i], line_width=1, legend=dfD.columns[i])
   
    tabs = Tabs(tabs=[ tab1, tab2 ])

    show(tabs) 

    return tabs
def create_map(tab_del_file):
    """
    This function was adapted from bokeh tutorial, so it might have similar
     elements in it.
    """
    data = pandas.read_csv(tab_del_file, sep="\\t", engine='python')
    lat_mean = data["Lat"].mean()
    long_mean = data["Long"].mean()
    map_options = GMapOptions(lat=lat_mean, lng=long_mean, map_type="hybrid",
                              zoom=5)
    plot = GMapPlot(x_range=DataRange1d(),
                    y_range=DataRange1d(),
                    map_options=map_options,
                    title="PopART-XTREME"
                    )
    source = ColumnDataSource(data=dict(lat=[x for x in data["Lat"]],
                                        lon=[y for y in data["Long"]],
                                        name=[s for s in data["Sequence"]],
                                        local=[l for l in data["Locality"]]))
    circle = Circle(x="lon", y="lat", size=15, fill_color="blue",
                    fill_alpha=0.8, line_color=None)
    tooltips = [("Sequence", "@name"), ("Locality", "@local")]

    render = plot.add_glyph(source, circle)
    plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool(), BoxZoomTool(),
                   PreviewSaveTool(), HoverTool(tooltips=tooltips,
                   renderers=[render]))
    output_file("map_plot.html")
    show(plot)
def stockPlots():
    # Load the index data so that it can be plotted
    dateDataSP500, openDataSP500 = SP500.convertPlotData(percentage='y')
    dateDataSSEC, openDataSSEC = SSEC.convertPlotData(percentage='y')
    dateDataN225, openDataN225 = N225.convertPlotData(percentage='y')  
    dateDataASX, openDataASX = ASX.convertPlotData(percentage='y')  
    dateDataFTSE, openDataFTSE = FTSE.convertPlotData(percentage='y')         
    
    #Plots data using Bokeh
    pTest = figure(plot_width=1200, plot_height=700, title="Stock Indices")
    pTest.line(dateDataSP500, openDataSP500, line_width=2, line_color="green", legend = "S&P 500")
    pTest.line(dateDataSSEC, openDataSSEC, line_width=2, line_color="red", legend="SSEC")
    pTest.line(dateDataN225, openDataN225, line_width=2, legend="N225")
    pTest.line(dateDataASX, openDataASX, line_width=2, line_color="orange", legend="ASX")
    pTest.line(dateDataFTSE, openDataFTSE, line_width=2, line_color="purple", legend="FTSE")
    pTest.xaxis.axis_label = "Date"
    pTest.yaxis.axis_label = "Percentage change (%)"
    pTest.legend.location = "top_left"
    pTest.xaxis[0].formatter = DatetimeTickFormatter(formats = dict(hours=["%B %Y"],
                                                                    days=["%B %Y"],
                                                                    months=["%B %Y"],
                                                                    years=["%B %Y"],))        
    script, div = components(pTest)
    return render_template("simpleline.html", script=script, div=div)
    show(pTest)
Exemple #6
0
 def test_zeppelin_with_notebook_handle(self):
     load_zeppelin_args = (Resources(), True, True, 1000, 'zeppelin')
     io.output_notebook(*load_zeppelin_args)
     with pytest.raises(Exception) as ex:
         p = Plot()
         io.show(p, notebook_handle=True)
     assert "Zeppelin doesn't support notebook_handle." == str(ex.value)
def plot_simple_bokeh_line(x,y, filename, height, width, xaxis, yaxis, title):
    output_file(filename)
    p=figure(plot_width=width, plot_height=height,title=title)
    p.line(x,y, color="green")
    p.xaxis.axis_label=xaxis
    p.yaxis.axis_label=yaxis
    show(p)
def correlationsBar():
    # Creates a bar plot showing the fraction of years that correlations have gone
    # below 0.
    # Create a dictionary of the different pairs of stocks for correlations calculations
    combinations = {'SP500-SSEC':[SP500,SSEC],'SP500-N225':[SP500,N225],'SP500-ASX':[SP500,ASX], 
                'SP500-FTSE':[SP500,FTSE],'SSEC-N225':[SSEC,N225],'SSEC-ASX':[SSEC,ASX],
                'SSEC-FTSE':[SSEC,FTSE],'N225-ASX':[N225,ASX],'N225-FTSE':[N225,FTSE],'ASX-FTSE':[ASX,FTSE]}
    
    #Calculate the fraction of years that the correlations were less than 0
    fracNeg =[]
    for x in combinations.keys():
        fracNeg.append(negativeCorrelation(combinations[x][0],combinations[x][1]))
   
    # Add data to dataframe for plotting 
    dictTest = {'values':fracNeg, 'names':combinations.keys()}
    df = pd.DataFrame(dictTest)
    
    #Plots data using Bokeh
    pTest = figure(plot_width=1200, plot_height=700, title="Correlations with S&P500")
    pTest = Bar(df, 'names', values='values', title = "Fraction of years where correlations are below 0",
            xlabel="Indices", ylabel="Fraction of years below 0")
    
    script, div = components(pTest)
    return render_template("simpleline.html", script=script, div=div)
    show(pTest)
Exemple #9
0
def plot_spec_notebook(spec, title=None, xmnx=None, ymnx=None):
    """ Simple spectrum plot in a Notebook

    Parameters
    ----------
    spec : XSpectrum1D
    title : str, optional
    xmnx : list or tuple or ndarray
      xmin, xmax values
    ymnx : list or tuple or ndarray
      ymin, ymax values

    """
    p = figure(plot_width=900, plot_height=500, title=title)
    # Data
    p.line(spec.dispersion.value, spec.flux.value, color='black', line_width=2)
    p.line(spec.dispersion.value, spec.sig, color='red', line_width=0.5)
    # Labels
    p.xaxis.axis_label = "Wavelength"
    p.yaxis.axis_label = "Flux"
    # Axes
    if xmnx is not None:
        p.set(x_range=Range1d(xmnx[0], xmnx[1]))
    if ymnx is not None:
        p.set(y_range=Range1d(ymnx[0], ymnx[1]))
    # Show
    show(p)
def plot_to_bokeh(data_frame, channels_names, desired_col_index=-1):
    '''

    :param data_frame:  pandas dataframe
    :param desired_col_index: -1 for all, i>0 for any other
    :return: non
    '''
    if desired_col_index>=0:
        header_str = data_frame._info_axis.values[desired_col_index]
        col_data = data_frame._series[channels_names[desired_col_index]].values     # returns nd_array
        # data_frame[data_frame._info_axis.values[3]]
        print col_data
        ###################
        output_file("iris.html")

        # Create the figure object
        f = figure()

        # adding glyphs
        f.circle(range(0,len(col_data)), col_data)

        # Save and show the figure
        show(f)

        print f

        ###################
        return col_data
Exemple #11
0
def create_heatmap(station_scores, plot_width=1000, plot_height=600):
    map_options = GMapOptions(lat=32.06, lng=34.87, map_type="roadmap", zoom=9)
    cmap = plt.get_cmap('jet')
    plot = GMapPlot(
        x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="Israel"
    )
    plot.plot_width = plot_width
    plot.plot_height = plot_height
    lat_vec = list(map(lambda x: get_loc_by_id(x).lat, station_scores.keys()))
    lon_vec = list(map(lambda x: get_loc_by_id(x).lon, station_scores.keys()))

    for ind, station in enumerate(station_scores):

        source = ColumnDataSource(
            data=dict(
                lat=[lat_vec[ind]],
                lon=[lon_vec[ind]],
            )
        )
        cmap_indx = int(station_scores[station]*cmap.N)
        cmap_val = tuple(np.floor(255 * np.array(cmap(cmap_indx)[:3])))
        circle = Circle(x="lon", y="lat", size=17, fill_color=cmap_val, fill_alpha=0.95, line_color=None)
        plot.add_glyph(source, circle)

    plot.add_tools(PanTool(), WheelZoomTool())
    output_file("Mean Time to Tel-Aviv Hashalom.html")
    show(plot)
Exemple #12
0
def notebook(*tunnels, mon_local=True, plot_list: Sequence = None):
    """
    Output monitor to a notebook
    This command will block the notebook until interrupted
    :param tunnels: strings
        ssh arguments used for logging into remote machines
        Example:
            "-p 5900 myuser@somehost" -> log in using port 5900 with "mysuser" on "somehost"
        For every ssh string a monitor column will be added to the interface
    :param mon_local: bool
        should the local machine be monitored?
    :param plot_list: Sequence of strings or None
        if not None, it overrides the default plots. use methods names of
        BokehPlots class
    :return: None
    """
    from bokeh.io import show
    execs = make_tunnels(tunnels, mon_local)
    plots = monitors, change_streams = generate_plots(execs)
    show(plots)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(
        *(mon() for mon in monitors),
        *(changes.start() for changes in change_streams)
    ))
Exemple #13
0
def notebook(*tunnels):
    from bokeh.io import show
    execs = dict()
    if tunnels:
        for tunnel in tunnels:
            t_args = re.findall('([\'"]([^"\']+)["\'])|([^ ]+)', tunnel)
            t_args = [a[-1] if a[-1] else a[-1] for a in t_args]
            t_args = [a.strip(' ') for a in t_args]
            execs['_'.join(t_args)] = make_ssh_subprocess(*t_args)
    else:
        execs['localhost'] = async_subprocess, Popen

    _hplots = list()
    monitors = list()
    change_streams = list()
    for ex in execs.values():
        changes = ChangeStream(source_fun=update_notebook_source)
        mon = RessourceMonitor(changes, async_exec=ex[0], normal_exec=ex[1])
        plot_gen = BokehPlots(changes, async_exec=ex[0], normal_exec=ex[1])
        _hplots.append(vplot(plot_gen.cpu_bars(False), plot_gen.gpu_bars(),
                             plot_gen.user_total_memusage()))
        monitors.append(mon)
        change_streams.append(changes)
    plots = hplot(*_hplots)
    show(plots)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(
        *(mon.gpus_mon(loop=loop) for mon in monitors),
        *(mon.cpus_mon() for mon in monitors),
        *(changes.start() for changes in change_streams)
    ))
Exemple #14
0
 def plot_matplobli(self):
     from omicexperiment.plotting.plot_bokeh import plot_interactive
     fig = plot_interactive(self.data_df)
     from bokeh.io import show, output_notebook
     output_notebook()
     show(fig)
     return fig
Exemple #15
0
    def hist_plot(self, bokeh=False):
        """ Simple histogram plot of the PDF

        Parameters
        ----------
        bokeh : bool, optional
          Generate a bokeh plot?

        Returns
        -------

        """
        if not bokeh:
            from matplotlib import pyplot as plt
            # imports
            try:
                import seaborn as sns; sns.set_style("white")
            except:
                pass
            # Giddy up
            plt.clf()
            plt.bar(self.x-self.dx/2., self.pdf, width=self.dx)
            plt.xlabel("x")
            plt.ylabel("PDF(x)")
            plt.show()
            plt.close()
        else:
            from bokeh.io import show
            from bokeh.plotting import figure
            p = figure(plot_width=400, plot_height=400, title='x PDF')
            p.quad(top=self.pdf, bottom=0, left=self.x-self.dx/2.,
                   right=self.x+self.dx/2.)
            p.xaxis.axis_label = 'x'
            # Show
            show(p)
 def make_map(self, map_type, title):
     options = GMapOptions(lat=43.7, lng=-79.4, map_type=map_type, zoom=11)
     plot = GMapPlot(x_range=DataRange1d(),
                     y_range=DataRange1d(),
                     map_options=options,
                     title=title)
     output_file('plot.html')
     show(plot)
Exemple #17
0
 def test_show_with_app(self, mock__run_notebook_hook):
     app = Application()
     io.show(app, notebook_url="baz")
     io._state.notebook_type == "foo"
     self.assertTrue(mock__run_notebook_hook.called)
     self.assertEqual(mock__run_notebook_hook.call_args[0][0], io._state.notebook_type)
     self.assertEqual(mock__run_notebook_hook.call_args[0][1:], ("app", app, io._state, "baz"))
     self.assertEqual(mock__run_notebook_hook.call_args[1], {})
Exemple #18
0
    def plot_cross_variograms(self, iter_plot=200, trace=None, experimental=None):
        """
        Plot the analytical cross-variogram of a given MCMC inference
        Args:
            iter_plot (int): Number of traces to plot
            trace (pymc3.trace): trace with the sill, range and weights of each property
            experimental (bool): if True plot the experimental variogram as well

        Returns:
            None
        """

        if not trace:
            trace = self.trace
        assert trace, 'set the trace to the object'

        n_exp = self.n_exp
        n_gauss = self.n_gauss
        lags = self.lags
        # DEP- n_equations = trace['weights'].shape[1]
        n_iter = trace['weights'].shape[0]
        lags_tiled = np.tile(lags, (iter_plot, 1))
        b_var = []
        for i in range(0, self.n_properties):  # DEP- n_equations, (n_exp+n_gaus)):
            # Init tensor
            b = np.zeros((len(lags), n_iter, 0))
            for i_exp in range(0, n_exp):

                b = np.dstack((b, trace['weights'][:, i_exp + i * (n_exp + n_gauss)] *
                               exp_vario(lags, trace['sill'][:, i_exp], trace['range'][:, i_exp])))
            for i_gauss in range(n_exp, n_gauss + n_exp):
                b = np.dstack((b, trace['weights'][:, i_gauss + i * (n_exp + n_gauss)] *
                               gaus_vario(lags, trace['sill'][:, i_gauss], trace['range'][:, i_gauss])))

            # Sum the contributins of each function
            b_all = b.sum(axis=2)
            # Append each variable
            b_var.append(b_all[:, -iter_plot:].T)

        # Bokeh code to plot this
        p_all = []
        for e, el in enumerate(self.properties):
            p = bp.figure()#x_axis_type="log")
            p.multi_line(list(lags_tiled), list(b_var[e]), color='olive', alpha=0.08)
            if experimental:
                p.scatter(self.lags, y=self.exp_var[el], color='navy', size=2)
            p.title.text = el
            p.xaxis.axis_label = "lags"
            p.yaxis.axis_label = "Semivariance"

            p_all = np.append(p_all, p)

        grid = bl.gridplot(list(p_all), ncols=5, plot_width=250, plot_height=150)

        show(grid)
Exemple #19
0
def plot_im_grid(imarray, dims):
    x, y, z  = dims
    plot_list = []
    for layer, depth in zip(range(imarray.shape[-1]), z):
        p = figure(x_range=[x[0], x[-1]], y_range=[y[0], y[-1]],
                title="Depth %.0f mm"%(depth))
        p.image(image=[np.squeeze(imarray[:,:,layer])], x=[0], y=[0],
                dw=x[-1], dh=y[-1], palette="Greys9")
        plot_list.append(p)
    grid = gridplot([plot_list[:6],plot_list[6:12],plot_list[12:]])
    show(grid)
    return components(grid)
Exemple #20
0
def UpdatePlot(source, source1):
    data_table.source=source1
    plotClusters(source, p)
    #set callbacks
    #sliders[0].callback = cb.callbackMin(source)
    #sliders[1].callback = cb.callbackMax(source)
    #taptool.callback = cb.callbackTap(source)

    curdoc().add(vbox)
    #session = push_session(curdoc())
    #session.show(vbox)
    show(curdoc())
Exemple #21
0
    def plot_cross_covariance(self, nuggets=False, iter_plot=200):
        """
        Plot the cross covariance for the given properties
        Args:
            nuggets (numpy.array): subtracted nuggets
            iter_plot (int): number of traces to plot

        Returns:
            None
        """
        n_exp = self.n_exp
        n_gauss = self.n_gauss
        trace = self.trace
        lags = self.lags

        n_equations = trace['weights'].shape[1]
        n_iter = trace['weights'].shape[0]
        lags_tiled = np.tile(lags, (iter_plot, 1))
        b_var = []
        for i in range(0, self.n_properties):  # n_equations, (n_exp+n_gaus)):
            # Init tensor
            b = np.zeros((len(lags), n_iter, 0))
            for i_exp in range(0, n_exp):
                # print(i_exp, "exp")
                b = np.dstack((b, trace['weights'][:, i_exp + i * (n_exp + n_gauss)] *
                               exp_vario(lags, trace['sill'][:, i_exp], trace['range'][:, i_exp])))
            for i_gaus in range(n_exp, n_gauss + n_exp):
                # print(i_gaus)
                b = np.dstack((b, trace['weights'][:, i_gaus + i * (n_exp + n_gauss)] *
                               gaus_vario(lags, trace['sill'][:, i_gaus], trace['range'][:, i_gaus])))
            # Sum the contributins of each function
            if nuggets:
                b_all = 1 - (b.sum(axis=2) + self.nuggets[i])
            else:
                b_all = 1 - (b.sum(axis=2))
            # Append each variable
            b_var.append(b_all[:, -iter_plot:].T)

        p_all = []
        for e, el in enumerate(self.properties):
            p = bp.figure(x_axis_type="log")
            p.multi_line(list(lags_tiled), list(b_var[e]), color='olive', alpha=0.08)

            p.title.text = el
            p.xaxis.axis_label = "lags"
            p.yaxis.axis_label = "Semivariance"

            p_all = np.append(p_all, p)

        grid = bl.gridplot(list(p_all), ncols=5, plot_width=250, plot_height=150)

        show(grid)
def box_plot_sim_game(df_results_team):
    # values to represent
    # score, two_pt_shots_attempt/made, three_pt_shots_made/attempts, off/def rebounds

    rel_col = [
        'PTS', 'FGA', 'FGM', 'FG3A', 'FG3M',
        'OREB', 'DREB', 'STL', 'BLK', 'TO', 'PASS'
    ]

    # get quartile info
    # q4=min, q5=max
    q1, q2, q3, q4, q5 = {}, {}, {}, {}, {}

    for col in rel_col:
        q1[col] = df_results_team[col].quantile(q=0.25)
        q2[col] = df_results_team[col].quantile(q=0.50)
        q3[col] = df_results_team[col].quantile(q=0.75)
        q4[col] = df_results_team[col].quantile(q=0.00)
        q5[col] = df_results_team[col].quantile(q=1.00)

    df = pd.DataFrame([q1, q2, q3, q4, q5]).T
    df.columns = ['q{}'.format(i) for i, col in enumerate(df, 1)]

    iqr = df.q3 - df.q1
    upper = df.q3 + 1.5 * iqr
    lower = df.q1 - 1.5 * iqr

    new_upper = [min([x, y]) for (x, y) in zip(df.q5.values, upper.values)]
    new_lower = [max([x, y]) for (x, y) in zip(df.q4.values, lower.values)]

    p = figure(tools="save", background_fill_color="#EFE8E2", title="", x_range=rel_col)
    # stems
    p.segment(rel_col, new_upper, rel_col, df.q3.values, line_color="black")
    p.segment(rel_col, new_lower, rel_col, df.q1.values, line_color="black")

    # boxes
    p.vbar(rel_col, 0.7, df.q2.values, df.q3.values, fill_color='#FF1493', line_color="black")
    p.vbar(rel_col, 0.7, df.q1.values, df.q2.values, fill_color='#1E90FF', line_color="black")

    # whiskers (almost-0 height rects simpler than segments)
    p.rect(rel_col, new_lower, 0.2, 0.01, line_color="black")
    p.rect(rel_col, new_upper, 0.2, 0.01, line_color="black")

    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = "white"
    p.grid.grid_line_width = 2
    p.xaxis.major_label_text_font_size = "12pt"

    output_file("box.html")

    show(p)
 def plotStockData(self, percentage='n'):
     # calls readDatabase, then uses pylab to plot the stock data from initialDate
     # to finalDate. Defaults are minDate and maxDate.
     #Read in stock data
     
     dateData, openData = self.convertPlotData(percentage='n')
     
     #Plots data using Bokeh
     pTest = figure(plot_width=500, plot_height=500, title="Stock Indices")
     pTest.line(dateData, openData, line_width=2)
     pTest.xaxis.axis_label = "Date"
     pTest.yaxis.axis_label = "Index Level"
     show(pTest) # show the results 
     return pTest
Exemple #24
0
def main():

    # Create Plot
    plot = create_plot()

    # Load Asset Glyphs
    with open('asset_data.json', 'r') as f:
        asset_json = json.loads(f.read())
    for asset in asset_json['assets']:
        plot_asset(plot, asset)

    # Display Plot
    output_file("county_map.html")
    show(plot)
Exemple #25
0
    def func(self, args):
        applications = self.build_applications(args)

        for (route, app) in applications.items():
            doc = app.create_document()
            if route == "/":
                filename = "index.html"
            else:
                filename = route[1:] + ".html"

            output_file(filename)

            if args.show:
                show(doc, new='tab')
            else:
                save(doc)
Exemple #26
0
 def start(self):
     c = self.last_report()
     b = [i for sub in c for i in sub]
     graph = vform(*b)
     s = '../Report' + '/' + 'report_%s.html' % self.build[0].replace('.', '_')
     output_file(s, title=self.build[0] + '-' + self.devicename[0] + 'Report')
     return show(graph)
def BernGrid(Theta,pTheta,Data):
    '''
    Theta is vector of values between 0 and 1.
    pTheta is prior probability mass at each value of Theta
    Data is vector of 0's and 1's.
    '''
    if np.any((Theta < 0)|(Theta > 1 )):
        raise ValueError("Theta values must be between 0 and 1")
    if np.any(pTheta < 0):
        raise ValueError("pTheta values must be non-negative")
    if not(math.isclose(math.fsum(pTheta),1)):
        raise ValueError("pTheta values must sum to 1.0")
    if not(np.all((Data == 0) | (Data == 1))):
        raise ValueError("Data values must be 0 or 1")
    z = np.sum(Data) # No of heads
    N = len(Data)
    # Compute the Bernoulli likelihood at each value of Theta:
    Likelihood = np.multiply(Theta**z,(1-Theta)**(N-z))

    ## calculate the Posterior
    p_Data= np.dot(np.multiply(Theta**z,(1-Theta)**(N-z)),pTheta)
    Posterior = (Likelihood * pTheta)/p_Data
    ## plot the Prior
    plot_prior = figure(plot_width=800, plot_height=250, title='Prior')
    plot_prior.x_range = Range1d(0,1)
    plot_prior.y_range = Range1d(0, max(np.append(pTheta,Posterior)))
    plot_prior.xaxis.axis_label = 'Θ'
    plot_prior.yaxis.axis_label = 'p(Θ)'
    plot_prior.vbar(x=Theta, width=0.001, bottom=0,top=pTheta)

    ## Plot the likelihood
    plot_likelihood = figure(plot_width=800, plot_height=250, title='Likelihood')
    plot_likelihood.x_range = Range1d(0, 1)
    plot_likelihood.y_range = Range1d(0, 1.1*max(Likelihood))
    plot_likelihood.xaxis.axis_label = 'Θ'
    plot_likelihood.yaxis.axis_label = 'p(D|Θ)'
    plot_likelihood.vbar(x=Theta, width=0.001, bottom=0,top=Likelihood)

    ## Plot the Posterior
    plot_posterior = figure(plot_width=800, plot_height=250, title='Posterior')
    plot_posterior.x_range = Range1d(0,1)
    plot_posterior.y_range = Range1d(0, max(np.append(pTheta,Posterior)))
    plot_posterior.xaxis.axis_label = 'Θ'
    plot_posterior.yaxis.axis_label = 'p(Θ|D)'
    plot_posterior.vbar(x=Theta, width=0.001, bottom=0,top=Posterior)

    show(column(plot_prior,plot_likelihood,plot_posterior))
def bar_chart(d, x, show=True, **kwargs):
    """Displays a bar chart for the occurrence of the given x-value.
    This plot type is especially useful for plotting the occurrence of categorical data,
    where only a small number (<= 10) of different values are present.
    This function is directly calling the advanced bokeh bar chart type,
    therefore no additional class is used.
    Useful kwargs include: title, plot_height, plot_width."""
    title = kwargs.pop("title", "Occurrence of {}".format(x))
    p = Bar(d, x, values=x, agg="count", legend=False, title=title, **kwargs)
    p.yaxis.axis_label = "Occurrence"
    p.axis.axis_label_text_font_size = "14pt"
    p.axis.major_label_text_font_size = "14pt"
    p.title.text_font_size = "18pt"
    if show:
        io.show(p)
    else:
        return p
def get_trains_week(stat_code): 
    sbn.set_style("white")
    stat_vals = dis_trains[dis_trains.code == stat_code]
    all_trains = stat_vals.times.values
    xx = all_trains
    days = np.array(xx[0])/1440
    tot_mins = np.array(xx[0])%1440
    hour = tot_mins/60
    mins = tot_mins % 60
    train_time = zip(days,hour,mins)
    hist, edges = np.histogram(xx[0], bins = range(0,10081,120))    
    d = np.sin(3*gradient)
    fig.image(image = [d],x = 0, y = 0, dw = 10080, dh = max(hist)+1)
    fig.quad(top=hist, bottom=0, left=edges[:-1],right=edges[1:],fill_color="#036564",line_color="#033649")
    fig.xaxis[0].ticker=FixedTicker(ticks=[])
    fig.xaxis.major_label_orientation = "vertical"
#    output_file("test_bg_image.html", title = "Background image")
    show(fig)
Exemple #30
0
def test_inline_extension():
    from bokeh.io import show
    from bokeh.models import TickFormatter
    from bokeh.plotting import figure
    from bokeh.util.compiler import TypeScript

    TS_CODE = """
    import {TickFormatter} from "models/formatters/tick_formatter"

    export class TestFormatter extends TickFormatter {

      doFormat(ticks: number[]): string[] {
        if (ticks.length == 0)
          return[]
        else {
          const formatted = [`${ticks[0]}`]
          for (let i = 1; i < ticks.length; i++) {
            const difference = (ticks[i] - ticks[0]).toPrecision(2)
            formatted.push(`+${difference}}`)
          }
          return formatted
        }
      }

      static initClass(): void {
        this.prototype.type = "TestFormatter"
      }
    }
    TestFormatter.initClass()
    """

    class TestFormatter(TickFormatter):

        __implementation__ = TypeScript(TS_CODE)

    class TestFormatter2(TickFormatter):

        __implementation__ = TypeScript("^") # invalid syntax on purpose

    p = figure()
    p.circle([1, 2, 3, 4, 6], [5, 7, 3, 2, 4])
    p.xaxis.formatter = TestFormatter()
    show(p)
Exemple #31
0
def show_skyview_widget(tpf,
                        notebook_url='localhost:8888',
                        magnitude_limit=18):
    """skyview

    Parameters
    ----------
    tpf : lightkurve.TargetPixelFile
        Target Pixel File to interact with
    notebook_url: str
        Location of the Jupyter notebook page (default: "localhost:8888")
        When showing Bokeh applications, the Bokeh server must be
        explicitly configured to allow connections originating from
        different URLs. This parameter defaults to the standard notebook
        host and port. If you are running on a different location, you
        will need to supply this value for the application to display
        properly. If no protocol is supplied in the URL, e.g. if it is
        of the form "localhost:8888", then "http" will be used.
    magnitude_limit : float
        A value to limit the results in based on Gaia Gmag. Default, 18.
    """
    try:
        import bokeh
        if bokeh.__version__[0] == '0':
            warnings.warn("interact_sky() requires Bokeh version 1.0 or later",
                          LightkurveWarning)
    except ImportError:
        log.error(
            "The interact_sky() tool requires the `bokeh` Python package; "
            "you can install bokeh using e.g. `conda install bokeh`.")
        return None

    # Try to identify the "fiducial frame", for which the TPF WCS is exact
    zp = (tpf.pos_corr1 == 0) & (tpf.pos_corr2 == 0)
    zp_loc, = np.where(zp)

    if len(zp_loc) == 1:
        fiducial_frame = zp_loc[0]
    else:
        fiducial_frame = 0

    def create_interact_ui(doc):
        # The data source includes metadata for hover-over tooltips
        tpf_source = None

        # Create the TPF figure and its stretch slider
        pedestal = np.nanmin(tpf.flux)
        fig_tpf, stretch_slider = make_tpf_figure_elements(
            tpf,
            tpf_source,
            pedestal=pedestal,
            fiducial_frame=fiducial_frame,
            plot_width=640,
            plot_height=600)
        fig_tpf, r = add_gaia_figure_elements(tpf,
                                              fig_tpf,
                                              magnitude_limit=magnitude_limit)

        # Optionally override the default title
        if tpf.mission == 'K2':
            fig_tpf.title.text = "Skyview for EPIC {}, K2 Campaign {}, CCD {}.{}".format(
                tpf.targetid, tpf.campaign, tpf.module, tpf.output)
        elif tpf.mission == 'Kepler':
            fig_tpf.title.text = "Skyview for KIC {}, Kepler Quarter {}, CCD {}.{}".format(
                tpf.targetid, tpf.quarter, tpf.module, tpf.output)
        elif tpf.mission == 'TESS':
            fig_tpf.title.text = 'Skyview for TESS {} Sector {}, Camera {}.{}'.format(
                tpf.targetid, tpf.sector, tpf.camera, tpf.ccd)

        # Layout all of the plots
        widgets_and_figures = layout([fig_tpf, stretch_slider])
        doc.add_root(widgets_and_figures)

    output_notebook(verbose=False, hide_banner=True)
    return show(create_interact_ui, notebook_url=notebook_url)
Exemple #32
0
def plot_close(d):

    ## Hovertool does so that when your mouse 'hovers' over the graph price and date is shown
    hover = HoverTool(tooltips=[('Price','@Adj_Close{0,0.0}'),('Volume','@Volume{0,0.}'),('Date','@Date{%F}')] ,formatters = {'Date':'datetime'})
    #  $y{0,0.0} is formatiing, "0," defines value y with comma (like 1000 is 1,000) and "0.0" is one decimal
    #  @x{%F} defines value x and use format option, fomatters then define that we use datetime format, 
    # since the x-value is the date.


    ## tools allows you to pan around, zoom in (you have to choose the boxzoom option in the graph then 
    # 'mark' area you wish to view) 
    ## reset to original position (there is no zoom in, besides this option),
    # and save a the graph as a picture
    tools="pan,box_zoom,reset,save"

    # Make a list of companys we have data for
    stock_list = list(d.columns.levels[0])
    # Choose our inital stock
    stock = list(d.columns.levels[0])[0]

    # This line creates a source for bokeh plotting with our chosen stock 
    stocksource = ColumnDataSource(d[stock])
    
    # We initialize our figure with titles, labels and specify that we want to use our tools mentioned above
    p = figure(x_axis_type='datetime',title=f'Closing price of {stock}', \
        tools=[hover,tools], y_axis_label='Closing price', x_axis_label='Date')

    # Plot a line with the adjusted close plices, we reference our stocksource, that contains data for our choosen stock
    p.line(x='Date', y='Adj_Close', source=stocksource, color = 'blue', legend= 'Closing price')

    # We locate the legend in the top left, stocks mostly go from bottom left corner to top right corner
    # so we figured this was a good location
    p.legend.location = "top_left"

    # visuals 
    p.ygrid.minor_grid_line_color = 'navy'
    p.ygrid.minor_grid_line_alpha = 0.1
    # formatting y-axis:
    p.yaxis.formatter=NumeralTickFormatter(format='0,0')

    # Defines a function that updates the plot when a different stock is chosen
    def update_name(stock):
        p.title.text = f'Closing price of {stock}'
        # Updates the data
        stocksource.data = ColumnDataSource(d[str(stock)]).data
        # I can't for the life of my explain why .data needs to there on both side of the equal sign
        # both they do

        # push_notebook is af bokeh->jupyter-specific comand to tell python to update the bokeh plot in jupyter
        push_notebook()
    
    # show the plot, notebook_handle is again bokeh->jupyter-specific to show the plot in the notebook
    show(p,notebook_handle=True)

    # Make a dropdown-widget, so the user can choose different stocks, the layout option, makes the options box wider
    # the style options make the desciption box wide enough for the description string to be read fully
    drop_down = widgets.Dropdown(options=stock_list, layout = {'width':'50%'},\
        description='Choose a stock or index:',style = {'description_width': 'initial'})

    # Call the function 
    interact(update_name, stock = drop_down)
Exemple #33
0
pv_share = len(pv) / len(firms_match)
shares = [both_share, parser_share, pv_share]
x = [1, 2, 3]
ticks = {1: "both", 2: "Parser", 3: "Patentsview"}

#* PLOT
plot = figure(plot_width=500,
              plot_height=500,
              title="Share of firm matches; total number of firms: 742518",
              x_axis_label="Datasource",
              y_axis_label="Percentage")
plot.vbar(x=x, top=shares, width=0.9)
plot.xaxis.ticker = list(ticks.keys())
plot.xaxis.major_label_overrides = ticks
plot.xaxis.major_label_orientation = 0.8
show(plot)
export_png(plot, filename="output/tmp/match_pv.png")

#* HOW MANY OF MISSINGS IN PARSER ARE MATCHED NOW
pv_pats = pv[["patent_id", "organization"]]
pv_pats = pv_pats.drop_duplicates(subset=["patent_id"], keep="first")
dst_missings = pat_3[["pat"]]
match_missings = dst_missings.merge(pv_pats,
                                    left_on="pat",
                                    right_on="patent_id",
                                    how="outer",
                                    indicator=True)
"""
Only 474 patents added, strongly suggesting that the missing citations
are indeed data from other patent systems or non-patent citations.
"""
Exemple #34
0
def _display_timeline_dict(data: dict,
                           **kwargs) -> figure:  # noqa: C901, MC0001
    """
    Display a timeline of events.

    Parameters
    ----------
    data : dict
        Data points to plot on the timeline.
            Need to contain:
                Key - Name of data type to be displayed in legend
                Value - dict of data containing:
                    data : pd.DataFrame
                        Data to plot
                    time_column : str
                        Name of the timestamp column
                    source_columns : list
                        List of source columns to use in tooltips
                    color: str
                        Color of datapoints for this data
    Other Parameters
    ----------------
    ref_time : datetime, optional
        Input reference line to display (the default is None)
    title : str, optional
        Title to display (the default is None)
    time_column : str, optional
        Name of the timestamp column
        (the default is 'TimeGenerated')
    legend: str, optional
        Where to position the legend
        None, left, right or inline (default is None)
    yaxis : bool, optional
        Whether to show the yaxis and labels
    range_tool : bool, optional
        Show the the range slider tool (default is True)
    source_columns : list, optional
        List of default source columns to use in tooltips
        (the default is None)
    height : int, optional
        The height of the plot figure
        (the default is auto-calculated height)
    width : int, optional
        The width of the plot figure (the default is 900)

    Returns
    -------
    figure
        The bokeh plot figure.

    """
    reset_output()
    output_notebook()

    height: int = kwargs.pop("height", None)
    width: int = kwargs.pop("width", 900)
    ref_time: Any = kwargs.pop("ref_time", None)
    ref_label: str = kwargs.pop("ref_label", None)
    title: str = kwargs.pop("title", None)
    legend_pos: str = kwargs.pop("legend", None)
    show_yaxis: bool = kwargs.pop("yaxis", False)
    show_range: bool = kwargs.pop("range_tool", True)
    xgrid: bool = kwargs.pop("xgrid", True)
    ygrid: bool = kwargs.pop("ygrid", False)

    tool_tip_columns, min_time, max_time = _unpack_data_series_dict(
        data, **kwargs)
    series_count = len(data)

    hover = HoverTool(
        tooltips=_create_tool_tips(data, tool_tip_columns),
        formatters={"Tooltip": "printf"},
    )

    title = f"Timeline: {title}" if title else "Event Timeline"
    start_range = min_time - ((max_time - min_time) * 0.1)
    end_range = max_time + ((max_time - min_time) * 0.1)
    height = height if height else _calc_auto_plot_height(len(data))
    y_range = ((-1 / series_count), series_count - 1 + (1 / series_count))
    plot = figure(
        x_range=(start_range, end_range),
        y_range=y_range,
        min_border_left=50,
        plot_height=height,
        plot_width=width,
        x_axis_label="Event Time",
        x_axis_type="datetime",
        x_minor_ticks=10,
        tools=[hover, "xwheel_zoom", "box_zoom", "reset", "save", "xpan"],
        title=title,
    )
    plot.yaxis.visible = show_yaxis
    if show_yaxis:
        if data:
            y_labels = {
                ser_def["y_index"]: str(lbl)
                for lbl, ser_def in data.items()
            }
            plot.yaxis.major_label_overrides = y_labels
    if ygrid:
        plot.ygrid.minor_grid_line_color = "navy"
        plot.ygrid.minor_grid_line_alpha = 0.1
        plot.ygrid.grid_line_color = "navy"
        plot.ygrid.grid_line_alpha = 0.3
    else:
        plot.ygrid.grid_line_color = None
    if xgrid:
        plot.xgrid.minor_grid_line_color = "navy"
        plot.xgrid.minor_grid_line_alpha = 0.3
    else:
        plot.xgrid.grid_line_color = None

    # Create plot bar to act as as range selector
    rng_select = _create_range_tool(
        data=data,
        min_time=min_time,
        max_time=max_time,
        plot_range=plot.x_range,
        width=width,
        height=height,
    )

    # set the tick datetime formatter
    plot.xaxis[0].formatter = _get_tick_formatter()

    if series_count > 1 and not legend_pos:
        legend_pos = "left"

    # plot groups individually so that we can create an interactive legend
    # if legend_pos is "inline", we add add the normal legend inside the plot
    # if legend_pos is "left" or "right", we add the legend to the side
    legend_items = []
    for ser_name, series_def in data.items():
        if legend_pos == "inline":
            p_series = plot.diamond(
                x=series_def["time_column"],
                y="y_index",
                color=series_def["color"],
                alpha=0.5,
                size=10,
                source=series_def["source"],
                legend_label=str(ser_name),
            )
        else:
            p_series = plot.diamond(
                x=series_def["time_column"],
                y="y_index",
                color=series_def["color"],
                alpha=0.5,
                size=10,
                source=series_def["source"],
            )
        if legend_pos in ["left", "right"]:
            legend_items.append((str(ser_name), [p_series]))

    if legend_pos == "inline":
        # Position the inline legend
        plot.legend.location = "center_left"
        plot.legend.click_policy = "hide"
    elif legend_pos in ["left", "right"]:
        # Create the legend box outside of the plot area
        ext_legend = Legend(
            items=legend_items,
            location="center",
            click_policy="hide",
            label_text_font_size="8pt",
        )
        plot.add_layout(ext_legend, legend_pos)

    if ref_time is not None:
        _add_ref_line(plot, ref_time, ref_label, len(data))

    if show_range:
        show(column(plot, rng_select))
    else:
        show(plot)
    return plot
Exemple #35
0
                    style="float: left; margin: 0px 15px 15px 0px;"
                    border="2"
                ></img>
            </div>
            <div>
                <span style="font-size: 15px; font-weight: bold;">@species</span>
            </div>
            <div>
                <span style="font-size: 10px; color: #696;">Petal length: @petal_length</span><br>
                <span style="font-size: 10px; color: #696;">Petal width: @petal_width</span>
            </div>
        </div>
""")

f.add_tools(hover)
f.toolbar_location="above"
f.toolbar.logo=None

#Style the legend
f.legend.location = (575,555)
f.legend.location = 'top_left'
f.legend.background_fill_alpha = 0
f.legend.border_line_color = None
f.legend.margin = 10
f.legend.padding = 18
f.legend.label_text_color = 'olive'
f.legend.label_text_font = 'times'

#Save and show the figure
show(f)
Exemple #36
0
           tooltips=[('date', '@Month @Year'), ('rate', '@rate%')])

p.grid.grid_line_color = None
p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.major_label_text_font_size = "5pt"
p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = pi / 3

p.rect(x="Year",
       y="Month",
       width=1,
       height=1,
       source=df,
       fill_color={
           'field': 'rate',
           'transform': mapper
       },
       line_color=None)

color_bar = ColorBar(color_mapper=mapper,
                     major_label_text_font_size="5pt",
                     ticker=BasicTicker(desired_num_ticks=len(colors)),
                     formatter=PrintfTickFormatter(format="%d%%"),
                     label_standoff=6,
                     border_line_color=None,
                     location=(0, 0))
p.add_layout(color_bar, 'right')

show(p)  # show the plot
Exemple #37
0
def show_radar(dataframe):
    """Visualize lipid-protein contacts using a Bokeh radar map.

    This is useful if you want to (i) compare the binding profile of two residues and
    (ii) when you want to see how different contact metrics compare against each other.

    Parameters
    ----------

    dataframe : pd.DataFrame
         A contacts dataframe. This will be the output of pl.contacts_dataframe() command.


    """

    output_notebook()

    def radarApp(doc):

        df = dataframe
        gpcrs = list(df.Protein.unique())
        lipids = list(df.Lipids.unique())
        radius = list(df.Radius.unique())
        radius = [str(r) for r in radius]

        # Normalize [0-1] all contact parameters with respect to each other.
        for cmn in list(df.columns)[:-5]:
            for lipid in lipids:
                for radius_value in radius:
                    radius_value = float(radius_value)

                    dfmin = df[(df.Lipids == lipid)
                               & (df.Radius == radius_value)][cmn].min()

                    dfmax = df[(df.Lipids == lipid)
                               & (df.Radius == radius_value)][cmn].max()

                    lip_index = list(df[(df.Lipids == lipid)
                                        & (df.Radius == radius_value)].index)

                    df.loc[lip_index, cmn] = df[(df.Lipids == lipid) & (
                        df.Radius == radius_value)][cmn].apply(
                            lambda x: (x - dfmin) / (dfmax - dfmin))

        df = df.fillna(0)

        # 1 unique set of residues - works also if there's only 1 set available.
        resname = df[(df.Protein == gpcrs[0]) & (df.Lipids == lipids[0]) &
                     (df.Radius == float(radius[0]))].ResName.to_list()
        resid = df[(df.Protein == gpcrs[0]) & (df.Lipids == lipids[0]) &
                   (df.Radius == float(radius[0]))].ResID.to_list()

        residues = []
        for rn, ri in zip(resname, resid):
            residues.append("{}-{}".format(rn, ri))

        import random
        # Create Input controls
        gpcr1 = Select(title="Protein",
                       value=gpcrs[0],
                       options=gpcrs,
                       width=100)
        gpcr2 = Select(title="Protein",
                       value=gpcrs[0],
                       options=gpcrs,
                       width=100)
        lipid1 = Select(title="Lipid",
                        value=lipids[0],
                        options=lipids,
                        width=100)
        lipid2 = Select(title="Lipid",
                        value=lipids[0],
                        options=lipids,
                        width=100)
        residue1 = Select(title="Residue",
                          value=random.choice(residues),
                          options=residues,
                          width=120)
        residue2 = Select(title="Residue",
                          value=random.choice(residues),
                          options=residues,
                          width=120)
        radius1 = Select(title="Radius",
                         value=radius[0],
                         options=radius,
                         width=100)
        radius2 = Select(title="Radius",
                         value=radius[0],
                         options=radius,
                         width=100)

        # num_vars = 6
        num_vars = len(list(df.columns)[:-5])
        centre = 0.5

        theta = np.linspace(0, 2 * np.pi, num_vars, endpoint=False)
        theta += np.pi / 2

        verts = unit_poly_verts(theta, centre)
        xv = [v[0] for v in verts]
        yv = [v[1] for v in verts]

        f1 = df[(df.Protein == str(gpcr1.value))
                & (df.Lipids == str(lipid1.value)) &
                (df.ResID == int(str(residue1.value).split("-")[1])) &
                (df.Radius == float(radius1.value)
                 )].loc[:, list(df.columns)[:num_vars]].to_numpy().reshape(
                     num_vars, )

        f2 = df[(df.Protein == str(gpcr2.value))
                & (df.Lipids == str(lipid2.value)) &
                (df.ResID == int(str(residue2.value).split("-")[1])) &
                (df.Radius == float(radius2.value)
                 )].loc[:, list(df.columns)[:num_vars]].to_numpy().reshape(
                     num_vars, )

        flist = [f1, f2]

        p = figure(plot_height=400,
                   plot_width=800,
                   x_range=(-0.3, 1.3),
                   y_range=(-0.3, 1.3),
                   tools="")
        cmap = RdBu[num_vars]
        colors = cmap[:1] + cmap[-1:]

        patch1 = ColumnDataSource(data=dict(xi=[], yi=[]))
        circle1 = ColumnDataSource(data=dict(xt=[], yt=[]))
        xt, yt = radar_patch(f1, theta, centre)
        xi, yi = star_curv(xt + xt[:1], yt + yt[:1])
        patch = p.patch(x="xi",
                        y="yi",
                        fill_alpha=0.15,
                        fill_color=colors[0],
                        line_color=colors[0],
                        source=patch1)
        circle = p.circle(x='xt',
                          y='yt',
                          size=10,
                          alpha=0.5,
                          line_color=colors[0],
                          fill_color=colors[0],
                          source=circle1)

        patch2 = ColumnDataSource(data=dict(xi=[], yi=[]))
        circle2 = ColumnDataSource(data=dict(xt=[], yt=[]))
        xt, yt = radar_patch(f2, theta, centre)
        xi, yi = star_curv(xt + xt[:1], yt + yt[:1])
        patch = p.patch(x="xi",
                        y="yi",
                        fill_alpha=0.15,
                        fill_color=colors[1],
                        line_color=colors[1],
                        source=patch2)
        circle = p.circle(x='xt',
                          y='yt',
                          size=10,
                          alpha=0.5,
                          line_color=colors[1],
                          fill_color=colors[1],
                          source=circle2)

        # Draw grid so the plot looks like a polar graph.
        text_label = list(df.columns)[:num_vars] + ['']
        p.circle(x=0.5,
                 y=0.5,
                 size=20,
                 fill_alpha=0,
                 line_color='black',
                 line_dash='dashed',
                 line_alpha=0.2)
        for size in [x * 100 for x in range(1, 10)]:
            p.circle(x=0.5,
                     y=0.5,
                     size=size,
                     fill_alpha=0,
                     line_color='black',
                     line_dash='dashed',
                     line_alpha=0.2)

        line = np.linspace(-2, 2, 100)
        p.line(line, (line * 0.58) + 0.21,
               line_color='black',
               line_dash='dashed',
               line_alpha=0.2)
        p.line(line, (line * (-0.58)) + 0.79,
               line_color='black',
               line_dash='dashed',
               line_alpha=0.2)
        p.line([0.5] * 100,
               line,
               line_color='black',
               line_dash='dashed',
               line_alpha=0.2)

        # Hide axes.
        p.xgrid.grid_line_color = None
        p.ygrid.grid_line_color = None
        p.xaxis.major_tick_line_color = None
        p.xaxis.minor_tick_line_color = None
        p.yaxis.major_tick_line_color = None
        p.yaxis.minor_tick_line_color = None
        p.xaxis.major_label_text_font_size = '0pt'
        p.yaxis.major_label_text_font_size = '0pt'

        p.axis.visible = None
        p.toolbar.logo = None
        p.toolbar_location = None

        # Draw the hexagon with labels attached.
        p.line(x=xv + [centre], y=yv + [1], color='black')

        xv[1] = xv[1] - 0.13
        xv[2] = xv[2] - 0.1
        xv[-2] = xv[-2] + 0.16
        xv[-1] = xv[-1] + 0.1
        # yv[3] = yv[3] - 0.06

        label_source = ColumnDataSource({
            'x': xv + [centre],
            'y': yv + [1],
            'text': text_label
        })
        labels = LabelSet(x="x",
                          y="y",
                          text="text",
                          source=label_source,
                          level='glyph',
                          text_align="center")
        p.add_layout(labels)

        def select_dfGPCR():
            gpcr1_val, gpcr2_val = gpcr1.value, gpcr2.value
            lipid1_val, lipid2_val = lipid1.value, lipid2.value
            res1_val, res2_val = str(residue1.value).split("-")[1], str(
                residue2.value).split("-")[1]

            f1 = df[(df.Protein == str(gpcr1_val))
                    & (df.Lipids == str(lipid1_val)) &
                    (df.ResID == int(res1_val)) &
                    (df.Radius == float(radius1.value)
                     )].loc[:, list(df.columns)[:num_vars]].to_numpy().reshape(
                         num_vars, )
            f2 = df[(df.Protein == str(gpcr2_val))
                    & (df.Lipids == str(lipid2_val)) &
                    (df.ResID == int(res2_val)) &
                    (df.Radius == float(radius2.value)
                     )].loc[:, list(df.columns)[:num_vars]].to_numpy().reshape(
                         num_vars, )

            return (f1, f2)

        def update1():
            gpcr_val = gpcr1.value
            lipid1_val = lipid1.value
            radius1_val = radius1.value

            resname = df[(df.Protein == str(gpcr_val))
                         & (df.Lipids == str(lipid1_val)) &
                         (df.Radius == float(radius1_val))].ResName.to_list()
            resid = df[(df.Protein == str(gpcr_val))
                       & (df.Lipids == str(lipid1_val)) &
                       (df.Radius == float(radius1_val))].ResID.to_list()

            residues = []
            for rn, ri in zip(resname, resid):
                residues.append("{}-{}".format(rn, ri))

            residue1.options = residues
            if residue1.value not in residues:
                residue1.value = residues[0]

            f1 = select_dfGPCR()[0]
            xt, yt = radar_patch(f1, theta, centre)
            xi, yi = star_curv(xt + xt[:1], yt + yt[:1])

            circle1.data = dict(xt=xt, yt=yt)
            patch1.data = dict(xi=xi, yi=yi)

        def update2():
            gpcr_val = gpcr1.value
            lipid2_val = lipid2.value
            radius2_val = radius2.value

            resname = df[(df.Protein == str(gpcr_val))
                         & (df.Lipids == str(lipid2_val)) &
                         (df.Radius == float(radius2_val))].ResName.to_list()
            resid = df[(df.Protein == str(gpcr_val))
                       & (df.Lipids == str(lipid2_val)) &
                       (df.Radius == float(radius2_val))].ResID.to_list()

            residues = []
            for rn, ri in zip(resname, resid):
                residues.append("{}-{}".format(rn, ri))

            # options = [str(x) for x in options]
            residue2.options = residues
            if residue2.value not in residues:
                residue2.value = residues[0]

            f2 = select_dfGPCR()[1]
            xt, yt = radar_patch(f2, theta, centre)
            xi, yi = star_curv(xt + xt[:1], yt + yt[:1])

            circle2.data = dict(xt=xt, yt=yt)
            patch2.data = dict(xi=xi, yi=yi)

        controls1 = [gpcr1, lipid1, residue1, radius1]
        controls2 = [gpcr2, lipid2, residue2, radius2]

        for control1 in controls1:
            control1.on_change('value', lambda attr, old, new: update1())
        for control2 in controls2:
            control2.on_change('value', lambda attr, old, new: update2())

        inputs1 = column([gpcr1, lipid1, residue1, radius1])
        inputs2 = column([gpcr2, lipid2, residue2, radius2])

        l = layout([[inputs1, p, inputs2]])

        update1()
        update2()

        doc.add_root(l)

        doc.title = "Radar App"
        doc.theme = Theme(json=yaml.load("""
            attrs:
                Figure:
                    toolbar_location: above
                    height: 500
                    width: 800
                Grid:
                    grid_line_dash: [6, 4]
                    grid_line_color: black
        """,
                                         Loader=yaml.FullLoader))

    return show(radarApp)
Exemple #38
0
def CNV_Map(df,
            sample_order=[],
            title="CN heatmaps sorted by SMAD4 loss, pointing VPS4B",
            width=900,
            height=400,
            standoff=10,
            y_label='',
            marks=[]):
    """
    create an interactive plot suited for visualizing segment level CN data for a set of samples using bokeh

    args:
    ----
      df: df['Sample' 'Start' 'End' 'Segment_Mean' 'size'] the df containing segment level
        copy number (can be subsetted to a specific region or genome-wide)
      sampleorder: list[Sample] <- for all samples present in the df
      title: plot title
      width: int width
      height: int height
      standoff: the space between the plot and the x axis
      y_label: the y axis label
      marks: location of lines at specific loci

    Returns:
    --------
      The bokeh object
    """
    colors = [
        "#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce", "#ddb7b1",
        "#cc7878", "#933b41", "#550b1d"
    ]
    colors = RdBu[8]
    mapper = LinearColorMapper(palette=colors,
                               low=df.Segment_Mean.min(),
                               high=df.Segment_Mean.max())
    if len(sample_order) == 0:
        sample_order = list(set(df.Sample.tolist()))
    TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
    p = figure(title=title,
               y_range=(df.End.max(), df.Start.min()),
               x_range=sample_order,
               x_axis_location="above",
               plot_width=width,
               plot_height=height,
               tools=TOOLS,
               toolbar_location='below',
               tooltips=[('pos', '@Start, @End'), ('relative CN', '@Sample')])

    p.grid.grid_line_color = None
    p.axis.axis_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.major_label_text_font_size = "5pt"
    p.axis.major_label_standoff = standoff
    p.xaxis.major_label_orientation = pi / 3
    pos = 0
    # for i,val in enumerate(historder):
    #    p.rect(x=pos,y=-7,width=len(orderbyhist[val]), height=10, fill_color=small_palettes['Viridis'][4][i])
    #    p.text(x=pos+len(orderbyhist[val])/2, y=-9, text=str(val), text_color="#96deb3")
    #    pos += len(orderbyhist[val])

    p.rect(x="Sample",
           y="Start",
           width=0.9,
           height="size",
           source=df.reset_index(drop=True),
           fill_color={
               'field': 'Segment_Mean',
               'transform': mapper
           },
           line_color=None)

    color_bar = ColorBar(color_mapper=mapper,
                         major_label_text_font_size="5pt",
                         ticker=BasicTicker(desired_num_ticks=len(colors)),
                         formatter=PrintfTickFormatter(format="%.2f"),
                         label_standoff=6,
                         border_line_color=None,
                         location=(0, 0))
    p.add_layout(color_bar, 'right')
    p.yaxis.axis_label = y_label
    # p.yaxis.major_label_overrides={20:'Centromer'}
    for val in marks:
        hline = Span(location=val,
                     dimension='width',
                     line_color='green',
                     line_width=0.2)
        p.renderers.extend([hline])
    if folder:
        save(p, folder + title.replace(' ', "_") + "_cn_plot.html")
        #export_png(p, filename=folder + title.replace(' ', "_") + "_cn_plot.png")
    show(p)  # show the plot
    return p
Exemple #39
0
if __name__ == '__main__':
    df = mercator_df()
    fig = nyc_map('Citi bike stations in Jersey city and New york city')
    # colors for Jersey city and NYC regions
    fill_color = {70: 'blue', 71: 'firebrick'}
    line_color = {70: 'blue', 71: 'firebrick'}
    df["fill"] = df['region_id'].map(lambda x: fill_color[x])
    df["line"] = df['region_id'].map(lambda x: line_color[x])

    source = ColumnDataSource(df)
    # circle glyph for the stations
    region_glyph = Circle(x="x",
                          y="y",
                          fill_color="fill",
                          line_color="line",
                          size=10,
                          fill_alpha=0.5)
    region = fig.add_glyph(source, region_glyph)

    # hover tooltip to display name
    tooltips = """
    <div>
        <span style="font-size: 15px;">@name</span>&nbsp;<br>
        <span style="font-size: 15px;">station id: @station_id</span>&nbsp;
    </div>
    """
    # add hover tool to figure
    hover = HoverTool(tooltips=tooltips, renderers=[region])
    fig.add_tools(hover)
    show(fig)
Exemple #40
0
def scatter(data,
            labels=None,
            title='scatter plot',
            showlabels=False,
            folder='',
            colors=None,
            xname='',
            yname="",
            importance=None,
            radi=5,
            alpha=0.8,
            **kwargs):
    """
    Makes an interactive scatter plot using Bokeh

    Args:
    -----
      data: array-like with shape [N,2]
      labels: list[str] a list of N names for each points
      title: str the plot title
      showlabels: bool if the labels should be always displayed or not (else just on hover)
      colors: list[int] of N integers from 0 up to 256 for the dot's colors
      folder: str of location where to save the plot, won't save if empty
      xname: str the name of the x axes
      yname: str the name of the y axes
      importance: a list[int] of N values to scale the size of the dots and their opacity by
      radi: int the size of the dots
      alpha: float the opacity of the dots
      **kwargs: additional bokeh.figure args

    Returns:
    ------
      the bokeh object
    """
    TOOLS = "hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,save,box_select,lasso_select,"

    col = viridis(len(set(colors))) if colors is not None else ['#29788E'
                                                                ]  # (viridis1)
    radii = []
    fill_alpha = []
    cols = []
    for i in range(data.shape[0]):
        radii.append(radi if importance is None else radi / 2 +
                     importance[i] * 30)
        fill_alpha.append(alpha if importance is None else alpha -
                          (0.2 * importance[i]))
        cols.append(col[0] if colors is None else col[int(colors[i])])
    source = ColumnDataSource(
        data=dict(x=data[:, 0],
                  y=data[:, 1],
                  labels=labels if labels is not None else [''] * len(radii),
                  fill_color=cols,
                  fill_alpha=fill_alpha,
                  radius=radii))
    TOOLTIPS = [
        ("name", "@labels"),
        ("(x,y)", "(@x, @y)"),
    ]
    p = figure(tools=TOOLS, tooltips=TOOLTIPS, title=title)
    p.circle('x',
             'y',
             color='fill_color',
             fill_alpha='fill_alpha',
             line_width=0,
             radius='radius' if radi else None,
             source=source)
    p.xaxis[0].axis_label = xname
    p.yaxis[0].axis_label = yname
    if showlabels:
        labels = LabelSet(x='x',
                          y='y',
                          text='labels',
                          level='glyph',
                          text_font_size='9pt',
                          x_offset=5,
                          y_offset=5,
                          source=source,
                          render_mode='canvas')
        p.add_layout(labels)
    try:
        show(p)
    except:
        show(p)
    if folder:
        save(p, folder + title.replace(' ', "_") + "_scatter.html")
        #export_png(p, filename=folder + title.replace(' ', "_") + "_scatter.png")
    return p
Exemple #41
0
def volcano(data,
            folder='',
            tohighlight=None,
            tooltips=[('gene', '@gene_id')],
            title="volcano plot",
            xlabel='log-fold change',
            ylabel='-log(Q)',
            maxvalue=100,
            searchbox=False,
            logfoldtohighlight=0.15,
            pvaltohighlight=0.1,
            showlabels=False):
    """
    Make an interactive volcano plot from Differential Expression analysis tools outputs

    Args:
    -----
      data: a df with rows genes and cols [log2FoldChange, pvalue, gene_id]
      folder: str of location where to save the plot, won't save if empty
      tohighlight: list[str] of genes to highlight in the plot
      tooltips: list[tuples(str,str)] if user wants tot specify another bokeh tooltip
      title: str plot title
      xlabel: str if user wants to specify the title of the x axis
      ylabel: str if user wants tot specify the title of the y axis
      maxvalue: float the max -log2(pvalue authorized usefull when managing inf vals)
      searchbox: bool whether or not to add a searchBox to interactively highlight genes
      logfoldtohighlight: float min logfoldchange when to diplay points
      pvaltohighlight: float min pvalue when to diplay points
      showlabels: bool whether or not to show a text above each datapoint with its label information

    Returns:
    --------
      The bokeh object
    """
    # pdb.set_trace()
    to_plot_not, to_plot_yes = selector(
        data, tohighlight if tohighlight is not None else [],
        logfoldtohighlight, pvaltohighlight)
    hover = HoverTool(tooltips=tooltips, names=['circles'])

    # Create figure
    p = figure(title=title, plot_width=650, plot_height=450)

    p.xgrid.grid_line_color = 'white'
    p.ygrid.grid_line_color = 'white'
    p.xaxis.axis_label = xlabel
    p.yaxis.axis_label = ylabel

    # Add the hover tool
    p.add_tools(hover)
    p, source1 = add_points(p,
                            to_plot_not,
                            'log2FoldChange',
                            'pvalue',
                            color='#1a9641',
                            maxvalue=maxvalue)
    p, source2 = add_points(p,
                            to_plot_yes,
                            'log2FoldChange',
                            'pvalue',
                            color='#fc8d59',
                            alpha=0.6,
                            outline=True,
                            maxvalue=maxvalue)
    if showlabels:
        labels = LabelSet(x='log2FoldChange',
                          y='transformed_q',
                          text_font_size='7pt',
                          text="gene_id",
                          level="glyph",
                          x_offset=5,
                          y_offset=5,
                          source=source2,
                          render_mode='canvas')
        p.add_layout(labels)
    if searchbox:
        text = TextInput(title="text", value="gene")
        text.js_on_change(
            'value',
            CustomJS(args=dict(source=source1),
                     code="""
      var data = source.data
      var value = cb_obj.value
      var gene_id = data.gene_id
      var a = -1
      for (i=0; i < gene_id.length; i++) {
          if ( gene_id[i]===value ) { a=i; console.log(i); data.size[i]=7; data.alpha[i]=1; data.color[i]='#fc8d59' }
      }
      source.data = data
      console.log(source)
      console.log(cb_obj)
      source.change.emit()
      console.log(source)
      """))
        p = column(text, p)
    if folder:
        save(p, folder + title.replace(' ', "_") + "_volcano.html")
        #export_png(p, filename=folder + title.replace(' ', "_") + "_volcano.png")
    try:
        show(p)
    except:
        show(p)
    return p
Exemple #42
0
def correlationMatrix(data,
                      names,
                      colors=None,
                      pvals=None,
                      maxokpval=10**-9,
                      other=None,
                      title="correlation Matrix",
                      dataIsCorr=False,
                      invert=False,
                      size=40,
                      folder='',
                      interactive=False,
                      maxval=None,
                      minval=None):
    """
    Make an interactive correlation matrix from an array using bokeh

    Args:
    -----
      data: arrayLike of int / float/ bool of size(names*val) or (names*names)
      names: list[str] of names for each rows
      colors: list[int] of size(names) a color for each names (good to display clusters)
      pvals: arraylike of int / float/ bool of size(names*val) or (names*names) with the corresponding pvalues
      maxokpval: float threshold when pvalue is considered good. otherwise lowers the size of the square
        until 10**-3 when it disappears
      other: arrayLike of int / float/ bool of size(names*val) or (names*names), an additional information
        matrix that you want ot display with opacity whereas correlations willl be displayed with
      title: str the plot title
      dataIsCorr: bool if not true, we will compute the corrcoef of the data array
      invert: bool whether or not to invert the matrix before running corrcoef
      size: int the plot size
      folder: str of folder location where to save the plot, won't save if empty
      interactive: bool whether or not to make the plot interactive (else will use matplotlib)
      maxval: float clamping coloring up to maxval
      minval: float clamping coloring down to minval

    Returns:
    -------
      the bokeh object if interactive else None

    """
    if not dataIsCorr:
        print("computing correlations")
        data = np.corrcoef(np.array(data) if not invert else np.array(data).T)
    else:
        data = np.array(data)
    regdata = data.copy()
    if maxval is not None:
        data[data > maxval] = maxval
        data[data < -maxval] = -maxval
    if minval is not None:
        data[data < minval] = minval
    data = data / data.max()
    TOOLS = "hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,save"
    xname = []
    yname = []
    color = []
    alpha = []
    height = []
    width = []
    if type(colors) is list:
        print('we are assuming you want to display clusters with colors')
    elif other is not None:
        print(
            'we are assuming you want to display the other of your correlation with opacity'
        )
    if pvals is not None:
        print(
            'we are assuming you want to display the pvals of your correlation with size'
        )
        regpvals = pvals.copy()
        u = pvals < maxokpval
        pvals[~u] = np.log10(1 / pvals[~u])
        pvals = pvals / pvals.max().max()
        pvals[u] = 1
    if interactive:
        xname = []
        yname = []
        color = []
        for i, name1 in enumerate(names):
            for j, name2 in enumerate(names):
                xname.append(name1)
                yname.append(name2)
                if pvals is not None:
                    height.append(max(0.1, min(0.9, pvals[i, j])))
                    color.append(cc.coolwarm[int(
                        max(0, (data[i, j] * 128) + 127))])
                    alpha.append(min(abs(data[i, j]), 0.9))
                elif other is not None:
                    color.append(cc.coolwarm[int((data[i, j] * 128) + 127)])
                    alpha.append(
                        max(min(other[i,
                                      j], 0.9), 0.1) if other[i,
                                                              j] != 0 else 0)
                else:
                    alpha.append(min(abs(data[i, j]), 0.9))
                if colors is not None:
                    if type(colors) is list:
                        if colors[i] == colors[j]:
                            color.append(Category10[10][colors[i]])
                        else:
                            color.append('lightgrey')

                elif pvals is None and other is None:
                    color.append('grey' if data[i,
                                                j] > 0 else Category20[3][2])
        print(regdata.max())
        if pvals is not None:
            width = height.copy()
            data = dict(xname=xname,
                        yname=yname,
                        colors=color,
                        alphas=alpha,
                        data=regdata.ravel(),
                        pvals=regpvals.ravel(),
                        width=width,
                        height=height)
        else:
            data = dict(xname=xname,
                        yname=yname,
                        colors=color,
                        alphas=alpha,
                        data=data.ravel())
        tt = [('names', '@yname, @xname'), ('value', '@data')]
        if pvals is not None:
            tt.append(('pvals', '@pvals'))
        p = figure(title=title if title is not None else "Correlation Matrix",
                   x_axis_location="above",
                   tools=TOOLS,
                   x_range=list(reversed(names)),
                   y_range=names,
                   tooltips=tt)

        p.plot_width = 800
        p.plot_height = 800
        p.grid.grid_line_color = None
        p.axis.axis_line_color = None
        p.axis.major_tick_line_color = None
        p.axis.major_label_text_font_size = "5pt"
        p.axis.major_label_standoff = 0
        p.xaxis.major_label_orientation = np.pi / 3

        p.rect('xname',
               'yname',
               width=0.9 if not width else 'width',
               height=0.9 if not height else 'height',
               source=data,
               color='colors',
               alpha='alphas',
               line_color=None,
               hover_line_color='black',
               hover_color='colors')
        save(p, folder + title.replace(' ', "_") + "_correlation.html")
        #export_png(p, filename=folder + title.replace(' ', "_") + "_correlation.png")
        try:
            show(p)
        except:
            show(p)
        return p  # show the plot
    else:
        plt.figure(figsize=(size, 200))
        plt.title('the correlation matrix')
        plt.imshow(data)
        plt.savefig(title + "_correlation.pdf")
        plt.show()
Exemple #43
0
def field_explorer(artifacts, points, fields_shp_path, html_file_out=''):
    """Create bokeh map with summary information about all fields
    
    Parameters
    ----------
    artifacts, points : pandas DataFrames
    fields_shp_path : str
        Path to the shapefile of fields
    html_file_out : str
        Path to save the output file
    
    Returns
    -------
    None
    
    Notes
    -----
    If you want to print the output in a Jupyter notebook, use
    
    `from bokeh.io import output_notebook; output_notebook()`
    
    before running the function.
    """
    from bokeh.io import show
    from bokeh.plotting import figure, output_file
    from bokeh.models import (GeoJSONDataSource, HoverTool, PanTool,
                              WheelZoomTool, BoxZoomTool, ResetTool,
                              NumeralTickFormatter)

    geo_artifacts = find_geo_field(
        artifacts, fields_shp_path)  # find geofield for artifacts
    geo_points = find_geo_field(points,
                                fields_shp_path)  # find geofield for points

    fields_sum = fields_summary_table(
        geo_points, geo_artifacts)  # summarize artifacts by geofield
    fields_shp = read_fields_shp(
        fields_shp_path)  # get fields shapefile as geodataframe

    # attach artifact summaries to fields geodataframe
    fields_merge = fields_shp.merge(fields_sum,
                                    how='left',
                                    left_on='fid',
                                    right_on='Id')
    fields_merge = fields_merge.rename(
        columns={  # renaming columns makes them usable
            'Polígono': 'polygon',  # as tooltips in the bokeh plot
            'Parcela': 'parcel',
            'Subparcela': 'subparcel',
            'Id': 'id',
            'Núm. Pts.': 'n_pts',
            'Núm. Frags.': 'n_frags',
            'Pos. Pts.': 'pos_pts'
        })

    surveyed = fields_merge[
        ~fields_merge['n_pts'].isna()]  # get separate dataframes for
    unsurveyed = fields_merge[
        fields_merge['n_pts'].isna()]  # surveyed and unsurveyed fields
    surveyed_geojson = surveyed.to_json()  # convert both to geo_json
    unsurveyed_geojson = unsurveyed.to_json()

    surveyed_source = GeoJSONDataSource(
        geojson=surveyed_geojson)  # convert JSON to
    unsurveyed_source = GeoJSONDataSource(
        geojson=unsurveyed_geojson)  # bokeh GeoJSONDataSource

    output_file(html_file_out)

    surveyed_hover = [('Status', 'surveyed'), ('Campo', '@fid'),
                      ('Núm. Pts.', '@n_pts'), ('Pos. Pts.', '@pos_pts'),
                      ('Núm. Frags.', '@n_frags')]

    unsurveyed_hover = [('Status', 'not surveyed'), ('Campo', '@fid')]

    p = figure(plot_width=600,
               plot_height=450,
               tools=[PanTool(),
                      WheelZoomTool(),
                      BoxZoomTool(),
                      ResetTool()])
    p.xaxis[0].formatter = NumeralTickFormatter(format="0")
    p.yaxis[0].formatter = NumeralTickFormatter(format="0")

    s = p.patches(xs='xs',
                  ys='ys',
                  source=surveyed_source,
                  line_color='gray',
                  fill_color='lightgreen')
    p.add_tools(HoverTool(renderers=[s], tooltips=surveyed_hover))

    u = p.patches(xs='xs',
                  ys='ys',
                  source=unsurveyed_source,
                  line_color='gray',
                  fill_color='seashell')
    p.add_tools(HoverTool(renderers=[u], tooltips=unsurveyed_hover))

    show(p)
Exemple #44
0
# CODE:

# Perform necessary imports
from bokeh.io import output_file, show
from bokeh.plotting import figure
from bokeh.models import HoverTool, ColumnDataSource

# Make the ColumnDataSource: source
source = ColumnDataSource(
    data={
        'x': data.loc[1970].fertility,
        'y': data.loc[1970].life,
        'country': data.loc[1970].Country,
    })

# Create the figure: p
p = figure(title='1970',
           x_axis_label='Fertility (children per woman)',
           y_axis_label='Life Expectancy (years)',
           plot_height=400,
           plot_width=700,
           tools=[HoverTool(tooltips='@country')])

# Add a circle glyph to the figure p
p.circle(x='x', y='y', source=source)

# Output the file and show the figure
output_file('gapminder.html')
show(p)
Exemple #45
0
from bokeh.io import show
from bokeh.layouts import gridplot
from bokeh.layouts import layout

# first line plot
p1 = figure(plot_width=300, plot_height=150, title='first')

p1.line([1, 2, 3, 4, 5], [6, 7, 8, 9, 10], color='blue')

# second line plot
p2 = figure(plot_width=300, plot_height=150, title='second')

p2.line([6, 7, 8, 9, 10], [1, 2, 3, 4, 5], color='green')

# third line plot
p3 = figure(plot_width=300, plot_height=150, title='second')

p3.line([6, 7, 3, 11, 10], [1, 2, 3, 2, 5], color='red')

# pass 3 objects of plots to a grid layout
grid = gridplot([[p1, p2], [p3]])

# # [0,0]: !null     [0,1]: !null       *[1,0]: null*       [1,1]:!null
# grid = gridplot([[p1, p2], [None, p3]])

# # span fits for a single column plot row
# doc = layout([[p1, p2], [p3]], sizing_mode='scale_width')

# pass the layout to show method instead plots
show(grid)
Exemple #46
0
from bokeh.io import output_file, show
from bokeh.layouts import column
from bokeh.plotting import figure

output_file("layout.html")

x = list(range(11))
y0 = x
y1 = [10 - i for i in x]
y2 = [abs(i - 5) for i in x]

# create three plots
s1 = figure(width=250, height=250, background_fill_color="#fafafa")
s1.circle(x, y0, size=12, color="#53777a", alpha=0.8)

s2 = figure(width=250, height=250, background_fill_color="#fafafa")
s2.triangle(x, y1, size=12, color="#c02942", alpha=0.8)

s3 = figure(width=250, height=250, background_fill_color="#fafafa")
s3.square(x, y2, size=12, color="#d95b43", alpha=0.8)

# put the results in a column and show
show(column(s1, s2, s3))
Exemple #47
0
    def draw(self):
        graph = self.graph

        N = len(graph.vertices)
        node_indices = list(graph.vertices.keys())

        plot = figure(title="Graph Layout Demonstration",
                      x_range=(-7, 7),
                      y_range=(-7, 7),
                      tools="",
                      toolbar_location=None)

        graph_renderer = GraphRenderer()

        graph_renderer.node_renderer.data_source.add(node_indices, 'index')
        # node_colors = ['red'] * N
        # graph.node_renderer.data_source.add(node_colors, 'color')
        graph_renderer.node_renderer.glyph = Circle(radius=0.5,
                                                    fill_color="red")

        edge_start = []
        edge_end = []

        # O(E), where E is the total number of edges
        for vertex_id in node_indices:
            for v in graph.vertices[vertex_id].edges:
                edge_start.append(vertex_id)
                edge_end.append(v)

        graph_renderer.edge_renderer.data_source.data = dict(start=edge_start,
                                                             end=edge_end)

        ### start of layout code
        # circ = [i*2*math.pi/8 for i in node_indices]
        # x = [math.cos(i) for i in circ]
        # y = [math.sin(i) for i in circ]
        x = []
        y = []
        for vertex_id in node_indices:
            vertex = graph.vertices[vertex_id]
            x.append(vertex.x)
            y.append(vertex.y)

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph_renderer.layout_provider = StaticLayoutProvider(
            graph_layout=graph_layout)

        plot.renderers.append(graph_renderer)

        labelSource = ColumnDataSource(data=dict(
            x=x, y=y, names=[vertex_id for vertex_id in graph.vertices]))
        labels = LabelSet(x='x',
                          y='y',
                          text='names',
                          level='glyph',
                          text_align='center',
                          text_baseline='middle',
                          source=labelSource,
                          render_mode='canvas')

        plot.add_layout(labels)

        output_file('graph.html')
        show(plot)
Exemple #48
0
import networkx as nx

from bokeh.io import show, output_file
from bokeh.plotting import figure
from bokeh.models.graphs import from_networkx

G=nx.karate_club_graph()

plot = figure(title="Networkx Integration Demonstration", x_range=(-1.1,1.1), y_range=(-1.1,1.1),
                      tools="", toolbar_location=None)

graph = from_networkx(G, nx.spring_layout, scale=2, center=(0,0))
plot.renderers.append(graph)

output_file("networkx_graph.html")
show(plot)
Exemple #49
0
 def show(self):
     self._plot.add_tools(*self._build_tools(self._df, *self._hover_args))
     show(self._plot)
s.yaxis.axis_label_text_font_size = "14pt"
s.xaxis.axis_label_text_font_size = "14pt"
s.axis.major_label_text_font_size = "15pt"

odf = odf.sort_values("stars_per_employee", ascending=False)
t = figure(title="Number of Stars per Employee",
           x_range=odf.corporate.unique(),
           tools="",
           toolbar_location=None,
           plot_height=plot_height,
           plot_width=plot_width)

t.vbar(source=odf,
       x='corporate',
       top='stars_per_employee',
       width=1,
       line_color='white',
       fill_color=factor_cmap('corporate',
                              palette=colors,
                              factors=odf.corporate.unique()))

t.xaxis.major_label_orientation = pi / 3
t.x_range.range_padding = 0.01
t.y_range.range_padding = 0.01
# t.xgrid.grid_line_color = None
t.yaxis.axis_label_text_font_size = "14pt"
t.xaxis.axis_label_text_font_size = "14pt"
t.axis.major_label_text_font_size = "15pt"

show(column(row(p), row(s), row(t)))
Exemple #51
0
from bokeh.layouts import gridplot
from bokeh.models.widgets import Tabs, Panel
from bokeh.layouts import column, row

#Read the Data File
TFGM = pd.read_csv('TSLA_F_GM.csv')

data = ColumnDataSource(TFGM)
TFGM['Date'] = pd.to_datetime(TFGM['Date'])
#plot1 Adjusted Closing Proces
plot1 = figure(x_axis_type = 'datetime', x_axis_label = 'Dates', y_axis_label = 'Adj. Close Price', title = '3 Stock Portfolio 10yr Adj. Close')
#plot1.line('datetime', 'Adj. Close Price', legend_label="some label")
plot1.line(x = TFGM['Date'], y = TFGM['GM_Adj Close'], color = 'red', legend_label='GM')
plot1.line(x = TFGM['Date'], y = TFGM['TSLA_Adj Close'], color = 'black', legend_label='TSLA')
plot1.line(x = TFGM['Date'], y = TFGM['F_Adj Close'], color = 'green', legend_label='F')
#plot1.line(x = TFGM['Date'], y = TFGM['S&P'], color = 'purple')
plot1.legend.location = "top_left"
output_file('PLOT001.html')
#plot2 high
plot2 = figure(x_axis_type = 'datetime', x_axis_label = 'Dates', y_axis_label = 'Volume', title = 'Volume')
plot2.line(x = TFGM['Date'], y = TFGM['GM_Volume'], color = 'red', legend_label='GM')
plot2.line(x = TFGM['Date'], y = TFGM['TSLA_Volume'], color = 'black', legend_label='TSLA')
plot2.line(x = TFGM['Date'], y = TFGM['F_Volume'], color = 'green', legend_label='F')
#plot2.line(x = TFGM['Date'], y = TFGM['S&P_RET'], color = 'purple')
plot2.legend.location = "top_left"
output_file('PLOT002.html')
#combined plots
row_layout = row(plot1, plot2)
output_file('twoplots.html')
show(row_layout)
Exemple #52
0
    def show_task_capacity_per_server(self):
        from bokeh.io import output_file, show
        from bokeh.models import GraphRenderer, Oval, StaticLayoutProvider, ColumnDataSource, LabelSet
        from bokeh.plotting import figure
        from bokeh.palettes import Category20c, Category20
        # we have 12 kinds of tasks (number of columns in H) and 4 time_slots (number of rows in H)
        number_of_servers = len(self.H)
        tasks = ['task ' + str(i) for i in range(1, len(self.H[0]) + 1)]

        index_array_of_tasks = list(range(1, len(tasks) + 1))
        index_array_of_servers = list(range(len(tasks) + 1, len(tasks) + number_of_servers + 1))

        number_of_tasks = len(tasks)

        node_indices = np.concatenate((index_array_of_tasks, index_array_of_servers), axis=None).tolist()
        node_x_location = np.concatenate((index_array_of_tasks, list(range(1, len(index_array_of_servers) + 1))),
                                         axis=None).tolist()
        node_y_location = np.concatenate(
            (np.full(len(index_array_of_tasks), 5), np.full(len(index_array_of_servers), 3)), axis=None).tolist()

        plot = figure(title='Task capacity per server', x_range=(0, max(number_of_servers, number_of_tasks) + 1),
                      y_range=(0, 8),
                      tools='', toolbar_location=None)

        graph = GraphRenderer()

        graph.node_renderer.data_source.add(node_indices, 'index')
        graph.node_renderer.data_source.add(Category20c[len(node_indices)], 'color')
        graph.node_renderer.glyph = Oval(height=0, width=0, fill_color='color')

        network_graph_tasks_indices = []
        network_graph_server_indices = []
        network_graph_tasks_server_hash = {}

        for k in range(number_of_servers):  # servers
            for j in range(number_of_tasks):  # tasks
                if self.H[k, j] > 0:
                    network_graph_tasks_indices.append(j + 1)
                    network_graph_server_indices.append(len(tasks) + k + 1)
                    network_graph_tasks_server_hash[j + 1] = self.H[k, j]

        graph.edge_renderer.data_source.data = dict(
            start=list(network_graph_tasks_indices),
            end=list(network_graph_server_indices)
        )

        x = node_x_location
        y = node_y_location

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

        plot.renderers.append(graph)

        x_servers = list(range(1, len(index_array_of_servers) + 1))
        y_servers = np.full(len(index_array_of_servers), 3)
        plot.square(x_servers, y_servers, size=30, color=Category20[number_of_servers], alpha=0.5)

        x_tasks = index_array_of_tasks
        y_tasks = np.full(len(index_array_of_tasks), 5)
        plot.circle(x_tasks, y_tasks, size=30, color=Category20[len(index_array_of_tasks)], alpha=0.5)
        text_label_values = np.round(
            np.multiply(np.round(list(network_graph_tasks_server_hash.values()), 2), 100)).tolist()
        text_label_values = [str(int(capacity)) + '%' for capacity in text_label_values]

        source = ColumnDataSource(data=dict(x=list(network_graph_tasks_server_hash.keys()),
                                            y=np.full(len(network_graph_tasks_indices), 4.8),
                                            values=text_label_values))
        capacityLabels = LabelSet(x='x', y='y', text='values', level='glyph',
                                  x_offset=-8, y_offset=10, source=source, render_mode='canvas', text_font_size="10pt")

        plot.add_layout(capacityLabels)

        source = ColumnDataSource(data=dict(x=[6, 6],
                                            y=[2.5, 5.5],
                                            values=['servers', 'tasks']))

        typeLabel = LabelSet(x='x', y='y', text='values', level='glyph',
                             x_offset=0, y_offset=0, source=source, render_mode='canvas', text_font_size="10pt")
        plot.add_layout(typeLabel)

        output_file('graph.html')
        show(plot)

        return None
Exemple #53
0
    def show_flow_from_outside_to_buffers_to_tasks(self):
        from bokeh.io import output_file, show
        from bokeh.models import GraphRenderer, Oval, StaticLayoutProvider, ColumnDataSource, LabelSet, Arrow, OpenHead
        from bokeh.plotting import figure
        from bokeh.palettes import Plasma256
        # vector alpha >0 , vector a can be any value
        # a is input/output coming from outside
        # alpha is initial value in buffer
        # matrix G connected buffers and tasks
        # in matrix G , flow between a task and multiple buffers
        # a to buffer to task

        number_of_io_nodes = len(self.a)
        number_of_buffers = self.K
        number_of_tasks = len(self.H[0])
        index_array_of_io = list(range(1, number_of_io_nodes + 1))
        index_array_of_buffers = list(range(number_of_io_nodes + 1, number_of_io_nodes + number_of_buffers + 1))
        index_array_of_tasks = list(range(number_of_io_nodes + number_of_buffers + 1,
                                          number_of_io_nodes + number_of_buffers + number_of_tasks + 1))

        node_indices = np.concatenate((index_array_of_io, index_array_of_buffers, index_array_of_tasks),
                                      axis=None).tolist()
        node_x_location = np.concatenate((index_array_of_io, list(range(1, len(index_array_of_buffers) + 1)),
                                          list(range(1, len(index_array_of_tasks) + 1))), axis=None).tolist()
        node_y_location = np.concatenate(
            (np.full(number_of_io_nodes, 7), np.full(number_of_buffers, 5), np.full(number_of_tasks, 3)),
            axis=None).tolist()

        max_x_range = max(number_of_io_nodes, number_of_buffers, number_of_tasks) + 1

        plot = figure(title='Flow from outside to buffers to tasks', x_range=(0, max_x_range), y_range=(0, 9),
                      tools='', toolbar_location=None)

        graph = GraphRenderer()

        graph.node_renderer.data_source.add(node_indices, 'index')
        graph.node_renderer.data_source.add(Plasma256[:len(node_indices)], 'color')
        graph.node_renderer.glyph = Oval(height=0, width=0, fill_color='color')

        start = index_array_of_io
        end = index_array_of_buffers

        network_graph_buffer_task_hash = {}

        for buffer_index in range(number_of_buffers):
            network_graph_buffer_task_hash[buffer_index + 1] = np.sum(self.G[buffer_index, :])

        graph.edge_renderer.data_source.data = dict(
            start=start,
            end=end
        )

        x = node_x_location
        y = node_y_location

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

        plot.renderers.append(graph)

        x_io = list(range(1, number_of_io_nodes + 1))
        y_io = np.full(number_of_io_nodes, 7)
        plot.triangle(x_io, y_io, size=30, color=getLargePalette(number_of_io_nodes,Plasma256), alpha=0.5, line_width=2)

        x_buffers = list(range(1, number_of_buffers + 1))
        y_buffers = np.full(number_of_buffers, 5)
        plot.rect(x_buffers, y_buffers, color=getLargePalette(number_of_buffers,Plasma256), alpha=0.5, width=0.5, height=0.5)

        x_tasks = list(range(1, number_of_tasks + 1))
        y_tasks = np.full(number_of_tasks, 3)
        plot.circle(x_tasks, y_tasks, size=30, color=getLargePalette(number_of_tasks,Plasma256), alpha=0.5)

        for i in range(number_of_buffers):
            for j in range(number_of_tasks):
                if self.G[i, j] > 0:
                    x_start_node = x_buffers[i]
                    y_start_node = y_buffers[i]
                    x_end_node = x_tasks[j]
                    y_end_node = y_tasks[j]
                elif self.G[i, j] < 0:
                    x_start_node = x_tasks[j]
                    y_start_node = y_tasks[j]
                    x_end_node = x_buffers[i]
                    y_end_node = y_buffers[i]
                plot.add_layout(Arrow(end=OpenHead(),
                                      x_start=x_start_node, y_start=y_start_node, x_end=x_end_node, y_end=y_end_node))

        text_label_values = np.round(
            np.multiply(np.round(list(network_graph_buffer_task_hash.values()), 2), 100)).tolist()
        text_label_values = [str(int(capacity)) + '%' for capacity in text_label_values]

        source = ColumnDataSource(data=dict(x=list(network_graph_buffer_task_hash.keys()),
                                            y=np.full(number_of_buffers, 4.8),
                                            values=text_label_values))
        capacityLabels = LabelSet(x='x', y='y', text='values', level='glyph',
                                  x_offset=-8, y_offset=10, source=source, render_mode='canvas', text_font_size="10pt")

        plot.add_layout(capacityLabels)

        source = ColumnDataSource(data=dict(x=[max_x_range / 2 - 0.5, max_x_range / 2 - 0.5, max_x_range / 2 - 0.5],
                                            y=[2.5, 5.5, 7.5],
                                            values=['tasks', 'buffers', 'outside sources']))

        typeLabel = LabelSet(x='x', y='y', text='values', level='glyph',
                             x_offset=0, y_offset=0, source=source, render_mode='canvas', text_font_size="10pt")
        plot.add_layout(typeLabel)

        output_file('graph.html')
        show(plot)

        return None
Exemple #54
0
s2.data['z']=d2[cb_obj.selected['1d'].indices]
console.log(d2['z'])
s2.trigger('change');
console.log('Tap event occured at x-position: ' + cb_obj.selected['1d'].indices)
""")
#Creating a slider
slider = Slider(start=0,
                end=14400,
                value=0,
                step=1,
                title="Time slider in seconds")


def update(s1=s1, slider=slider, window=None):
    data = s1.data
    v = cb_obj.value
    data['rate'] = data[v]
    s1.trigger('change')


slider.js_on_change('value', CustomJS.from_py_func(update))
g1 = (column(
    p,
    widgetbox(slider),
))
g2 = column(sp, n)
layout = row(g1, g2)
show(layout)

# In[ ]:
Exemple #55
0
def show_interact_widget(tpf,
                         notebook_url='localhost:8888',
                         max_cadences=30000,
                         aperture_mask='pipeline',
                         exported_filename=None):
    """Display an interactive Jupyter Notebook widget to inspect the pixel data.

    The widget will show both the lightcurve and pixel data.  The pixel data
    supports pixel selection via Bokeh tap and box select tools in an
    interactive javascript user interface.

    Note: at this time, this feature only works inside an active Jupyter
    Notebook, and tends to be too slow when more than ~30,000 cadences
    are contained in the TPF (e.g. short cadence data).

    Parameters
    ----------
    tpf : lightkurve.TargetPixelFile
        Target Pixel File to interact with
    notebook_url: str
        Location of the Jupyter notebook page (default: "localhost:8888")
        When showing Bokeh applications, the Bokeh server must be
        explicitly configured to allow connections originating from
        different URLs. This parameter defaults to the standard notebook
        host and port. If you are running on a different location, you
        will need to supply this value for the application to display
        properly. If no protocol is supplied in the URL, e.g. if it is
        of the form "localhost:8888", then "http" will be used.
    max_cadences : int
        Raise a RuntimeError if the number of cadences shown is larger than
        this value. This limit helps keep browsers from becoming unresponsive.
    """
    try:
        import bokeh
        if bokeh.__version__[0] == '0':
            warnings.warn("interact() requires Bokeh version 1.0 or later",
                          LightkurveWarning)
    except ImportError:
        log.error("The interact() tool requires the `bokeh` Python package; "
                  "you can install bokeh using e.g. `conda install bokeh`.")
        return None

    aperture_mask = tpf._parse_aperture_mask(aperture_mask)

    if exported_filename is None:
        exported_filename = make_default_export_name(tpf)
    try:
        exported_filename = str(exported_filename)
    except:
        log.error('Invalid input filename type for interact()')
        raise
    if ('.fits' not in exported_filename.lower()):
        exported_filename += '.fits'

    lc = tpf.to_lightcurve(aperture_mask=aperture_mask)

    npix = tpf.flux[0, :, :].size
    pixel_index_array = np.arange(0, npix, 1).reshape(tpf.flux[0].shape)

    # Bokeh cannot handle many data points
    # https://github.com/bokeh/bokeh/issues/7490
    if len(lc.cadenceno) > max_cadences:
        msg = 'Interact cannot display more than {} cadences.'
        raise RuntimeError(msg.format(max_cadences))

    def create_interact_ui(doc):
        # The data source includes metadata for hover-over tooltips
        lc_source = prepare_lightcurve_datasource(lc)
        tpf_source = prepare_tpf_datasource(tpf, aperture_mask)

        # Create the lightcurve figure and its vertical marker
        fig_lc, vertical_line = make_lightcurve_figure_elements(lc, lc_source)

        # Create the TPF figure and its stretch slider
        pedestal = np.nanmin(tpf.flux)
        fig_tpf, stretch_slider = make_tpf_figure_elements(tpf,
                                                           tpf_source,
                                                           pedestal=pedestal,
                                                           fiducial_frame=0)

        # Helper lookup table which maps cadence number onto flux array index.
        tpf_index_lookup = {cad: idx for idx, cad in enumerate(tpf.cadenceno)}

        # Interactive slider widgets and buttons to select the cadence number
        cadence_slider = Slider(start=np.min(tpf.cadenceno),
                                end=np.max(tpf.cadenceno),
                                value=np.min(tpf.cadenceno),
                                step=1,
                                title="Cadence Number",
                                width=490)
        r_button = Button(label=">", button_type="default", width=30)
        l_button = Button(label="<", button_type="default", width=30)
        export_button = Button(label="Save Lightcurve",
                               button_type="success",
                               width=120)
        message_on_save = Div(text=' ', width=600, height=15)

        # Callbacks
        def update_upon_pixel_selection(attr, old, new):
            """Callback to take action when pixels are selected."""
            # Check if a selection was "re-clicked", then de-select
            if ((sorted(old) == sorted(new)) & (new != [])):
                # Trigger recursion
                tpf_source.selected.indices = new[1:]

            if new != []:
                selected_indices = np.array(new)
                selected_mask = np.isin(pixel_index_array, selected_indices)
                lc_new = tpf.to_lightcurve(aperture_mask=selected_mask)
                lc_source.data['flux'] = lc_new.flux
                ylims = get_lightcurve_y_limits(lc_source)
                fig_lc.y_range.start = ylims[0]
                fig_lc.y_range.end = ylims[1]
            else:
                lc_source.data['flux'] = lc.flux * 0.0
                fig_lc.y_range.start = -1
                fig_lc.y_range.end = 1

            message_on_save.text = " "
            export_button.button_type = "success"

        def update_upon_cadence_change(attr, old, new):
            """Callback to take action when cadence slider changes"""
            if new in tpf.cadenceno:
                frameno = tpf_index_lookup[new]
                fig_tpf.select('tpfimg')[0].data_source.data['image'] = \
                    [tpf.flux[frameno, :, :] - pedestal]
                vertical_line.update(location=tpf.time[frameno])
            else:
                fig_tpf.select('tpfimg')[0].data_source.data['image'] = \
                    [tpf.flux[0, :, :] * np.NaN]
            lc_source.selected.indices = []

        def go_right_by_one():
            """Step forward in time by a single cadence"""
            existing_value = cadence_slider.value
            if existing_value < np.max(tpf.cadenceno):
                cadence_slider.value = existing_value + 1

        def go_left_by_one():
            """Step back in time by a single cadence"""
            existing_value = cadence_slider.value
            if existing_value > np.min(tpf.cadenceno):
                cadence_slider.value = existing_value - 1

        def save_lightcurve():
            """Save the lightcurve as a fits file with mask as HDU extension"""
            if tpf_source.selected.indices != []:
                selected_indices = np.array(tpf_source.selected.indices)
                selected_mask = np.isin(pixel_index_array, selected_indices)
                lc_new = tpf.to_lightcurve(aperture_mask=selected_mask)
                lc_new.to_fits(exported_filename,
                               overwrite=True,
                               aperture_mask=selected_mask.astype(np.int),
                               SOURCE='lightkurve interact',
                               NOTE='custom mask',
                               MASKNPIX=np.nansum(selected_mask))
                if message_on_save.text == " ":
                    text = '<font color="black"><i>Saved file {} </i></font>'
                    message_on_save.text = text.format(exported_filename)
                    export_button.button_type = "success"
                else:
                    text = '<font color="gray"><i>Saved file {} </i></font>'
                    message_on_save.text = text.format(exported_filename)
            else:
                text = '<font color="gray"><i>No pixels selected, no mask saved</i></font>'
                export_button.button_type = "warning"
                message_on_save.text = text

        def jump_to_lightcurve_position(attr, old, new):
            if new != []:
                cadence_slider.value = lc.cadenceno[new[0]]

        # Map changes to callbacks
        r_button.on_click(go_right_by_one)
        l_button.on_click(go_left_by_one)
        tpf_source.selected.on_change('indices', update_upon_pixel_selection)
        lc_source.selected.on_change('indices', jump_to_lightcurve_position)
        export_button.on_click(save_lightcurve)
        cadence_slider.on_change('value', update_upon_cadence_change)

        # Layout all of the plots
        sp1, sp2, sp3, sp4 = (Spacer(width=15), Spacer(width=30),
                              Spacer(width=80), Spacer(width=60))
        widgets_and_figures = layout([fig_lc, fig_tpf], [
            l_button, sp1, r_button, sp2, cadence_slider, sp3, stretch_slider
        ], [export_button, sp4, message_on_save])
        doc.add_root(widgets_and_figures)

    output_notebook(verbose=False, hide_banner=True)
    return show(create_interact_ui, notebook_url=notebook_url)
Exemple #56
0
def bigScatter(data,
               precomputed=False,
               logscale=False,
               features=False,
               title="BigScatter",
               binsize=0.1,
               folder="",
               showpoint=False):
    """
    uses a binning method to display millions of points at the same time and showcase density.

    Does this in an interactive fashion

    Args:
    -----
      data: array like. the array containing the point location x,y or their location and density of bins (q,r,c)
      precomputed: bool whether or not the array has aleady been hexbined
      logscale: bool, whether or not the data is logscaled
      features: list[] if the matrix contains a feature column with feature information (names, values. for each bin/dot)
      title: str the title of the plot
      binsize: float the size of the bins
      showpoint: bool whether or not to display them as points or hexes.
      folder: str of location where to save the plot, won't save if empty

    Returns:
    ------
      the bokeh object
    """
    TOOLS = "wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,save,box_select,lasso_select,"
    names = [("count", "@c")]
    if features:
        names.append(('features', '@features'))
    if precomputed:
        TOOLS = "hover," + TOOLS
    p = figure(title=title,
               tools=TOOLS,
               tooltips=names if precomputed else None,
               match_aspect=True,
               background_fill_color='#440154')
    if precomputed:
        p.hex_tile(q="q",
                   r="r",
                   size=binsize,
                   line_color=None,
                   source=data,
                   hover_color="pink",
                   hover_alpha=0.8,
                   fill_color=linear_cmap('c', 'Viridis256', 0, max(data.c))
                   if not logscale else {
                       'field': 'c',
                       'transform': LogColorMapper('Viridis256')
                   })
    else:
        if features:
            print("we cannot yet process features on non precomputed version")
        r, bins = p.hexbin(data[:, 0],
                           data[:, 1],
                           line_color=None,
                           size=binsize,
                           hover_color="pink",
                           hover_alpha=0.8,
                           fill_color=linear_cmap('c', 'Viridis256', 0, None)
                           if not logscale else {
                               'field': 'c',
                               'transform': LogColorMapper('Viridis256')
                           })
    p.grid.visible = False
    if showpoint:
        p.circle(data[:, 0], data[:, 1], color="white", size=1)

    if not precomputed:
        p.add_tools(
            HoverTool(tooltips=names,
                      mode="mouse",
                      point_policy="follow_mouse",
                      renderers=[r] if not precomputed else None))

    try:
        show(p)
    except:
        show(p)
    if folder:
        save(p, folder + title.replace(' ', "_") + "_scatter.html")
        #export_png(p, filename=folder + title.replace(' ', "_") + "_scatter.png")

    return p
from bokeh.io import show
from bokeh.models import Div

div = Div(
    width=400, height=100, background="#fafafa",
    text="The Pythagorean identity is $$\sin^2(x) + \cos^2(x) = 1$$"
)

show(div)
Exemple #58
0
def create_cws_map(df, suffix):
    """Reads in a data-frame and exports a html file, containing a bokeh map, placed within the 'maps' folder.

    Parameters
    ----------
    df : dataframe
        A dataframe that must contain the following columns:
        - geometry
        - p_id
        - lon
        - lat
        - ta_int

    suffix : str
        A string that will be appended to the title of the plots as well as the html file-names.
    """

    tile_provider = get_provider(
        "CARTODBPOSITRON_RETINA"
    )  # More Providers https://docs.bokeh.org/en/latest/docs/reference/tile_providers.html

    # Range bounds supplied in web mercator coordinates
    p = figure(
        x_range=(825000, 833000),
        y_range=(5933000, 5935000),
        x_axis_type="mercator",
        y_axis_type="mercator",  # Changes axis to a more legible input
        x_axis_label="Longitude",
        y_axis_label="Latitude",
        sizing_mode="stretch_both")
    p.add_tile(tile_provider)

    # Filter point sto be added by color
    p = filter_points_by_color(df, p)

    # Add hover tools as a means for interactivity
    my_hover = HoverTool(
    )  # https://automating-gis-processes.github.io/2016/Lesson5-interactive-map-bokeh.html#adding-interactivity-to-the-map

    # Specify what parameters should be displayed when hovering
    my_hover.tooltips = [('Id', '@p_id'), ('Temperature [C]', '@ta_int'),
                         ('Longitude', '@lon'), ('Latitude', '@lat')]
    p.add_tools(my_hover)

    # Creating divs to serve as additional information
    div_title = Div(align="center",
                    text="<h1>Citizen Weather Stations: " + suffix +
                    ":00</h1>",
                    sizing_mode="stretch_both")
    div_subtitle = Div(
        align="center",
        text=
        "Blue: Below 22 °C. <br> Orange: Between 22 °C and 28 °C. <br> Red: Above 28 °C.",
        sizing_mode="stretch_both")

    # Arrange all the bokeh elements in a layout
    layout_plot = layout([[div_title], [div_subtitle], [p]])

    # Specify output location and name
    output_file("../maps/Bern-CWS-Map_" + suffix + ".html")

    # Shows the result in the default browser and saves the file
    show(layout_plot)
Exemple #59
0
def display_timeline_values(
    data: pd.DataFrame,
    y: str,
    time_column: str = "TimeGenerated",
    source_columns: list = None,
    **kwargs,
) -> figure:
    """
    Display a timeline of events.

    Parameters
    ----------
    data : pd.DataFrame
        DataFrame as a single data set or grouped into individual
        plot series using the `group_by` parameter
    time_column : str, optional
        Name of the timestamp column
        (the default is 'TimeGenerated')
    y : str
        The column name holding the value to plot vertically
    source_columns : list, optional
        List of default source columns to use in tooltips
        (the default is None)

    Other Parameters
    ----------------
    x : str, optional
        alias of `time_column`
    title : str, optional
        Title to display (the default is None)
    ref_event : Any, optional
        Add a reference line/label using the alert time (the default is None)
    ref_time : datetime, optional
        Add a reference line/label using `ref_time` (the default is None)
    group_by : str
        (where `data` is a DataFrame)
        The column to group timelines on
    legend: str, optional
        "left", "right", "inline" or "none"
        (the default is to show a legend when plotting multiple series
        and not to show one when plotting a single series)
    yaxis : bool, optional
        Whether to show the yaxis and labels
    range_tool : bool, optional
        Show the the range slider tool (default is True)
    height : int, optional
        The height of the plot figure
        (the default is auto-calculated height)
    width : int, optional
        The width of the plot figure (the default is 900)
    color : str
        Default series color (default is "navy"). This is overridden by
        automatic color assignments if plotting a grouped chart
    kind : Union[str, List[str]]
        one or more glyph types to plot., optional
        Supported types are "circle", "line" and "vbar" (default is "vbar")

    Returns
    -------
    figure
        The bokeh plot figure.

    """
    check_kwargs(kwargs, _DEFAULT_KWARGS + _TL_VALUE_KWARGS)

    reset_output()
    output_notebook()

    height: int = kwargs.pop("height", None)
    width: int = kwargs.pop("width", 900)
    title: str = kwargs.pop("title", None)
    time_column = kwargs.get("x", time_column)
    group_by: str = kwargs.get("group_by", None)
    show_yaxis: bool = kwargs.pop("yaxis", True)
    show_range: bool = kwargs.pop("range_tool", True)
    color: str = kwargs.get("color", "navy")
    legend_pos: str = kwargs.pop("legend", None)
    kind: Any = kwargs.pop("kind", ["vbar"])
    plot_kinds = kind if isinstance(kind, list) else [kind]

    ref_time, ref_label = _get_ref_event_time(**kwargs)

    graph_df, group_count_df, tool_tip_columns, series_count = _create_data_grouping(
        data, source_columns, time_column, group_by, color)

    hover = HoverTool(
        tooltips=_create_tool_tips(data, tool_tip_columns),
        formatters={"Tooltip": "printf"},
    )

    # Create the Plot figure
    title = title if title else "Timeline"
    min_time = graph_df[time_column].min()
    max_time = graph_df[time_column].max()
    start_range = min_time - ((max_time - min_time) * 0.1)
    end_range = max_time + ((max_time - min_time) * 0.1)
    height = height if height else _calc_auto_plot_height(series_count)

    plot = figure(
        x_range=(start_range, end_range),
        min_border_left=50,
        plot_height=height,
        plot_width=width,
        x_axis_label="Event Time",
        x_axis_type="datetime",
        x_minor_ticks=10,
        y_axis_label=y,
        tools=[hover, "xwheel_zoom", "box_zoom", "reset", "save", "xpan"],
        toolbar_location="above",
        title=title,
    )
    plot.yaxis.visible = show_yaxis
    plot.ygrid.minor_grid_line_color = "navy"
    plot.ygrid.minor_grid_line_alpha = 0.1
    plot.ygrid.grid_line_color = "navy"
    plot.ygrid.grid_line_alpha = 0.3
    plot.xgrid.minor_grid_line_color = "navy"
    plot.xgrid.minor_grid_line_alpha = 0.1
    plot.xgrid.grid_line_color = "navy"
    plot.xgrid.grid_line_alpha = 0.3

    # set the tick datetime formatter
    plot.xaxis[0].formatter = _get_tick_formatter()

    # plot groups individually so that we can create an interactive legend
    if group_by:
        legend_items = []
        for _, group_id in group_count_df[group_by].items():
            first_group_item = graph_df[graph_df[group_by] == group_id].iloc[0]
            legend_label = str(first_group_item[group_by])
            inline_legend = str(group_id) if legend_pos == "inline" else None
            group_color = first_group_item["color"]
            row_source = ColumnDataSource(
                graph_df[graph_df[group_by] == group_id])
            p_series = []
            # create default plot args
            plot_args: Dict[str, Any] = dict(
                x=time_column,
                alpha=0.7,
                source=row_source,
                legend_label=str(inline_legend),
            )
            if "vbar" in plot_kinds:
                p_series.append(
                    plot.vbar(top=y, width=4, color="color", **plot_args))
            if "circle" in plot_kinds:
                p_series.append(
                    plot.circle(y=y, size=4, color="color", **plot_args))
            if "line" in plot_kinds:
                p_series.append(
                    plot.line(y=y,
                              line_width=1,
                              line_color=group_color,
                              **plot_args))
            if not inline_legend:
                legend_items.append((legend_label, p_series))

        if legend_pos == "inline":
            # Position the inline legend
            plot.legend.location = "top_left"
            plot.legend.click_policy = "hide"
        elif legend_pos in ["left", "right"]:
            # Create the legend box outside of the plot area
            ext_legend = Legend(
                items=legend_items,
                location="center",
                click_policy="hide",
                label_text_font_size="8pt",
            )
            plot.add_layout(ext_legend, legend_pos)
    else:
        plot_args = dict(x=time_column,
                         color="color",
                         alpha=0.7,
                         source=ColumnDataSource(graph_df))
        if "vbar" in plot_kinds:
            plot.vbar(top=y, width=4, **plot_args)
        if "circle" in plot_kinds:
            plot.circle(y=y, size=4, **plot_args)
        if "line" in plot_kinds:
            plot.line(y=y, line_width=4, **plot_args)

    # if we have a reference, plot the time as a line
    if ref_time is not None:
        _add_ref_line(plot, ref_time, ref_label, series_count)

    if show_range:
        rng_select = _create_range_tool(
            data=graph_df,
            min_time=min_time,
            max_time=max_time,
            plot_range=plot.x_range,
            width=width,
            height=height,
            time_column=time_column,
        )
        show(column(plot, rng_select))
    else:
        show(plot)
    return plot
# create a new plot (with a title) using figure
p = figure(
    plot_width=400,
    plot_height=400,
    title="Comparison of Losses (in blue) and Validation Losses (in red)")

# add a line renderer
p.multi_line([
    list(range(len(history.history["loss"]))),
    list(range(len(history.history["val_loss"])))
], [history.history["loss"], history.history["val_loss"]],
             color=["firebrick", "navy"],
             line_width=2)

show(p)  # show the results

# In[7]:

from sklearn.metrics import confusion_matrix

pred = model.predict(x_test)
pred = np.argmax(pred, axis=1)
y_test2 = np.argmax(y_test.values, axis=1)

# Compute confusion matrix
cm = confusion_matrix(y_test2, pred)
np.set_printoptions(precision=2)
print('Confusion matrix, without normalization')
#print(cm)