Esempio n. 1
0
def programming(request):

    lang = ['Python', 'JavaScript', 'C#', 'PHP', 'C++', 'Java']
    counts = [25, 30, 8, 22, 12, 17]

    p = figure(x_range=lang,
               plot_height=450,
               title="Programming Languages Popularity",
               toolbar_location="below",
               tools="pan,wheel_zoom,box_zoom,reset, hover, tap, crosshair")

    source = ColumnDataSource(
        data=dict(lang=lang, counts=counts, color=Spectral6))
    p.add_tools(LassoSelectTool())
    p.add_tools(WheelZoomTool())

    p.vbar(x='lang',
           top='counts',
           width=.8,
           color='color',
           legend="lang",
           source=source)
    p.legend.orientation = "horizontal"
    p.legend.location = "top_center"

    p.xgrid.grid_line_color = "black"
    p.y_range.start = 0
    p.line(x=lang, y=counts, color="black", line_width=2)

    script, div = components(p)

    return render(request, 'programming.html', {'script': script, 'div': div})
Esempio n. 2
0
    def _setup_map(self):
        """"""
        pan = PanTool()
        save = SaveTool()
        tap = TapTool()
        lasso = LassoSelectTool()
        reset = ResetTool()
        wheel = WheelZoomTool()

        tooltips = HoverTool(tooltips=[("Station", "@STATN"),
                                       ("Lat", "@LATIT_DD"),
                                       ("Lon", "@LONGI_DD")])

        # range bounds supplied in web mercator coordinates
        self.map = figure(
            x_range=(0, 4000000),
            y_range=(7100000, 9850000),
            x_axis_type="mercator",
            y_axis_type="mercator",
            sizing_mode='stretch_both',
            tools=[pan, wheel, tap, lasso, tooltips, reset, save], height=300, width=500,
        )

        # self.map.yaxis.axis_label = ' '  # in order to aline y-axis with figure window below
        self.map.toolbar.active_scroll = self.map.select_one(WheelZoomTool)
        self.map.add_tile(self.tile_provider)

        tap.callback = station_callback(
            plot_source=self.plot_source,
            data_source=self.data_source,
            text_source=self.text,
            station_source=self.position_source,
            text_input_list=self.text_inputs,
        )
Esempio n. 3
0
def test_lasso_select(output_file_url, selenium):
    plot = generate_plot()

    #limit to one callback on click release
    plot.add_tools(LassoSelectTool(select_every_mousemove=False))

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

    # Drag a lasso selection area around middle point
    canvas = selenium.find_element_by_tag_name('canvas')

    actions = ActionChains(selenium)
    actions.move_to_element_with_offset(canvas, PLOT_DIM * 0.25,
                                        PLOT_DIM * 0.25)
    actions.click_and_hold()
    actions.move_by_offset(0, PLOT_DIM * 0.5)
    actions.move_by_offset(PLOT_DIM * 0.5, 0)
    actions.move_by_offset(0, PLOT_DIM * -0.5)
    actions.release()
    actions.perform()

    # Get the alert from box select and assert that the middle item is selected
    alert = selenium.switch_to_alert()
    assert alert.text == 'middle'
Esempio n. 4
0
def protein_detail(request, name):

    data = PesticidalProteinDatabase.objects.filter(name=name).first()
    histo = data.get_sequence_count_aminoacids()

    keys, values = zip(*histo.items())
    language = list(keys)
    counts = list(values)

    p = figure(x_range=language, plot_height=1000, plot_width=1000,
               toolbar_location="below", tools="pan, wheel_zoom, box_zoom, reset, hover, tap, crosshair")

    source = ColumnDataSource(
        data=dict(language=language, counts=counts, color=Category20[20]))
    p.add_tools(LassoSelectTool())
    p.add_tools(WheelZoomTool())

    p.vbar(x='language', top='counts', width=0.8, color='color',
           legend_group="language", source=source)
    p.legend.orientation = "horizontal"
    p.legend.location = "top_center"
    p.y_range.start = 0

    script, div = components(p)

    context = {'proteins': PesticidalProteinDatabase.objects.filter(name=name),
               'script': script, 'div': div
               }

    return render(request, 'database/protein_detail.html', context)
Esempio n. 5
0
def MarketPlot(tblCoins, coinHistory):
    hover2 = HoverTool(
        tooltips=[
            ('Coin:', '@name'),
            ('Date:', '@strDate'),
            ('Price:',
             '$@strPrice_USD'),  # use @{ } for field names with spaces
        ],
        formatters={
            'Date:': 'datetime',
        },
    )

    tools = [hover2, WheelZoomTool(), 'box_zoom', 'pan', LassoSelectTool()]

    market_plot = figure(x_axis_type="datetime",
                         title="Performance of the Coins I Own",
                         plot_width=1000,
                         plot_height=400,
                         y_range=(0, 22000),
                         tools=tools)
    market_plot.grid.grid_line_alpha = 0.2
    market_plot.xaxis.axis_label = "Date"
    market_plot.yaxis.axis_label = "Price (USD)"

    coins = list(set(coinHistory.name))
    numCoins = len(coins)

    tblCoins = tblCoins.sort_values('timestamp')
    tblCoins['strDate'] = tblCoins['timestamp'].dt.strftime('%Y-%m-%d %H:%M')
    tblCoins['strPrice_USD'] = tblCoins['price_usd'].round(2).astype(str)

    datasourceCoins = dict()
    for i, coin in zip(range(numCoins), coins):
        datasourceCoins[i] = ColumnDataSource(
            tblCoins[tblCoins['name'] == coin])
        market_plot.line('timestamp',
                         'price_usd',
                         color=colorDict[coin],
                         alpha=1,
                         legend=coin,
                         source=datasourceCoins[i])

    dates = list(set(coinHistory['transaction_time']))

    Purchase = dict()
    for d in dates:

        Purchase[d] = Span(location=dt2ut(d) * 1000,
                           dimension='height',
                           line_color='green',
                           line_dash='dashed',
                           line_width=1)
        market_plot.add_layout(Purchase[d])

    market_plot.legend.location = "top_center"
    market_plot.legend.orientation = "horizontal"

    return market_plot
    def plot_pca_apexbio_asinex(self, parameter, a, b):
        result = self.result
        print(a, b)
        source1 = column_source(result, "APEXBIO")
        source2 = column_source(result, "Asinex")
        hover = HoverTool(tooltips=[
            ("PCA 1", "$x"),
            ("PCA 2", "$y"),
            ("ID", "@N"),
        ])
        p = figure(
            # title="PCA based on: " + parameter,
            x_axis_label="PC 1 " + str(a) + "%",
            y_axis_label="PC 2 " + str(b) + "%",
            x_range=(-2, 6),
            y_range=(-4, 4.1),
            tools=[hover],
            plot_width=1000,
            plot_height=800,
        )
        p.add_tools(LassoSelectTool(), ZoomInTool(), ZoomOutTool(), SaveTool(),
                    PanTool())
        APEXBIO_plot = p.circle(x="x",
                                y="y",
                                source=source1,
                                color="mediumvioletred",
                                size=5)
        Asinex_plot = p.circle(x="x",
                               y="y",
                               source=source2,
                               color="mediumslateblue",
                               size=5)

        legend = Legend(
            items=[
                ("APEXBIO", [APEXBIO_plot]),
                ("Asinex", [Asinex_plot]),
            ],
            location="center",
            orientation="vertical",
            click_policy="hide",
        )
        p.add_layout(legend, place="right")
        p.xaxis.axis_label_text_font_size = "20pt"
        p.yaxis.axis_label_text_font_size = "20pt"
        p.xaxis.axis_label_text_color = "black"
        p.yaxis.axis_label_text_color = "black"
        p.xaxis.major_label_text_font_size = "18pt"
        p.yaxis.major_label_text_font_size = "18pt"
        p.title.text_font_size = "22pt"
        #
        show(p)
        # save
        p.output_backend = "svg"
        export_svgs(
            p,
            filename="/Users/eurijuarez/Desktop/Alexis/Plots/SVG_files/" +
            "ChemSpace_PCA_APEXBIO_Asinex" + ".svg",
        )
Esempio n. 7
0
def bike_locations(request):
    if not is_manager(request.user):
        return redirect(reverse('bikes:index'))

    loc = request.GET.get('loc', None)
    if loc is None:
        location_name = Location.objects.first().station_name
    else:
        location_name = Location.objects.get(station_name__iexact=loc).station_name
    loc = Location.objects.get(station_name__iexact=location_name)

    locations = Location.objects.annotate(bike_count=Count('bikes'))
    stations = [location.station_name for location in locations]
    bike_counts = [location.bike_count for location in locations]
    plot = figure(x_range=stations, plot_height=400,  title="Bikes per location", toolbar_location="below")
    source = ColumnDataSource(data=dict(stations=stations, bike_counts=bike_counts, color=Spectral6))
    plot.add_tools(LassoSelectTool())
    plot.add_tools(WheelZoomTool())
    plot.add_tools(HoverTool())

    plot.vbar(x='stations', top='bike_counts', width=.8, color='color', source=source)

    plot.xgrid.grid_line_color = "black"
    plot.xaxis.major_label_orientation = math.pi/6
    plot.min_border_left = 80
    plot.min_border_right = 80
    plot.y_range.start = 0
    plot.y_range.end   = max(bike_counts) + 2

    script, div = components(plot)

    # Time series graph
    hire_history = LocationBikeCount.objects.filter(location=loc).values()
    dates = [hire['datetime'] for hire in hire_history]
    count = [hire['count'] for hire in hire_history]
    time_source = ColumnDataSource(
        data=dict(datetime=dates, count=count)
    )
    time_plot = figure(x_axis_type='datetime', plot_height=400)
    time_plot.step('datetime', 'count', line_width=2, source=time_source)
    hover = HoverTool()
    hover.tooltips = [
        ("Date", "@datetime"), 
        ("Count", "@count")
    ]
    time_plot.add_tools(hover)
    time_script, time_div = components(time_plot)

    context = {
        "script": script, 
        "div": div, "location_name": 
        location_name, 
        "locations": locations,
        "time_series_script": time_script,
        "time_series_div": time_div
    }
    return render(request, 'reports/bike-locations.html', context)
Esempio n. 8
0
def hist_plot(hist=None, edges=None, opts=None, **kwargs):
    """
  Create a Bokeh figure object and populate its histogram 
  plot propertie with the provided information. To create a 
  histogram plot, you actually need to the correct properties
  of the quad object from Bokeh. This method already does that 
  for you. It also already computes the correct values, and 
  create the bins correctly.

  :param ndarray hist: The hist output from numpy.histogram
  :param ndarray edges: The histogram edges output from numpy.histogram
  :param dict opts: The desired options of the plot.yaml in dictionary format
  :param kwargs: The desired options of the plot.yaml in directive format

  :return: A Bokeh figure object with the line properties filled
  :rtype: bokeh.Figure
  """
    # Define the figure options
    yopts = dict()
    if opts is not None:
        for opt in opts:
            yopts[opt] = opts[opt]
    if kwargs is not None:
        for opt in kwargs:
            yopts[opt] = kwargs[opt]
    fopts = handle_opts(def_fig_opts['histogram_plot'], yopts)
    # Check axis data
    if hist is None:
        plotLog.error("Please provide the proper hist parameter.")
        return 0
    if edges is None:
        plotLog.error("Please provide the proper edges parameter.")
        return 0
    # Create the figure image
    p = figure(title=fopts['title'],
               x_axis_type=fopts['x_axis']['type'],
               y_axis_type=fopts['y_axis']['type'],
               plot_width=fopts['fig_size'][0],
               plot_height=fopts['fig_size'][1])
    # Style the figure image
    p.grid.grid_line_alpha = fopts['dec']['grid']['line_alpha']
    p.xgrid.band_fill_alpha = fopts['dec']['x_grid']['band_alpha']
    p.xgrid.band_fill_color = color_theme[0]
    p.yaxis.axis_label = fopts['y_axis']['label']
    p.xaxis.axis_label = fopts['x_axis']['label']
    # Place the information on plot
    p.quad(top=hist,
           bottom=0,
           left=edges[:-1],
           right=edges[1:],
           fill_color=color_theme[fopts['color_index']],
           line_color="white",
           alpha=0.5)
    # Include some plot tools
    p.add_tools(LassoSelectTool())
    p.add_tools(HoverTool())
    return p
Esempio n. 9
0
def make_plot(store_now, store_future, ecom_zipcode_all):
    # Source: http://www.bigendiandata.com/2017-06-27-Mapping_in_Jupyter/

    from bokeh.io import output_file, output_notebook, show
    from bokeh.models import GMapOptions, ColumnDataSource, CategoricalColorMapper, HoverTool, LassoSelectTool
    from bokeh.palettes import RdBu3
    from bokeh.plotting import gmap

    map_options = GMapOptions(lat=42.37,
                              lng=-71.23,
                              map_type="roadmap",
                              zoom=10)

    plot = gmap(map_options=map_options,
                google_api_key='AIzaSyCrnuAv4K0j80AZzUsYFS2NwyY49-yMXRI',
                plot_width=780,
                plot_height=780,
                output_backend="webgl")
    plot.title.text = "PUMA Retail Store and Ecommerce Transactions"

    mapper = CategoricalColorMapper(
        factors=['Unreached', 'Reached', 'Future Reach'],
        palette=[RdBu3[1], RdBu3[0], RdBu3[2]])

    plot1 = plot.square(x="lng",
                        y="lat",
                        size=20,
                        color='blue',
                        source=store_now)
    plot2 = plot.square(x="lng",
                        y="lat",
                        size=20,
                        color='red',
                        source=store_future)
    plot3 = plot.circle(x="lng",
                        y="lat",
                        size='Size',
                        fill_color={
                            'field': 'inrange',
                            'transform': mapper
                        },
                        source=ecom_zipcode_all,
                        legend='inrange')

    tooltips1 = [("Ship To ZipCode", "@store_zip"),
                 ("Ship To City", "@in_city"),
                 ('Ecom Transactions', '@Transactions')]
    plot.add_tools(HoverTool(tooltips=tooltips1, renderers=[plot3]))

    tooltips3 = [("Store ZipCode", "@store_zip"), ("City located", "@in_city"),
                 ('Ecom Transactions in range', '@Transactions')]
    plot.add_tools(HoverTool(tooltips=tooltips3, renderers=[plot2]))

    plot.add_tools(LassoSelectTool())

    return plot
Esempio n. 10
0
    def generate_chart(self):
        """
        Description:

        -------------------------------------------
        Input:

        -------------------------------------------

        Ouput:
        """
        if self.color_palette is None:
            self.no_colors_set = True
            self.color_palette = Hot

        if len(self.title) == 0:
            self.title = ("Scatter plot for " + self.aggregate_col + " " +
                          self.aggregate_fn)

        self.chart = figure(
            title=self.title,
            toolbar_location="right",
            tools="pan, wheel_zoom, reset",
            active_scroll="wheel_zoom",
            active_drag="pan",
            x_range=self.x_range,
            y_range=self.y_range,
            width=self.width,
            height=self.height,
        )

        self.chart.add_tools(BoxSelectTool())
        self.chart.add_tools(LassoSelectTool())

        self.tile_provider = _get_provider(self.tile_provider)
        if self.tile_provider is not None:
            self.chart.add_tile(self.tile_provider)
            self.chart.axis.visible = False
        # reset legend and color_bar
        self.legend_added = False
        self.color_bar = None

        self.chart.xgrid.grid_line_color = None
        self.chart.ygrid.grid_line_color = None

        self.interactive_image = InteractiveImage(
            self.chart,
            self.generate_InteractiveImage_callback(),
            data_source=self.source,
            timeout=self.timeout,
            x_dtype=self.x_dtype,
            y_dtype=self.y_dtype,
        )

        if self.legend_added is False:
            self.render_legend()
Esempio n. 11
0
def line_plot(x_data=None, y_data=None, opts=None, **kwargs):
    """
  Create a Bokeh figure object and populate its line 
  propertie with the provided information.

  :param ndarray x_data: The ndarray with x axis values
  :param ndarray y_data: The ndarray with y axis values
  :param dict opts: The desired options of the *plot.yaml* in dictionary format
  :param kwargs: The desired options of the *plot.yaml* in directive format

  :return: A Bokeh figure object with the line properties filled
  :rtype: bokeh.Figure
  """
    # Define the figure options
    yopts = dict()
    if opts is not None:
        for opt in opts:
            yopts[opt] = opts[opt]
    if kwargs is not None:
        for opt in kwargs:
            yopts[opt] = kwargs[opt]
    fopts = handle_opts(def_fig_opts['line_plot'], yopts)
    # Check axis data
    if x_data is None:
        plotLog.warning("No x axis data was provided...")
    if y_data is None:
        plotLog.error("Please provide y axis data!!")
        return 0
    # Create the figure image
    p = figure(title=fopts['title'],
               x_axis_type=fopts['x_axis']['type'],
               y_axis_type=fopts['y_axis']['type'],
               plot_width=fopts['fig_size'][0],
               plot_height=fopts['fig_size'][1])
    # Style the figure image
    p.grid.grid_line_alpha = fopts['dec']['grid']['line_alpha']
    p.xgrid.band_fill_alpha = fopts['dec']['x_grid']['band_alpha']
    p.xgrid.band_fill_color = color_theme[0]
    p.yaxis.axis_label = fopts['y_axis']['label']
    p.xaxis.axis_label = fopts['x_axis']['label']
    # Place the information on plot
    p.line(x_data,
           y_data,
           legend_label=fopts['legend_label'],
           line_width=fopts['line_width'],
           color=color_theme[fopts['color_index']],
           muted_alpha=fopts['muted_alpha'],
           line_cap=fopts['line_cap'])
    p.add_tools(LassoSelectTool())
    p.add_tools(HoverTool())
    p.legend.location = fopts['legend']['location']
    p.legend.click_policy = fopts['legend']['click_policy']
    return p
Esempio n. 12
0
def product_page(request):
    template = 'products.html'
    
    car_price = []
    car_model = []

    cars = []
    price = []

    
    car_price = Products.objects.values_list('price',flat=True)
    car_model = Products.objects.values_list('name',flat=True)

    

    for prc in car_price:
        price.append(prc)

    for model in car_model:
        cars.append(model)


    print(price)
    print(cars)
    
    p = figure(x_range=cars,plot_height=450,title='Car Price in Dollar',toolbar_location="below",
                tools="pan,wheel_zoom,box_zoom,reset,hover,tap,crosshair"
    )

    source = ColumnDataSource(data=dict(cars=cars,price=price,color=Spectral6))
    p.add_tools(LassoSelectTool())
    p.add_tools(WheelZoomTool())

    p.vbar(x='cars',top='price',width=.8,color='color',legend='cars',source=source)
    p.legend.orientation = "horizontal"
    p.legend.location  = "top_center"

    p.xgrid.grid_line_color = "black"
    p.y_range.start = 0
    p.line(x=cars,y=price,color="black",line_width=2)

    script,div = components(p)

    print(script)
    print(div)
    context = {'script':script,'div':div}

    return render(request,template,context)
Esempio n. 13
0
def constructLines(directory, df, col1, col2, cachebust, redir_url, file):
    filename = str(file + "gating" + cachebust + ".html")

    output_file(os.path.join(directory, filename))
    print(df.columns)
    x = df[col1]
    y = df[col2]

    data = pd.DataFrame(dict(x=x, y=y))

    source = ColumnDataSource(data)

    handler = CustomJS(args=dict(source=source),
                       code="""
    var src_dat = source.selected['1d']['indices'];
    var conv_data = JSON.stringify(src_dat);
    console.log(conv_data);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", '{0}', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send("json=" + conv_data);
    var but = document.getElementsByClassName("bk-btn-success").item(0);
    but.innerHTML = "<p>Reload the page (auto reload in 5 seconds)</p>";
    console.log(but);""".format(redir_url, file))

    p = figure(plot_height=500,
               plot_width=1000,
               title=col1 + " vs " + col2 + ' Gating',
               x_axis_label=col1,
               y_axis_label=col2)
    p.scatter(x="x", y="y", source=source, fill_alpha=0.6, size=8)

    hover = HoverTool(tooltips=[(col1, "$x"), (col2, "$y")])

    p.add_tools(hover)
    p.add_tools(LassoSelectTool())
    p.add_tools(BoxSelectTool())

    bargraphs = []
    bargraphs.append(p)
    btn = Button(label='Submit selected points',
                 button_type="success",
                 callback=handler)
    bargraphs.append(btn)
    #df1[c[activegroup.data['source']]], df2[c[activegroup.data['source']]]
    #grid = gridplot([widgetbox(view_selection)], bargraphs, scatterplots)
    l = layout(bargraphs)
    save(l)
def empty_plot():
    p = figure(
        tools="hover,wheel_zoom,reset",
        width=FIGURE_WIDTH,
        height=FIGURE_HEIGHT,
        responsive=True,
        tags=["clusterPlot"],
        min_border_bottom=MIN_BORDER_BOTTOM,
        min_border_top=MIN_BORDER_TOP,
        min_border_left=MIN_BORDER_LEFT,
        min_border_right=MIN_BORDER_RIGHT,
    )

    # Ensure that the lasso only selects with mouseup, not mousemove.
    p.add_tools(LassoSelectTool(select_every_mousemove=False))

    # These turn off the x/y axis ticks
    p.axis.visible = None

    # These turn the major grid off
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None

    # Plot non-selected circles with a particular style using CIRCLE_SIZE and
    # 'color' list
    but_relevant = Button(label="Relevant", type="success")
    but_irrelevant = Button(label="Irrelevant", type="success")
    but_neutral = Button(label="Neutral", type="success")
    custom_tag_input = TextInput(value="Add custom tag...")
    custom_tag_select = Select(value="Custom tags", options=["Custom tags"])
    but_backward_crawl = Button(label="Backlinks", type="success")
    but_forward_crawl = Button(label="Forwardlinks", type="success")

    tags = hplot(but_relevant,
                 but_irrelevant,
                 but_neutral,
                 custom_tag_input,
                 custom_tag_select,
                 height=40)
    tags_crawl = hplot(but_backward_crawl, but_forward_crawl)
    layout = vform(p, tags, tags_crawl)

    # Combine script and div into a single string.
    plot_code = components(layout)
    return plot_code[0] + plot_code[1]
Esempio n. 15
0
def NLD_add_tools(plot):
    plot.add_tools(WheelZoomTool())
    plot.add_tools(ZoomInTool())
    plot.add_tools(ZoomOutTool())
    plot.add_tools(ResetTool())
    plot.add_tools(UndoTool())
    plot.add_tools(RedoTool())
    plot.add_tools(PanTool())
    plot.add_tools(TapTool())
    plot.add_tools(SaveTool())
    plot.add_tools(BoxSelectTool())
    plot.add_tools(LassoSelectTool())
    plot.add_tools(BoxZoomTool())
    # !!! Hover the node attributes !!!
    node_hover = HoverTool(tooltips=[('Name', '@index'), ('Degree', '@degree'),
                                    ('Min Weight', '@minweight'), ('Max Weight', '@maxweight'),
                                    ('Average Weight', '@avrweight'), ('Sum Weight', '@sumweight')])
    plot.add_tools(node_hover)
 def plot(self,  source1, source2, source3, source4, source5, source6, source7, source8, source9):
     a = self.a
     b = self.b
     hover = HoverTool(tooltips = [
                                     ("PCA1","($x)"),
                                     ("PCA2","($y)"),
                                     ("NAME","(@N)"),
                                     ])
     p = figure( title = "CHEMICAL SPACE BY MORGAN3 FP",
             x_axis_label = "PC 1 " + "("+str(a)+"%)", y_axis_label="PC 2 " + "("+str(b)+"%)",
             x_range = (-7,7), y_range = (-7,7), tools = [hover], plot_width = 1000, plot_height = 800)
     FDA_plot = p.circle(x = "x", y = "y", source = source1, color = "darkslateblue", size = 5)
     PPI_plot = p.circle(x = "x", y = "y", source = source2, color = "yellowgreen", size = 5)
     MACRO_plot = p.circle(x = "x", y = "y", source = source3, color ="lightsteelblue", size = 5)
     NP_plot = p.circle(x = "x", y = "y", source = source4, color = "olive", size = 5)
     PEP_FDA_plot = p.circle(x = "x", y = "y", source = source5, color ="darkslategray", size = 5)
     LIN_plot = p.circle(x = "x", y = "y", source = source6, color = "aquamarine", size = 5)
     LIN_NM_plot = p.circle(x = "x", y = "y", source = source7, color = "teal", size = 5)
     CYC_plot = p.circle(x = "x", y = "y", source = source8, color = "lightpink", size = 5)
     CYC_NM_plot = p.circle(x = "x", y = "y", source = source9, color = "mediumvioletred", size = 5)
     p.add_tools(LassoSelectTool(), ZoomInTool(), ZoomOutTool(), SaveTool(), PanTool())
     legend = Legend(items=[
                 ("FDA",     [FDA_plot]),
                 ("PPI",     [PPI_plot]),
                 ("MACRO",   [MACRO_plot]),
                 ("NP",      [NP_plot]),
                 ("PEP FDA", [PEP_FDA_plot]),
                 ("LIN",     [LIN_plot]),
                 ("LIN NM",  [LIN_NM_plot]),
                 ("CYC",     [CYC_plot]),
                 ("CYC NM",  [CYC_NM_plot]),
                 ], 
             location = "center", orientation = "vertical", click_policy = "hide"
         )
     p.add_layout(legend, place = 'right')
     p.xaxis.axis_label_text_font_size = "20pt"
     p.yaxis.axis_label_text_font_size = "20pt"
     p.xaxis.axis_label_text_color = "black"
     p.yaxis.axis_label_text_color = "black"
     p.xaxis.major_label_text_font_size = "18pt"
     p.yaxis.major_label_text_font_size = "18pt"
     p.title.text_font_size = "22pt"
     return p
def rijst_olie_chart(data_WFP):
    output_file("scatter_rice_and_oil.html")

    countries_names = ['Djibouti', 'Haiti', 'India', 'Iran(Islamic Republic of)', 'Jordan', 'Mozambique', 'Pakistan', 'Somalia', 'Swaziland' , 'Syrian Arab Republic', 'Tajikistan', 'Congo', 'Myanmar' ]
    countries = [1,2,3,45,6,7,8,9,10,11,12,13]

    #rijst_prijzen = []

    for x in countries_names:
        rijst_prijzen = (data_WFP.loc[(data_WFP['adm0_name'] == x) & (data_WFP['cm_name'] == 'Rice'), 'mp_price'])
        #rijst_prijzen.append(gemiddelde_rijst_prijs)

    #olie_prijzen = []

    for x in countries_names:
        olie_prijzen = (data_WFP.loc[(data_WFP['adm0_name'] == x) & (data_WFP['cm_name'] == 'Oil'), 'mp_price'])
        #olie_prijzen.append(gemiddelde_olie_prijs)
    
    olie_prijzen = olie_prijzen.to_frame()
    rijst_prijzen = rijst_prijzen.to_frame()

    olie_cds = ColumnDataSource(olie_prijzen)
    rijst_cds = ColumnDataSource(rijst_prijzen)
 

    s1 = figure(title = "Oil and Rice prices", x_axis_label = "Oil price", y_axis_label = "Rice price")

    s1.toolbar.tools = [PanTool(), ResetTool(), WheelZoomTool(), HoverTool(), LassoSelectTool(), BoxSelectTool()]

    # And let us just move it to the top instead of the side.
    s1.toolbar_location='above'
    #TOOLS = "hover,pan,wheel_zoom,box_zoom,reset,save" 
    hover = s1.select(dict(type=HoverTool))
    
    s1.hover.tooltips = [
    ("Country", "$index"),
    ("Oil price:", "$x"),
    ("Rice price", "$y"), 
    ]
    s1.add_tools(BoxSelectTool(dimensions="width"))   
    s1.scatter(x=olie_prijzen, y=rijst_prijzen, color="blue")
    show(s1)
    return
Esempio n. 18
0
 def plot(self, source1, source2, source3, source4, source5, source6, source7, source8, source9):
     hover = HoverTool(tooltips = [
         ("Similarity","($x)"),
         ("ECF","($y)"),
         ])
     p = figure(title = "MACCS keys FP/Tanimoto Similarity",
             x_axis_label = "Similarity", y_axis_label="Cumulative Distribution Function",
             x_range = (0,1), y_range = (0,1), tools=[hover], plot_width = 1000, plot_height = 800)
     FDA_plot = p.line(x = "x", y = "y", source = source1, line_width = 3, color="darkslateblue")
     PPI_plot = p.line(x = "x", y = "y", source = source2, line_width = 3, color="yellowgreen")
     MACRO_plot = p.line(x = "x", y = "y", source = source3, line_width = 3, color="lightsteelblue")
     NP_plot = p.line(x = "x", y = "y", source = source4, line_width = 3, color="olive")
     PEP_FDA_plot = p.line(x = "x", y = "y", source = source5, line_width = 3, color="darkslategray")
     LIN_plot = p.line(x = "x", y = "y", source = source6, line_width = 3, color="aquamarine")
     LIN_NM_plot = p.line(x = "x", y = "y", source = source7, line_width = 3, color="teal")
     CYC_plot = p.line(x = "x", y = "y", source = source8, line_width = 3, color="lightpink")
     CYC_NM_plot = p.line(x = "x", y = "y", source = source9, line_width = 3, color="mediumvioletred")
     p.add_tools(LassoSelectTool(), ZoomInTool(), ZoomOutTool(), SaveTool(), PanTool())
     
     legend = Legend(items=[
             ("FDA", [FDA_plot]),
             ("PPI", [PPI_plot]),
             ("MACRO", [MACRO_plot]),
             ("NP", [NP_plot]),
             ("PEP FDA", [PEP_FDA_plot]),
             ("LIN", [LIN_plot]),
             ("LIN NM", [LIN_NM_plot]),
             ("CYC", [CYC_plot]),
             ("CYC NM", [CYC_NM_plot]),
             ], 
             location = "center", orientation = "vertical", click_policy = "hide")
     p.add_layout(legend, place = 'right')
     p.xaxis.axis_label_text_font_size = "20pt"
     p.yaxis.axis_label_text_font_size = "20pt"
     p.xaxis.axis_label_text_color = "black"
     p.yaxis.axis_label_text_color = "black"
     p.xaxis.major_label_text_font_size = "18pt"
     p.yaxis.major_label_text_font_size = "18pt"
     p.title.text_font_size = "22pt"
     return p
Esempio n. 19
0
def programming(request):

    lang = ['Python', 'JavaScript', 'C#', 'PHP', 'C++', 'Java']
    counts = [25, 30, 8, 22, 12, 17]

    p = figure(x_range=lang,
               plot_height=450,
               title="Programming Languages Popularity",
               toolbar_location="below",
               tools="pan,wheel_zoom,box_zoom,reset, hover, tap, crosshair")

    # ColumnDataSource allows us to modify the data so each bar has a different color
    # Spectral6 is from the bokeh.palettes module
    # the 6 denotes we need 6 of the colors from Spectral colormap
    source = ColumnDataSource(
        data=dict(lang=lang, counts=counts, color=Spectral6))
    p.add_tools(LassoSelectTool())
    p.add_tools(WheelZoomTool())

    p.vbar(x='lang',
           top='counts',
           width=.8,
           color='color',
           legend="lang",
           source=source)
    p.legend.orientation = "horizontal"
    p.legend.location = "top_center"

    p.xgrid.grid_line_color = "black"
    p.y_range.start = 0
    p.line(x=lang, y=counts, color="black",
           line_width=2)  # line that touches all the points on the bars

    script, div = components(p)

    return render(request, 'programming.html', {'script': script, 'div': div})
# Populate the data with the dataframe
source = ColumnDataSource(data=load_data())

# Build out the hover tools
hover = HoverTool(tooltips=[
    ("title", "@title"),
    ("variety", "@variety"),
])

# Define the tool list as a list of the objects so it is easier to customize
# each object
TOOLS = [
    hover,
    BoxZoomTool(),
    LassoSelectTool(),
    WheelZoomTool(),
    PanTool(),
    ResetTool(),
    SaveTool()
]

# Build out the figure with the individual circle plots
p = figure(plot_height=600,
           plot_width=700,
           title="Australian Wine Analysis",
           tools=TOOLS,
           x_axis_label="points",
           y_axis_label="price (USD)",
           toolbar_location="above")
Esempio n. 21
0
def get_bokeh_image_selectable(url, field_name, pre_filled=None):
    """Get images to be rendered with bokeh

    Parameters
    ----------
    url: url of the image
    field_name: javscript field name where the number of drawn objects would be shown
    pre_filled: coordinates of any previously selected objects
    """
    if not pre_filled:
        x = []
        y = []
    else:
        x = pre_filled['x']
        y = pre_filled['y']

    # callback for LassoSelectTool
    source = ColumnDataSource(data=dict(x=x, y=y))
    callback = CustomJS(args=dict(source=source),
                        code="""
        // get data source from Callback args
        var data = source.data;
        
        // getting the geometry from cb_data parameter of Callback
        var geometry = cb_data['geometry'];
        
        // pushing Selected portions x, y coordinates for drawing border
        for (i=0; i < geometry.x.length; i++) {
            data['x'].push(geometry.x[i]);
            data['y'].push(geometry.y[i]);
        }
        
        // pushing NaN to separate the selected polygon from others
        // this will also be used for detecting how many polygons have been drawn
        data['x'].push(NaN);
        data['y'].push(NaN);
        
        // count number of selections
        var count = 0
        for (i=0; i < data['x'].length; i++) {
            if (isNaN(data['x'][i])) {
                count++;
            }
        }
        
        document.getElementById('field_name_span').innerHTML = count;
        document.getElementById('field_name_data_x').value = data['x'].join(',');
        document.getElementById('field_name_data_y').value = data['y'].join(',');
        
        if (count > 0) {
            document.getElementById('field_name_zero-button').classList.remove('visible');
        }
        
        // emit update of data source
        source.change.emit();
        """.replace('field_name', field_name))

    callback_reset = CustomJS(args=dict(source=source),
                              code="""
        // get data source from Callback args
        var data = source.data;
        
        // getting the double clicked/tapped coordinates
        var clicked_position = cb_obj;
        
        // clearing the lasso select areas on double click/tap on the figure
        var to_change = false;
        if (clicked_position.x >= 0 && clicked_position.x <= 1 && clicked_position.y >= 0 && clicked_position.y <= 1) {
            data['x'] = [];
            data['y'] = [];
            to_change = true;
        }
             
        if (to_change) {
            document.getElementById('field_name_span').innerHTML = 'None';
            document.getElementById('field_name_data_x').value = '';
            document.getElementById('field_name_data_y').value = '';
            document.getElementById('field_name_zero-button').classList.add('visible');
        }
        
        // emit update of data source
        source.change.emit();
        """.replace('field_name', field_name))

    # polygon to reflect selected area via LassoSelectTool
    polygon = Patch(
        x='x',
        y='y',
        fill_alpha=0.0,
        fill_color='#009933',
        line_width=1,
        line_alpha=1.0,
        line_color='#044A7E',
    )

    lasso_select = LassoSelectTool(callback=callback,
                                   select_every_mousemove=False)
    box_zoom = BoxZoomTool()
    pan = PanTool()
    wheel_zoom = WheelZoomTool()
    reset = ResetTool()

    tools = [
        box_zoom,
        lasso_select,
        wheel_zoom,
        pan,
        reset,
    ]

    # constructing bokeh figure
    plot = figure(
        x_range=(0, 1),
        y_range=(0, 1),
        width=display_image_size,
        height=display_image_size,
        logo=None,
        tools=tools,
        active_drag=lasso_select,
    )

    # adding image to the figure
    plot.image_url(
        url=[url],
        x=0,
        y=0,
        w=1,
        h=1,
        anchor="bottom_left",
    )

    # adding polygon to the figure
    plot.add_glyph(source,
                   polygon,
                   selection_glyph=polygon,
                   nonselection_glyph=polygon)
    # adding reset lasso selected areas on double click/tap
    plot.js_on_event(events.DoubleTap, callback_reset)

    plot.axis.visible = False
    plot.background_fill_color = "#000000"
    plot.background_fill_alpha = 0.8
    plot.grid.grid_line_color = None

    script, div = components(plot)
    return script, div
	def do_plot(self, simOutDir, plotOutDir, plotOutFileName, simDataFile, validationDataFile, metadata):
		if not os.path.isdir(simOutDir):
			raise Exception, "simOutDir does not currently exist as a directory"

		if not os.path.exists(plotOutDir):
			os.mkdir(plotOutDir)

		sim_data = cPickle.load(open(simDataFile))

		constraintIsKcatOnly = sim_data.process.metabolism.constraintIsKcatOnly

		mainListener = TableReader(os.path.join(simOutDir, "Main"))
		initialTime = mainListener.readAttribute("initialTime")
		time = mainListener.readColumn("time") - initialTime
		mainListener.close()

		massListener = TableReader(os.path.join(simOutDir, "Mass"))
		cellMass = massListener.readColumn("cellMass")
		dryMass = massListener.readColumn("dryMass")
		massListener.close()

		coefficient = dryMass / cellMass * sim_data.constants.cellDensity.asNumber(MASS_UNITS / VOLUME_UNITS)

		# read constraint data
		enzymeKineticsReader = TableReader(os.path.join(simOutDir, "EnzymeKinetics"))
		targetFluxes = (COUNTS_UNITS / MASS_UNITS / TIME_UNITS) * (enzymeKineticsReader.readColumn("targetFluxes").T / coefficient).T
		actualFluxes = (COUNTS_UNITS / MASS_UNITS / TIME_UNITS) * (enzymeKineticsReader.readColumn("actualFluxes").T / coefficient).T
		reactionConstraint = enzymeKineticsReader.readColumn("reactionConstraint")
		constrainedReactions = np.array(enzymeKineticsReader.readAttribute("constrainedReactions"))
		enzymeKineticsReader.close()

		targetFluxes = targetFluxes.asNumber(units.mmol / units.g / units.h)
		actualFluxes = actualFluxes.asNumber(units.mmol / units.g / units.h)

		targetAve = np.mean(targetFluxes[BURN_IN_STEPS:, :], axis = 0)
		actualAve = np.mean(actualFluxes[BURN_IN_STEPS:, :], axis = 0)

		kcatOnlyReactions = np.all(constraintIsKcatOnly[reactionConstraint[BURN_IN_STEPS:,:]], axis = 0)
		kmAndKcatReactions = ~np.any(constraintIsKcatOnly[reactionConstraint[BURN_IN_STEPS:,:]], axis = 0)
		mixedReactions = ~(kcatOnlyReactions ^ kmAndKcatReactions)

		thresholds = [2, 10]
		categorization = np.zeros(reactionConstraint.shape[1])
		categorization[actualAve == 0] = -2
		categorization[actualAve == targetAve] = -1
		for i, threshold in enumerate(thresholds):
			# categorization[targetAve / actualAve > threshold] = i + 1
			categorization[actualAve / targetAve > threshold] = i + 1

		# url for ecocyc to highlight fluxes that are 0 on metabolic network diagram
		siteStr = "https://ecocyc.org/overviewsWeb/celOv.shtml?zoomlevel=1&orgid=ECOLI"
		excluded = ['RXN0-2201', 'RXN-16000', 'RXN-12583', 'RXN-11496', 'DIMESULFREDUCT-RXN', '3.6.1.41-R[4/63051]5-NUCLEOTID-RXN'] # reactions not recognized by ecocyc
		rxns = []
		for i, reaction in enumerate(constrainedReactions):
			if actualAve[i] == 0:
				rxn = re.findall(".+RXN", reaction)
				if len(rxn) == 0:
					rxn = re.findall("RXN[^-]*-[0-9]+", reaction)
				if rxn[0] not in excluded:
					siteStr += "&rnids=%s" % rxn[0]
				rxns.append(rxn[0])
		# print siteStr

		csvFile = open(os.path.join(plotOutDir, plotOutFileName + ".tsv"), "wb")
		output = csv.writer(csvFile, delimiter = "\t")
		output.writerow(["ecocyc link:", siteStr])
		output.writerow(["Km and kcat", "Target", "Actual", "Category"])
		for reaction, target, flux, category in zip(constrainedReactions[kmAndKcatReactions], targetAve[kmAndKcatReactions], actualAve[kmAndKcatReactions], categorization[kmAndKcatReactions]):
			output.writerow([reaction, target, flux, category])

		output.writerow(["kcat only"])
		for reaction, target, flux, category in zip(constrainedReactions[kcatOnlyReactions], targetAve[kcatOnlyReactions], actualAve[kcatOnlyReactions], categorization[kcatOnlyReactions]):
			output.writerow([reaction, target, flux, category])

		if np.sum(mixedReactions):
			output.writerow(["mixed constraints"])
			for reaction, target, flux, category in zip(constrainedReactions[mixedReactions], targetAve[mixedReactions], actualAve[mixedReactions], categorization[mixedReactions]):
				output.writerow([reaction, target, flux, category])

		csvFile.close()

		targetAve += 1e-6
		actualAve += 1e-6

		axes_limits = [1e-7, 1e4]
		plt.figure(figsize = (8, 8))
		ax = plt.axes()
		plt.loglog(axes_limits, axes_limits, 'k')
		plt.loglog(targetAve, actualAve, "ob", markeredgewidth = 0.25, alpha = 0.25)
		plt.xlabel("Target Flux (mmol/g/hr)")
		plt.ylabel("Actual Flux (mmol/g/hr)")
		plt.minorticks_off()
		whitePadSparklineAxis(ax)
		ax.set_ylim(axes_limits)
		ax.set_xlim(axes_limits)
		ax.set_yticks(axes_limits)
		ax.set_xticks(axes_limits)

		exportFigure(plt, plotOutDir, plotOutFileName)
		plt.close("all")

		source = ColumnDataSource(
			data = dict(
				x = targetAve,
				y = actualAve,
				reactionName = constrainedReactions)
			)

		hover = HoverTool(
			tooltips = [
				("Reaction", "@reactionName"),
				]
			)

		TOOLS = [hover,
			BoxZoomTool(),
			LassoSelectTool(),
			PanTool(),
			WheelZoomTool(),
			ResizeTool(),
			UndoTool(),
			RedoTool(),
			"reset",
			]

		p1 = figure(x_axis_label = "Target",
			x_axis_type = "log",
			x_range = [min(targetAve[targetAve > 0]), max(targetAve)],
			y_axis_label = "Actual",
			y_axis_type = "log",
			y_range = [min(actualAve[actualAve > 0]), max(actualAve)],
			width = 800,
			height = 800,
			tools = TOOLS,
			)

		p1.scatter(targetAve, actualAve, source = source, size = 8)
		p1.line([1e-15, 10], [1e-15, 10], line_color = "red", line_dash = "dashed")


		## bar plot of error
		# sortedReactions = [constrainedReactions[x] for x in np.argsort(aveError)[::-1]]
		# aveError[np.log10(aveError) == -np.inf] = 0

		# source = ColumnDataSource(
		# 	data = dict(
		# 			x = sorted(relError, reverse = True),
		# 			reactionName = sortedReactions
		# 		)
		# 	)

		# p2 = Bar(data, values = "x")

		# hover2 = p2.select(dict(type=HoverTool))
		# hover2.tooltips = [("Reaction", "@reactionName")]

		## flux for each reaction
		hover2 = HoverTool(
			tooltips = [
				("Reaction", "@reactionName"),
				]
			)

		TOOLS2 = [hover2,
			BoxZoomTool(),
			LassoSelectTool(),
			PanTool(),
			WheelZoomTool(),
			ResizeTool(),
			UndoTool(),
			RedoTool(),
			"reset",
			]

		p2 = figure(x_axis_label = "Time(s)",
			y_axis_label = "Flux",
			y_axis_type = "log",
			y_range = [1e-8, 1],
			width = 800,
			height = 800,
			tools = TOOLS2,
			)

		colors = COLORS_LARGE
		nTimesteps = len(time[BURN_IN_STEPS:])
		x = time[BURN_IN_STEPS:]
		y = actualFluxes[BURN_IN_STEPS:, 0]
		reactionName = np.repeat(constrainedReactions[0], nTimesteps)

		source = ColumnDataSource(
			data = dict(
				x = x,
				y = y,
				reactionName = reactionName)
			)

		p2.line(x, y, line_color = colors[0], source = source)

		# Plot remaining metabolites onto initialized figure
		for m in np.arange(1, actualFluxes.shape[1]):
			y = actualFluxes[BURN_IN_STEPS:, m]
			reactionName = np.repeat(constrainedReactions[m], nTimesteps)

			source = ColumnDataSource(
				data = dict(
					x = x,
					y = y,
					reactionName = reactionName)
			)

			p2.line(x, y, line_color = colors[m % len(colors)], source = source)

		if not os.path.exists(os.path.join(plotOutDir, "html_plots")):
			os.makedirs(os.path.join(plotOutDir, "html_plots"))

		p = bokeh.io.vplot(p1, p2)
		bokeh.io.output_file(os.path.join(plotOutDir, "html_plots", plotOutFileName + ".html"), title=plotOutFileName, autosave=False)
		bokeh.io.save(p)
		bokeh.io.curstate().reset()
    box = BoxSelectTool(callback=boxtoolcallback)

    help_b = HelpTool(help_tooltip="""
        Button fuctions:\n

        Pan: Move around plot\n
        Lasso Select: View plot of artists in selection\n
        Box Select: Listen to all songs in selection\n
        Wheel Zoom: Resize plot\n
        Tap (Click): Listen to all overlaping songs\n
        Hover: Listen, view album cover and title\n
        Reset\n
        """)

    wheel_zoom = WheelZoomTool()
    lasso_select = LassoSelectTool()

    p2 = figure(width=700, height=700)
    p1 = figure(tools=[
        hover, lasso_select, "reset", tap, wheel_zoom, box, "pan", help_b
    ],
                toolbar_location="right",
                toolbar_sticky=False,
                title="Music Collections",
                width=700,
                height=700)
    p1.circle('x',
              'y',
              source=s1,
              size=7.3,
              fill_alpha=0.5,
Esempio n. 24
0
def programming(request):

    # language = ['Python', 'JavaScript', 'C#', 'PHP', 'C++', 'Java']
    # counts = [25, 30, 8, 22, 12, 17]
    histo = {
        "A": 21,
        "C": 0,
        "D": 26,
        "E": 37,
        "F": 14,
        "G": 28,
        "H": 3,
        "I": 39,
        "K": 43,
        "L": 44,
        "M": 11,
        "N": 19,
        "P": 9,
        "Q": 22,
        "R": 15,
        "S": 24,
        "T": 20,
        "V": 20,
        "W": 3,
        "Y": 10,
    }
    # fixed_list = [x.items() for x in list(histo)]
    # keys,values = zip(*fixed_list)
    keys, values = zip(*histo.items())
    language = list(keys)
    counts = list(values)
    print("language", language)
    print("counts", counts)

    p = figure(
        x_range=language,
        plot_height=1000,
        plot_width=1000,
        title="Aminoacid histogram",
        toolbar_location="below",
        tools="pan, wheel_zoom, box_zoom, reset, hover, tap, crosshair",
    )
    # Spectral =

    source = ColumnDataSource(data=dict(language=language, counts=counts, color=Category20[20]))
    p.add_tools(LassoSelectTool())
    p.add_tools(WheelZoomTool())

    p.vbar(
        x="language",
        top="counts",
        width=0.8,
        color="color",
        legend_group="language",
        source=source,
    )
    p.legend.orientation = "horizontal"
    p.legend.location = "top_center"

    # p.xgrid.grid_line_color = "black"
    p.y_range.start = 0
    # p.line(x=language, y= counts, color="black", line_width=2)
    # p.line(x=language, y= counts, color="black", line_width=2)

    script, div = components(p)

    return render(
        request,
        "graphs/programming.html",
        {"script": script, "div": div},
    )
Esempio n. 25
0
    def generate_chart(self):
        """
        Description:

        -------------------------------------------
        Input:

        -------------------------------------------

        Ouput:
        """
        if len(self.title) == 0:
            self.title = "Graph"
        self.x_range = (
            self.x_range[0] - self.node_point_size,
            self.x_range[1] + self.node_point_size,
        )
        self.y_range = (
            self.y_range[0] - self.node_point_size,
            self.y_range[1] + self.node_point_size,
        )
        self.chart = figure(
            toolbar_location="right",
            tools="pan, wheel_zoom, reset",
            active_scroll="wheel_zoom",
            active_drag="pan",
            x_range=self.x_range,
            y_range=self.y_range,
            width=self.width,
            height=self.height,
        )

        self.tile_provider = _get_provider(self.tile_provider)
        if self.tile_provider is not None:
            self.chart.add_tile(self.tile_provider)
            self.chart.axis.visible = False
        # reset legend and color_bar
        self.legend_added = False
        self.color_bar = None
        # loading icon from a url
        impath = (
            "https://raw.githubusercontent.com/rapidsai/cuxfilter/" +
            "branch-0.15/python/cuxfilter/charts/datashader/icons/graph.png")

        self.inspect_neighbors = CustomInspectTool(
            icon=load_image(impath),
            _active=True,
            tool_name="Inspect Neighboring Edges",
        )
        # loading icon from a url
        impath = (
            "https://raw.githubusercontent.com/rapidsai/cuxfilter/" +
            "branch-0.15/python/cuxfilter/charts/datashader/icons/XPan.png")
        self.display_edges = CustomInspectTool(icon=load_image(impath),
                                               _active=True,
                                               tool_name="Display Edges")

        def cb(attr, old, new):
            if new:
                self.connected_edges = calc_connected_edges(
                    self.interactive_image.kwargs["data_source"],
                    self.edges,
                    self.node_x,
                    self.node_y,
                    self.node_id,
                    self.edge_source,
                    self.edge_target,
                    self.edge_aggregate_col,
                    self.x_dtype,
                    self.y_dtype,
                    self.edge_render_type,
                    self.curve_params,
                )
            self.interactive_image.update_chart()

        self.display_edges.on_change("_active", cb)

        self.chart.add_tools(BoxSelectTool())
        self.chart.add_tools(LassoSelectTool())
        self.chart.add_tools(self.inspect_neighbors)
        self.chart.add_tools(self.display_edges)

        self.chart.xgrid.grid_line_color = None
        self.chart.ygrid.grid_line_color = None

        self.interactive_image = InteractiveImage(
            self.chart,
            self.generate_InteractiveImage_callback(),
            data_source=self.nodes,
            timeout=self.timeout,
            x_dtype=self.x_dtype,
            y_dtype=self.y_dtype,
        )

        if self.legend_added is False:
            self.render_legend()
Esempio n. 26
0
y = Select(title='Y-Axis', value=Y_INIT, options=continuous)
# link widget callback to update_plot()
y.on_change('value', update_plot)

# create dot color dropdown widget with "countable" var columns
color = Select(title='Color', value=COLOR_INIT, options=countable)
# link widget callback to update_plot()
color.on_change('value', update_plot)

# create image glyph toggle button
toggle = Toggle(label="Show Images", button_type="success")
# link button callback to toggle_callback()
toggle.on_click(toggle_callback)

# create lasso
lasso = LassoSelectTool()

# download button
button = Button(label="Download", button_type="success")

# button.callback = download_callback()
button.callback = CustomJS(args=dict(source=source),
                           code=open(join(dirname(__file__),
                                          "download.js")).read())

# add button and dropdown selections to a widgetbox
widgets = [x, y, color, toggle, button]
controls = widgetbox(widgets, sizing_mode='scale_both')

# overall layout with plot, widgetbox, and the table
plot = visualise()
Esempio n. 27
0
################################

src = ColumnDataSource(data=dict(Lat=[], Long=[], CreatedAt=[], tweet_text=[]))
# separate latitude and longitude points for the borders of the states.
state_xs = [us_states[code]["lons"] for code in us_states]
state_ys = [us_states[code]["lats"] for code in us_states]

hover2 = HoverTool(tooltips=[("Tweet", "@tweet_text")])

# init figure
plot_tweet = figure(
    title="Origin of Tweets",
    toolbar_location="left",
    plot_width=600,
    plot_height=400,
    tools=[hover2, LassoSelectTool(),
           ResetTool(), BoxZoomTool()])

# Draw state lines
plot_tweet.patches(state_xs,
                   state_ys,
                   fill_alpha=0.0,
                   line_color="#884444",
                   line_width=1.5)

plt_src = plot_tweet.circle(x='Long', y='Lat', size=4, color='Red', source=src)
plot_tweet.axis.visible = False
plot_tweet.xgrid.grid_line_color = None
plot_tweet.ygrid.grid_line_color = None

plot_scatter(relevant_tweet)
Esempio n. 28
0
def multline_plot(x_data=None, y_data=None, opts=None, **kwargs):
    """
  Create a Bokeh figure object and populate a line object
  of the bokeh library for each line data provided in the 
  y_data list parameter of this function.

  :param list x_data: The list with a ndarray data for the x axis of each line
  :param list y_data: The list with a ndarray data for the y axis of each line
  :param dict opts: The desired options of the *plot.yaml* in dictionary format
  :param kwargs: The desired options of the *plot.yaml* in directive format

  :return: A Bokeh figure object with the line properties filled
  :rtype: bokeh.Figure
  """
    # Define the figure options
    yopts = dict()
    if opts is not None:
        for opt in opts:
            yopts[opt] = opts[opt]
    if kwargs is not None:
        for opt in kwargs:
            yopts[opt] = kwargs[opt]
    fopts = handle_opts(def_fig_opts['multline_plot'], yopts)
    # Check axis data
    if x_data is None:
        plotLog.warning("No x axis data was provided...")
    if y_data is None:
        plotLog.error("Please provide y axis data!!")
        return 0
    # Create the figure image
    p = figure(title=fopts['title'],
               x_axis_type=fopts['x_axis']['type'],
               y_axis_type=fopts['y_axis']['type'],
               plot_width=fopts['fig_size'][0],
               plot_height=fopts['fig_size'][1])
    # Style the figure image
    p.grid.grid_line_alpha = fopts['dec']['grid']['line_alpha']
    p.xgrid.band_fill_alpha = fopts['dec']['x_grid']['band_alpha']
    p.xgrid.band_fill_color = color_theme[0]
    p.yaxis.axis_label = fopts['y_axis']['label']
    p.xaxis.axis_label = fopts['x_axis']['label']
    # Place the information on plot
    data, ind_track = x_data, 0
    if type(x_data) is not list:
        x_data = list()
        for k in range(len(y_data)):
            x_data.append(data)
    for x, y in zip(x_data, y_data):
        try:
            p.line(x,
                   y,
                   legend_label=fopts['legend_label'][ind_track],
                   line_width=fopts['line_width'][ind_track],
                   color=color_theme[fopts['color_index'][ind_track]],
                   muted_alpha=fopts['muted_alpha'],
                   line_cap=fopts['line_cap'])
        except:
            p.line(x,
                   y,
                   legend_label=fopts['legend_label'][ind_track],
                   line_width=fopts['line_width'][0],
                   color=color_theme[fopts['color_index'][ind_track]],
                   muted_alpha=fopts['muted_alpha'],
                   line_cap=fopts['line_cap'])
        ind_track += 1
    p.add_tools(LassoSelectTool())
    p.add_tools(HoverTool())
    p.legend.location = fopts['legend']['location']
    p.legend.click_policy = fopts['legend']['click_policy']
    return p
Esempio n. 29
0
for country in countries:
    legend_it = []
    products = df["food"][df["country"] == country].unique()
    f = figure(plot_width=1000, plot_height=650, title=country)
    for product, color in zip(products, my_palette):
        source = ColumnDataSource(name = 'data', data=dict(
            year = df["year"][(df["country"] == country) & (df["food"] == product)],
            price_per_unit = df["price_per_unit"][(df["country"] == country) & (df["food"] == product)]
        ))
        hover = HoverTool(tooltips=[
            ("year", "@year"),
            ("price_per_unit", "@price_per_unit")
        ], mode='vline')
        c = f.line(x='year', y='price_per_unit', line_width=2, color=color, legend=source.name, alpha=0.8, muted_color=color, muted_alpha=0.1, source=source)
        legend_it.append((product, [c]))
    f.toolbar.tools = [PanTool(), ResetTool(), WheelZoomTool(), hover, LassoSelectTool(), BoxSelectTool()]
    f.xaxis.axis_label="year"
    f.yaxis.axis_label="price per unit"
    legend = Legend(items=legend_it, location=(0, 10))
    legend.click_policy="hide"
    f.legend.visible = False
    f.add_layout(legend, "right")
    html = file_html(f, CDN, "CountryChart")
    fOut.write(html)
fOut.close()


# # creates scatterplots between the rate of change of the number of refugees
# # in percentage of the population of the country
# # and the rate of change of the average price per country
# fOut = open("Price_vs_refugee.html", "a")
Esempio n. 30
0
plot.legend.location = "bottom_right"
main_plot = row(plot, width=1100, height=1000)
main_plot.sizing_mode = "fixed"
inputs = column(*controls, width=240, height=1000)
inputs.sizing_mode = "fixed"
plots = column([hist_p, iqr_p, index_select, index_p, ewi_p, stats_table],
               width=450,
               height=1000)
plots.sizing_mode = "fixed"

print(stock_ohlc_df.isnull().values.any())
print(ohlc_df.isnull().values.any())
print(data.isnull().values.any())
print(hs.isnull().values.any())
print(returns_df.isnull().values.any())

print(stock_ohlc_df.dtypes)
print(ohlc_df.dtypes)
print(data.dtypes)
print(hs.dtypes)
print(returns_df.dtypes)

TOOLTIPS = [("symbol", "@name"), ("name", "@full_name"),
            ("category", "@category"), ("Sector", "@sector")]
plot.add_tools(HoverTool(tooltips=TOOLTIPS, renderers=[graph_renderer]),
               TapTool(), LassoSelectTool())

l = layout([[inputs, main_plot, plots]], sizing_mode="scale_both")

doc.add_root(l)