Exemplo n.º 1
0
def add_evt_plugins(obj, plot, hover_tool = False, copy_source=False):
    colors = ["red", "blue", "orange", "green"][:len(obj._plugins)]
    code = ""
    objs = {'plot': plot}
    for pl in obj._plugins:
        if copy_source:
            evts_source = ColumnDataSource(pl.evts_source.data)
        else:
            evts_source = pl.evts_source

        renderer = pl.add_glyph_to_plot(plot, hover_tool=hover_tool, evts_source=evts_source)
        # tap =plot.select(dict(type=TapTool))
        _code = pl.cb_code(obj.selected_symbol)
        if _code:
            code=_code
        objs['%s_source' % pl.name] = pl.evts_source

        if not getattr(obj,'%s_source' % pl.name):
            setattr(obj, '%s_source' % pl.name, pl.evts_source)

    callback = Callback(args=objs, code=code)

    tap = TapTool(
        # renderers=[renderer],
        action=callback)
    plot.add_tools(tap)
    tap.action = callback

    return plot
Exemplo n.º 2
0
def modify_doc(doc):
    def callback(event):
        selected = geosource.selected.indices
        yr = slider.value
        data = get_json(str(yr), selected[0])
        sgeosource.geojson = data[0]
        text_year.text = str(yr)
        text_state.text = data[1]
        text_beer.text = str(f"{data[2]:,d}")
        text_numco.text = str(numco(data[1], str(yr)))
        text_rank.text = str(rank(data[1], str(yr)))
        text_rate.text = str(rate(data[1], str(yr))) + '%'
        text_adults.text = str(adults(data[1])) + '%'
        text_capita.text = str(capita(data[1], str(yr)))
        company_selection.labels = company(data[1])
        initial_companies = [
            company_selection.labels[i] for i in company_selection.active
        ]
        src.data = make_dataset(initial_companies).data

        coordinates = xysource(data[1], df1)
        ycoordinate = [i / 100000 for i in coordinates[1]]
        statesource.data = dict(x=coordinates[0], y=ycoordinate)
        coordinatesplot = xysource(data[1], df4)
        numcosource.data = dict(x=coordinatesplot[0], y=coordinatesplot[1])
        splot.visible = True
        tplot.visible = True

    def xysource(state, df5):
        df2 = df5.loc[df5['states'] == state]
        df2 = df2.drop('states', 1)
        list_x = [int(i) for i in list(df2)]
        list_y = df2.values[0]
        return [list_x, list_y]

    flask_args = doc.session_context.request.arguments
    try:
        plot_title = flask_args.get('plot_title')[0].decode("utf-8")
    except:
        plot_title = "Sea Surface Temperature at 43.18, -70.43"
    try:
        dataset = flask_args.get('dataset')[0].decode("utf-8")
    except:
        dataset = "Dataset One"
    try:
        unit_type = flask_args.get('unit_type')[0].decode("utf-8")
    except:
        unit_type = "Celcius"
    try:
        theme = flask_args.get('theme')[0].decode("utf-8")
    except:
        theme = "default"

    gdf = gpd.GeoDataFrame.from_file(
        join(dirname(__file__), 'data/states', 'gz_2010_us_040_00_20m.shp'))[[
            'NAME', 'geometry', 'GEO_ID', 'CENSUSAREA'
        ]]

    yr = 2018
    gdf.columns = ['state', 'geometry', 'geo_id', 'censusarea']
    gdf = gdf.drop(gdf.index[26])
    gdf = gdf.drop(gdf.index[7])

    df_company = pd.DataFrame(get_data(query_craft),
                              columns=[
                                  'company', 'state', '2008', '2009', '2010',
                                  '2011', '2012', '2013', '2014', '2015',
                                  '2016', '2017', '2018'
                              ])
    df_companies = df_company.replace({"state": states})
    df_companies = df_companies.astype({
        "2008": int,
        "2009": int,
        "2010": int,
        "2011": int,
        "2012": int,
        "2013": int,
        "2014": int,
        "2015": int,
        "2016": int,
        "2017": int,
        "2018": int
    })

    df = pd.DataFrame(dframe(query_state),
                      columns=['states', '2008', '2009', '2010'])
    df1 = df.replace({"states": states})
    df1 = df1.astype({"2008": int, "2009": int, "2010": int})

    df_brew = pd.DataFrame(get_data(query_brew),
                           columns=[
                               'state', '2011', '2012', '2013', '2014', '2015',
                               '2016', '2017', '2018'
                           ])
    df_brew = df_brew.astype({
        "2011": int,
        "2012": int,
        "2013": int,
        "2014": int,
        "2015": int,
        "2016": int,
        "2017": int,
        "2018": int
    })

    df1 = df1.merge(df_brew, left_on='states', right_on='state')
    df1 = df1.drop('state', 1)

    df3 = pd.DataFrame(dframe(query_num_co),
                       columns=[
                           'states', '2008', '2009', '2010', '2011', '2012',
                           '2013', '2014', '2015', '2016', '2017'
                       ])
    df4 = df3.replace({"states": states})
    df4 = df4.astype({
        "2008": int,
        "2009": int,
        "2010": int,
        "2011": int,
        "2012": int,
        "2013": int,
        "2014": int,
        "2015": int,
        "2016": int,
        "2017": int
    })

    df_numco = pd.DataFrame(get_data(query_numco), columns=['state', '2018'])
    df_numco = df_numco.astype({"2018": int})

    df4 = df4.merge(df_numco, left_on='states', right_on='state')
    df4 = df4.drop('state', 1)

    df_pop = pd.DataFrame(get_data(query_population),
                          columns=['state', 'population', 'percent', 'adults'])
    df_pop = df_pop.astype({"percent": float, "adults": int})
    df_pop['percent'] = df_pop['percent'] * 100

    def numco(state, year):
        merged = df4.loc[df4['states'] == state]
        numco_text = merged.iloc[0][year]
        return numco_text

    def rank(state, year):
        df_rank = df4[['states', year]]
        df = df_rank.sort_values(year, ascending=False)
        df = df.reset_index(drop=True)
        idx = df.index[df['states'] == state]
        idx = idx[0] + 1
        return idx

    def rate(state, year):
        rate = (100 * df4.loc[df4['states'] == state][year].values[0]
                ) / df4[year].sum()
        return rate.round(2)

    def adults(state):
        adults = df_pop.loc[df_pop['state'] == state]['percent'].values[0]
        return adults.round(2)

    def capita(state, year):
        adults = df_pop.loc[df_pop['state'] == state]['adults'].values[0]
        num = numco(state, year)
        kf = 100000
        capita = (num / adults) * kf
        print(capita)
        return capita.round(1)

    def get_json(year, idx):
        df_yr = df1[['states', year]]
        df_yr.columns = ['states', 'year']
        merged = gdf.merge(df_yr, left_on='state', right_on='states')
        state_text = ''
        beer_text = ''

        if idx is not None:
            merged = merged.iloc[[idx]]
            state_text = merged.iloc[0]['state']
            beer_text = merged.iloc[0]['year']

        merged_json = json.loads(merged.to_json())
        json_data = json.dumps(merged_json)
        return [json_data, state_text, beer_text]

    #Input GeoJSON source that contains features for plotting.
    geosource = GeoJSONDataSource(geojson=get_json('2018', None)[0])

    #Define a sequential multi-hue color palette.
    palette = ['#084594', '#2171b5', '#4292c6', '#6baed6', '#9ecae1']
    #palette = d3['Category20b'][4]
    #Reverse color order so that dark blue is highest obesity.
    palette = palette[::-1]
    #Instantiate LinearColorMapper that linearly maps numbers in a range, into a sequence of colors.
    color_mapper = LinearColorMapper(palette=palette,
                                     low=0,
                                     high=2500000,
                                     nan_color='#d9d9d9')
    #Define custom tick labels for color bar.
    tick_labels = {
        '0': '0%',
        '5': '5%',
        '10': '10%',
        '15': '15%',
        '20': '20%',
        '25': '25%',
        '30': '30%',
        '35': '35%',
        '40': '>40%'
    }
    #Add hover tool

    hover = HoverTool(tooltips=[('State', '@state'),
                                ('brew', '@year' + " bbls")],
                      toggleable=False)
    #Create color bar.
    color_bar = ColorBar(color_mapper=color_mapper,
                         label_standoff=10,
                         width=590,
                         height=20,
                         border_line_color=None,
                         location=(0, 0),
                         orientation='horizontal',
                         major_label_overrides=tick_labels)
    #Create figure object.
    plot = figure(plot_width=640,
                  plot_height=420,
                  aspect_scale=0.85,
                  title='State Craft Beer Sales 2018')
    plot.add_tools(hover)

    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = None
    plot.background_fill_color = "#F5F5F5"
    #Add patch renderer to figure.
    plot.axis.visible = False
    initial_map = Patches(xs='xs',
                          ys='ys',
                          fill_color={
                              'field': 'year',
                              'transform': color_mapper
                          },
                          line_color='white',
                          line_width=0.15,
                          fill_alpha=0.5)
    selected_state = Patches(line_width=1,
                             fill_color={
                                 'field': 'year',
                                 'transform': color_mapper
                             },
                             line_color='#00022b',
                             fill_alpha=0.5)
    nonselected_state = Patches(line_width=0.15,
                                fill_color={
                                    'field': 'year',
                                    'transform': color_mapper
                                },
                                line_color='white',
                                fill_alpha=0.5)
    plot.add_glyph(geosource,
                   initial_map,
                   selection_glyph=selected_state,
                   nonselection_glyph=nonselected_state)
    #Specify figure layout.
    plot.add_tools(TapTool())
    plot.on_event(Tap, callback)
    plot.add_layout(color_bar, 'below')
    splot = figure(plot_width=320,
                   plot_height=300,
                   match_aspect=True,
                   title=None,
                   toolbar_location=None)
    tplot = figure(plot_width=320,
                   plot_height=300,
                   title=None,
                   toolbar_location=None,
                   tools='')
    sales_plot = figure(
        plot_width=320,
        plot_height=300,
        title="Sales 2008-2018",
        x_axis_label='Year',
        y_axis_label='Barrels of Craft Beer Produced (x 100 000)',
        toolbar_location=None)
    numco_plot = figure(plot_width=320,
                        plot_height=300,
                        title="Number of Companies 2008-2018",
                        x_axis_label='Year',
                        y_axis_label='Number of craft beer breweries',
                        toolbar_location=None)

    splot.axis.visible = False
    tplot.axis.visible = False
    splot.grid.visible = False
    tplot.grid.visible = False
    splot.outline_line_width = 0
    tplot.outline_line_width = 0
    #    splot.visible = False
    #    tplot.visible = False

    sgeosource = GeoJSONDataSource(geojson=get_json('2018', 2)[0])
    splot.patches('xs',
                  'ys',
                  source=sgeosource,
                  fill_color='#131E3A',
                  line_color='black',
                  line_width=0.25,
                  fill_alpha=1)
    year_source = ColumnDataSource({'year': ['2018']})
    text_year = Label(x=250,
                      y=250,
                      x_units='screen',
                      y_units='screen',
                      text='2018',
                      text_color='#131E3A',
                      text_font_size='16pt',
                      text_font_style='bold')
    text_state = Label(x=0,
                       y=250,
                       x_units='screen',
                       y_units='screen',
                       text='California',
                       text_color='#131E3A',
                       text_font_size='16pt',
                       text_font_style='bold')
    text_beer = Label(x=145,
                      y=220,
                      x_units='screen',
                      y_units='screen',
                      text='1,032,369',
                      text_color='#013240',
                      text_font_size='28pt',
                      text_font_style='bold',
                      text_font='Roboto',
                      text_baseline='middle',
                      text_align='right',
                      x_offset=25)
    text_val1 = Label(x=175,
                      y=222,
                      x_units='screen',
                      y_units='screen',
                      text='Barrels of Craft Beer',
                      text_color='#013220',
                      text_font_size='11pt',
                      text_font_style='normal',
                      text_font='Roboto')
    text_val2 = Label(x=175,
                      y=208,
                      x_units='screen',
                      y_units='screen',
                      text='Produced per Year',
                      text_color='#013220',
                      text_font_size='11pt',
                      text_font_style='normal',
                      text_font='Roboto')

    text_numco = Label(x=145,
                       y=180,
                       x_units='screen',
                       y_units='screen',
                       text='750',
                       text_color='#013240',
                       text_font_size='28pt',
                       text_font_style='bold',
                       text_font='Roboto',
                       text_baseline='middle',
                       text_align='right',
                       x_offset=25)

    text_val3 = Label(x=175,
                      y=182,
                      x_units='screen',
                      y_units='screen',
                      text='Craft Breweries',
                      text_color='#013220',
                      text_font_size='11pt',
                      text_font_style='normal',
                      text_font='Roboto')
    text_val4 = Label(x=175,
                      y=168,
                      x_units='screen',
                      y_units='screen',
                      text='Operating per Year',
                      text_color='#013220',
                      text_font_size='11pt',
                      text_font_style='normal',
                      text_font='Roboto')

    text_rank = Label(x=145,
                      y=140,
                      x_units='screen',
                      y_units='screen',
                      text='1',
                      text_color='#013240',
                      text_font_size='28pt',
                      text_font_style='bold',
                      text_font='Roboto',
                      text_baseline='middle',
                      text_align='right',
                      x_offset=25)

    text_val5 = Label(x=175,
                      y=142,
                      x_units='screen',
                      y_units='screen',
                      text='Most Craft',
                      text_color='#013220',
                      text_font_size='11pt',
                      text_font_style='normal',
                      text_font='Roboto')
    text_val6 = Label(x=175,
                      y=128,
                      x_units='screen',
                      y_units='screen',
                      text='Breweries in the US',
                      text_color='#013220',
                      text_font_size='11pt',
                      text_font_style='normal',
                      text_font='Roboto')

    text_rate = Label(x=145,
                      y=100,
                      x_units='screen',
                      y_units='screen',
                      text='5%',
                      text_color='#013240',
                      text_font_size='28pt',
                      text_font_style='bold',
                      text_font='Roboto',
                      text_baseline='middle',
                      text_align='right',
                      x_offset=25)

    text_val7 = Label(x=175,
                      y=102,
                      x_units='screen',
                      y_units='screen',
                      text='of US Craft Breweries',
                      text_color='#013220',
                      text_font_size='11pt',
                      text_font_style='normal',
                      text_font='Roboto')
    text_val8 = Label(x=175,
                      y=88,
                      x_units='screen',
                      y_units='screen',
                      text='',
                      text_color='#013220',
                      text_font_size='11pt',
                      text_font_style='normal',
                      text_font='Roboto')

    text_adults = Label(x=145,
                        y=60,
                        x_units='screen',
                        y_units='screen',
                        text='75%',
                        text_color='#013240',
                        text_font_size='28pt',
                        text_font_style='bold',
                        text_font='Roboto',
                        text_baseline='middle',
                        text_align='right',
                        x_offset=25)

    text_val9 = Label(x=175,
                      y=62,
                      x_units='screen',
                      y_units='screen',
                      text='21+ Adults in state',
                      text_color='#013220',
                      text_font_size='11pt',
                      text_font_style='normal',
                      text_font='Roboto')
    text_val10 = Label(x=175,
                       y=48,
                       x_units='screen',
                       y_units='screen',
                       text='',
                       text_color='#013220',
                       text_font_size='11pt',
                       text_font_style='normal',
                       text_font='Roboto')

    text_capita = Label(x=145,
                        y=20,
                        x_units='screen',
                        y_units='screen',
                        text='2.8%',
                        text_color='#013240',
                        text_font_size='28pt',
                        text_font_style='bold',
                        text_font='Roboto',
                        text_baseline='middle',
                        text_align='right',
                        x_offset=25)

    text_val11 = Label(x=175,
                       y=22,
                       x_units='screen',
                       y_units='screen',
                       text='Breweries per',
                       text_color='#013220',
                       text_font_size='11pt',
                       text_font_style='normal',
                       text_font='Roboto')
    text_val12 = Label(x=175,
                       y=8,
                       x_units='screen',
                       y_units='screen',
                       text='100,000 21+ Adults',
                       text_color='#013220',
                       text_font_size='11pt',
                       text_font_style='normal',
                       text_font='Roboto')

    coordinates = xysource('California', df1)
    ycoordinate = [i / 100000 for i in coordinates[1]]
    statesource = ColumnDataSource(dict(x=coordinates[0], y=ycoordinate))
    coordinatesplot = xysource('California', df4)
    numcosource = ColumnDataSource(
        dict(x=coordinatesplot[0], y=coordinatesplot[1]))
    sales_plot.line('x', 'y', source=statesource, line_width=3, line_alpha=0.6)
    numco_plot.line('x', 'y', source=numcosource, line_width=3, line_alpha=0.6)

    tplot.add_layout(text_year)
    tplot.add_layout(text_state)
    tplot.add_layout(text_beer)
    tplot.add_layout(text_val1)
    tplot.add_layout(text_val2)
    tplot.add_layout(text_numco)
    tplot.add_layout(text_val3)
    tplot.add_layout(text_val4)
    tplot.add_layout(text_rank)
    tplot.add_layout(text_val5)
    tplot.add_layout(text_val6)
    tplot.add_layout(text_rate)
    tplot.add_layout(text_val7)
    tplot.add_layout(text_val8)
    tplot.add_layout(text_adults)
    tplot.add_layout(text_val9)
    tplot.add_layout(text_val10)
    tplot.add_layout(text_capita)
    tplot.add_layout(text_val11)
    tplot.add_layout(text_val12)

    #    glyph = Text(x="x", y="y", text="text", angle=0.3, text_color="#96deb3")
    #    tplot.add_glyph(source, glyph)

    def update_plot(attr, old, new):
        yr = slider.value
        new_data = get_json(str(yr), None)[0]
        geosource.geojson = new_data
        plot.title.text = 'State Craft Beer Sales, %d' % yr

    # Make a slider object: slider
    slider = Slider(title='Year', start=2008, end=2018, step=1, value=2018)
    slider.on_change('value', update_plot)

    def make_dataset(company_list):
        xs = []
        ys = []
        colors = []
        labels = []
        #        src_circle = []
        for i, company in enumerate(company_list):
            df_co = df_companies.loc[df_companies['company'] == company]
            df_co = df_co.drop(['company', 'state'], axis=1)
            list_x = [int(i) for i in list(df_co)]
            list_y = df_co.values[0]
            xs.append(list_x)
            ys.append(list_y)
            colors.append(company_colors[i])
            labels.append(company)
        new_src = ColumnDataSource(data={
            'x': xs,
            'y': ys,
            'color': colors,
            'label': labels
        })
        #        for i in range(0, len(new_src.data['x'])):
        #            print (i)
        #            src_circle.append(ColumnDataSource(data={'x': new_src.data['x'][i], 'y': new_src.data['y'][i]}))
        return new_src

    def make_plot(src):
        p = figure(plot_width=800,
                   plot_height=420,
                   title='Craft Beer Sales by State Companies 2008-2018',
                   x_axis_label='Year',
                   y_axis_label='Barrels of Craft Beer Produced, bbls')
        p.multi_line('x',
                     'y',
                     color='color',
                     line_alpha=0.6,
                     hover_line_alpha=1.0,
                     legend='label',
                     line_width=3,
                     name='needshover',
                     source=src)
        #        for i in src_circle:
        #            p.circle('x', 'y', fill_color="white", color = 'grey', size=8, source = i)
        hover = HoverTool(names=['needshover'],
                          tooltips=[('Company', '@label'), ('Year', '$x{int}'),
                                    ('Barrels', '$data_y' + " bbls")])
        p.add_tools(hover)
        p.yaxis.formatter = NumeralTickFormatter(format="0.0 a")
        p.legend.location = "top_left"
        return p

    def update(attr, old, new):
        companies_to_plot = [
            company_selection.labels[i] for i in company_selection.active
        ]
        new_src = make_dataset(companies_to_plot)

        src.data.update(new_src.data)

    def company(state):
        available_companies = df_companies.loc[df_companies['state'] ==
                                               state][:]
        sort_companies = list(set(available_companies['company'][:20]))
        sort_companies.sort()
        return sort_companies

    company_selection = CheckboxGroup(labels=company('California'),
                                      active=[0, 1])
    company_selection.on_change('active', update)
    initial_companies = [
        company_selection.labels[i] for i in company_selection.active
    ]
    company_colors = Category20_16
    company_colors.sort()
    src = make_dataset(initial_companies)
    #    src_circle = make_dataset(initial_companies)[1]
    plot_state = make_plot(src)
    controls = WidgetBox(company_selection, width=200)
    l1 = row(controls, plot_state)

    if plot_title == '1':
        r = row([plot, tplot], sizing_mode='stretch_height')
        doc.add_root(column(r, l1))
    else:
        l = layout([[plot], [splot, tplot], [numco_plot, sales_plot]])
        doc.add_root(column(slider, l))

    doc.theme = Theme(filename=f"theme-{theme}.yaml")
Exemplo n.º 3
0
# load the data
dfcon, dfkoi, dfk2, dftoi = load_data()

# what to display when hovering over a data point
TOOLTIPS = [
    ("Planet", "@planet"),
    # only give the decimal and sig figs if needed
    ("Period", "@period{0,0[.][0000]} days"),
    ("Radius", "@radius{0,0[.][00]} Earth; @jupradius{0,0[.][0000]} Jup"),
    ("Discovered by", "@discovery")
]

# create the figure
fig = plotting.figure(x_axis_type='log', y_axis_type='log', tooltips=TOOLTIPS)
# allow for something to happen when you click on data points
fig.add_tools(TapTool())

# need to store min and max radius values to create the second axis
ymin = 1
ymax = 1
# save the output plots to rearrange them in the legend
glyphs = []

for ii, imiss in enumerate(missions):
    # select the appropriate set of planets for each mission
    if imiss == 'Other':
        good = ((~np.in1d(dfcon['pl_facility'], missions))
                & np.isfinite(dfcon['pl_rade'])
                & np.isfinite(dfcon['pl_orbper'])
                & dfcon['pl_tranflag'].astype(bool))
    else:
def plot_data(data_df, connections, year, geoSource_new, df):

    d_yr = df[df['Years'] == year]

    data_df_countries = d_yr.merge(data_df,
                                   left_on='Origin_Country',
                                   right_on='Country')
    #data_df_countries = node_dt #.drop_duplicates(subset=None, keep='first', inplace=True)
    connections_df = connections

    # node_source = ColumnDataSource(data_df_countries[["country_id","Country", "Longitude", "Latitude"]])

    node_source = ColumnDataSource(data_df_countries)
    edge_source = ColumnDataSource(connections_df[["start", "end"]])

    node_renderer = GlyphRenderer(data_source=node_source,
                                  glyph=node_glyph,
                                  selection_glyph=node_selection,
                                  nonselection_glyph=node_nonselection)

    ## Create edge_renderer
    edge_renderer = GlyphRenderer(data_source=edge_source,
                                  glyph=edge_glyph,
                                  hover_glyph=edge_hover,
                                  selection_glyph=edge_selection,
                                  nonselection_glyph=edge_nonselection)
    ## Create layout_provider
    graph_layout = dict(
        zip(data_df_countries.country_id.astype(str),
            zip(data_df_countries.Longitude, data_df_countries.Latitude)))
    layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

    ## Create graph renderer
    graph = GraphRenderer(edge_renderer=edge_renderer,
                          node_renderer=node_renderer,
                          layout_provider=layout_provider,
                          inspection_policy=NodesAndLinkedEdges(),
                          selection_policy=NodesAndLinkedEdges())

    plot = Plot(x_range=Range1d(-150, 150),
                y_range=Range1d(15, 75),
                plot_width=800,
                plot_height=600,
                background_fill_color=Set3_12[4],
                background_fill_alpha=0.2)

    plot.title.text = "Human Trafficing Visualization for " + str(year)

    plot.add_glyph(
        geoSource_new,
        Patches(xs='xs',
                ys='ys',
                line_color='grey',
                line_width=.2,
                fill_color={
                    'field': 'Tier',
                    'transform': mapper2
                },
                fill_alpha=0.40))

    plot.renderers.append(graph)
    plot.add_layout(LinearAxis(axis_label="Latitude"), "below")
    plot.add_layout(LinearAxis(axis_label="Longitude"), "left")

    # tooltips="""
    #                             <div>
    #                                 <div>
    #                                     <span style="font-size: 17px; font-weight: bold;">@desc</span>
    #                                     <span style="font-size: 15px; color: #966;">[$index]</span>
    #                                 </div>
    #                                 <div>
    #                                     <span style="font-size: 15px;">Country Involved</span>
    #                                     <span style="font-size: 10px; color: #696;">@Country</span>
    #                                 </div>
    #                             </div>
    #                             """,

    hover = HoverTool(
        show_arrow=True,  # tooltips=  # [("Country Involved: ", "@Country")],
        tooltips="""
                                <div>
                                    <div>
                                        <span style="font-size: 13px;">Country Info</span>
                                        <span style="font-size: 12px; color: #696;">@Destination_Country, @Type_Of_Trafficking</span>
                                    </div>
                                </div>
                                """,
        renderers=[node_renderer],
        name='Test')
    hover_no_tooltips = HoverTool(tooltips=None, renderers=[graph])
    box_zoom = BoxZoomTool()

    plot.add_tools(hover, hover_no_tooltips, box_zoom, TapTool(),
                   BoxSelectTool(), ResetTool(), WheelZoomTool())
    plot.toolbar.active_inspect = [hover, hover_no_tooltips]
    plot.toolbar.active_drag = box_zoom
    plot.outline_line_color = "navy"
    plot.outline_line_alpha = 0.3
    plot.outline_line_width = 1

    select_overlay = plot.select_one(BoxSelectTool).overlay

    select_overlay.fill_color = "firebrick"
    select_overlay.line_color = None

    zoom_overlay = plot.select_one(BoxZoomTool).overlay

    zoom_overlay.line_color = "olive"
    zoom_overlay.line_width = 3
    zoom_overlay.line_dash = "solid"
    zoom_overlay.fill_color = None

    plot.add_tile(STAMEN_TONER_LABELS)

    return plot
Exemplo n.º 5
0
    def __init__(self, n_rectangles=1000, clear_interval=20000, **kwargs):
        """
        kwargs are applied to the bokeh.models.plots.Plot constructor
        """
        self.n_rectangles = n_rectangles
        self.clear_interval = clear_interval
        self.last = 0

        self.source = ColumnDataSource(
            data=dict(start=[time() - clear_interval],
                      duration=[0.1],
                      key=['start'],
                      name=['start'],
                      color=['white'],
                      worker=['foo'],
                      y=[0],
                      worker_thread=[1],
                      alpha=[0.0]))

        x_range = DataRange1d(range_padding=0)
        y_range = DataRange1d(range_padding=0)

        self.root = figure(title="Task Stream",
                           id='bk-task-stream-plot',
                           x_range=x_range,
                           y_range=y_range,
                           toolbar_location="above",
                           x_axis_type='datetime',
                           min_border_right=35,
                           tools='',
                           **kwargs)
        self.root.yaxis.axis_label = 'Worker Core'

        rect = self.root.rect(source=self.source,
                              x="start",
                              y="y",
                              width="duration",
                              height=0.4,
                              fill_color="color",
                              line_color="color",
                              line_alpha=0.6,
                              fill_alpha="alpha",
                              line_width=3)
        rect.nonselection_glyph = None

        self.root.yaxis.major_label_text_alpha = 0
        self.root.yaxis.minor_tick_line_alpha = 0
        self.root.xgrid.visible = False

        hover = HoverTool(point_policy="follow_mouse",
                          tooltips="""
                <div>
                    <span style="font-size: 12px; font-weight: bold;">@name:</span>&nbsp;
                    <span style="font-size: 10px; font-family: Monaco, monospace;">@duration</span>
                    <span style="font-size: 10px;">ms</span>&nbsp;
                </div>
                """)

        tap = TapTool(callback=OpenURL(url='/profile?key=@name'))

        self.root.add_tools(hover, tap, BoxZoomTool(),
                            ResetTool(reset_size=False),
                            PanTool(dimensions="width"),
                            WheelZoomTool(dimensions="width"))
        if ExportTool:
            export = ExportTool()
            export.register_plot(self.root)
            self.root.add_tools(export)

        # Required for update callback
        self.task_stream_index = [0]
Exemplo n.º 6
0
    def make_plot(self,title, x, y):
        """

        :param title:
        :param x:
        :param y:
        :return:
        """

        print(title,x,y)


        t0 = time()

        pt = PanTool()
        lst = LassoSelectTool()
        pst = PolySelectTool()
        bst = BoxSelectTool()
        wzt = WheelZoomTool()
        tt = TapTool()
        st = SaveTool()
        ut = UndoTool()
        rt = RedoTool()

        p = figure(
            tools=[pt,lst,pst,bst,wzt,tt,st,ut,rt],
            plot_width=400,
            plot_height=400,
            title=self.initial_plot_2_data_mapper[x]+" vs. "+self.initial_plot_2_data_mapper[y],
            webgl=accelerator)
        # configure so that no drag tools are active
        p.toolbar.active_drag = pt

        # configure so that Bokeh chooses what (if any) scroll tool is active
        p.toolbar.active_scroll = wzt

        # configure so that a specific PolySelect tap tool is active
        p.toolbar.active_tap = tt

        p.xaxis.axis_label = self.initial_plot_2_data_mapper[x]
        p.yaxis.axis_label = self.initial_plot_2_data_mapper[y]
        c = p.circle(x=x, y=y, size=5, color="__COLOR__", alpha=.75, source=self.source,
                     hover_color='white', hover_alpha=1, hover_line_color='grey')
        c.data_source.on_change('selected', self.update)


        # Edge generator
        '''
        self.graph_set = [{i: [[1,0.15],[2,0.5],[3,0.99]] for i in range(self.n)}]

        self.edge_colors = qual_2_color(['g'+str(i) for i,_ in enumerate(self.graph_set)])

        self.edge_sources = [ColumnDataSource({'x0': [],
                                               'y0': [],
                                               'x1': [],
                                               'y1': [],
                                               'alpha': []})
                             for i in self.graph_set]

        self.edge_segments = [p.segment(x0='x0',
                                        y0='y0',
                                        x1='x1',
                                        y1='y1',
                                        color=self.edge_colors[i],
                                        alpha='alpha',
                                        line_width=3,
                                        #line_dash=[1,1],
                                        source=self.edge_sources[i])
                              for i, _ in enumerate(self.graph_set)]

        for i, _ in enumerate(self.graph_set):
            code1 = """
                    var links = %s;
                    var data = {'x0': [], 'y0': [], 'x1': [], 'y1': [], 'alpha': []};
                    var cdata = circle.get('data');
                    var indices = cb_data.index['1d'].indices;
                    for (i=0; i < indices.length; i++) {
                    ind0 = indices[i]
                    for (j=0; j < links[ind0].length; j++) {
                    ind1 = links[ind0][j][0];
                    w = links[ind0][j][1];
                    """ % self.graph_set[i]
            code2 = "data['x0'].push(cdata['" + x + "'][ind0]);\n" + \
                    "data['y0'].push(cdata['" + y + "'][ind0]);\n" + \
                    "data['x1'].push(cdata['" + x + "'][ind1]);\n" + \
                    "data['y1'].push(cdata['" + y + "'][ind1]);\n" + \
                    "data['alpha'].push([w]);\n"
            code3 = "}}segment.set('data', data);"
            code = code1 + code2 + code3
            callback = CustomJS(args={'circle': c.data_source,
                                      'segment': self.edge_segments[i].data_source},
                                code=code)
            p.add_tools(HoverTool(tooltips=None, callback=callback, renderers=[c]))
        '''

        p.select(BoxSelectTool).select_every_mousemove = False
        p.select(LassoSelectTool).select_every_mousemove = False



        # Plot Controls
        xdim_select = Select(title="X Dim", options=self.data_dict.keys(), value=self.initial_plot_2_data_mapper[x],width=400)
        ydim_select = Select(title="Y Dim", options=self.data_dict.keys(), value=self.initial_plot_2_data_mapper[y],width=400)
        xdim_select.on_change('value', self.plot_update)
        ydim_select.on_change('value', self.plot_update)
        remove = Button(label="Remove", button_type="danger",width=400)
        remove.on_click(partial(self.remove_plot,title,x,y))

        self.plot_control_dict[title] = {'x':xdim_select,
                                         'y':ydim_select,
                                         'xprev':xdim_select.value,
                                         'yprev':ydim_select.value,
                                         'figure':p,
                                         'tooltip':HoverTool(tooltips=self.tooltip_list,point_policy='snap_to_data',show_arrow=False)}
        # Give the hover tool a tool tip
        self.plot_control_dict[title]['figure'].add_tools(self.plot_control_dict[title]['tooltip'])


        # Form Tab
        plot_options = WidgetBox(xdim_select,ydim_select,remove)
        tab1 = Panel(child=self.plot_control_dict[title]['figure'], title=title,width=400,height=400)
        tab2 = Panel(child=plot_options, title="options",width=400,height=400)
        tabs = Tabs(tabs=[tab1, tab2],width=400,height=400)


        self.tab_list.append(tabs)
        self.circle_list.append(c)

        print('Plot Time: ' + str(time() - t0))

        return tabs, c
Exemplo n.º 7
0
def create_mmap_figure(mdate):
    df = mmap.get_data(mdate)
    TOOLTIPS = [("code", "@code"), ("(pday, profit)", "(@pday, @profit)")]
    TOOLS = [
        TapTool(),
        PanTool(),
        BoxZoomTool(),
        WheelZoomTool(),
        ResetTool(),
        BoxSelectTool(),
        HoverTool(tooltips=TOOLTIPS)
    ]
    p = figure(plot_height=800,
               plot_width=1300,
               x_axis_label='时间',
               y_axis_label='强度',
               tools=TOOLS,
               toolbar_location="above",
               title="活点地图")
    if df is None or df.empty: return p
    mdict = {
        'code': df.code.tolist(),
        'profit': df.profit.tolist(),
        'pday': df.pday.tolist()
    }
    global msource
    msource = ColumnDataSource(mdict)
    color_mapper = LinearColorMapper(palette="Viridis256",
                                     low=min(mdict['profit']),
                                     high=max(mdict['profit']))
    p.circle(x='pday',
             y='profit',
             color=transform('profit', color_mapper),
             size=5,
             alpha=0.6,
             source=msource)
    color_bar = ColorBar(color_mapper=color_mapper,
                         label_standoff=12,
                         location=(0, 0),
                         title='强度')
    p.add_layout(color_bar, 'right')
    callback = CustomJS(args=dict(msource=msource,
                                  tsource=tsource,
                                  mtable=mtable),
                        code="""
            var inds = cb_obj.indices;
            var d1 = msource.data;
            var d2 = tsource.data;
            d2['code'] = []
            d2['pday'] = []
            d2['profit'] = []
            for (var i = 0; i < inds.length; i++) {
                d2['code'].push(d1['code'][inds[i]])
                d2['profit'].push(d1['profit'][inds[i]])
                d2['pday'].push(d1['pday'][inds[i]])
            }
            tsource.change.emit();
            mtable.change.emit()
        """)
    msource.selected.js_on_change('indices', callback)
    return p
Exemplo n.º 8
0
# genre = Select(title="Genre", value="All", options=genre_tags)
# not working yet

graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0))

callback = CustomJS(args=dict(source=graph_renderer.node_renderer.data_source),
                    code="""
    console.log(cb_data.source)
    var inds = cb_data.source.selected['1d'].indices;
    var artist = cb_data.source.data.Img[inds]
    window.alert(artist);
    """)

node_hover_tool = HoverTool(tooltips=tips)
node_select_tool = TapTool(callback=callback)
plot.add_tools(node_hover_tool, WheelZoomTool(), PanTool(), ResetTool(),
               node_select_tool)

graph_renderer.node_renderer.glyph = Circle(size=node_size,
                                            fill_color=Spectral4[0])
graph_renderer.edge_renderer.glyph = MultiLine(line_color="black",
                                               line_alpha=0.6,
                                               line_width=1)
plot.renderers.append(graph_renderer)

# def select_tags():
#     genre_val = genre.value
#     selected = G.node
#     if genre_val != "All":
#         selected = selected[selected.Genre.str.contains(genre_val) == True]
Exemplo n.º 9
0
def metric_rank_bar_graph(exoplanet_array, tooltip_dict=dict()):
    '''Funtion to generate html for an interactive bokeh bar graph, specifically for metric score vs rank'''

    # append to tooltip arrays
    for planet in exoplanet_array:
        for prop, vals in tooltip_dict.items():
            vals.append(rgetattr(planet, prop))

    # axis scale
    x_axis_type = 'linear'
    y_axis_type = 'log'

    # create tooltip table
    tooltips = [('(rank, metric)', '(@rank, @decision_metric)')]
    for prop in tooltip_dict.keys():
        tooltips.append((prop, '@%s' % prop))

    # create plot figure
    plot = figure(
        x_axis_type=x_axis_type,
        y_axis_type=y_axis_type,
        plot_height=400,
        sizing_mode='stretch_width',
        tools=[
            PanTool(),
            BoxZoomTool(),
            WheelZoomTool(),
            TapTool(),
            UndoTool(),
            RedoTool(),
            CrosshairTool(),
            HoverTool(mode='vline'),
            SaveTool(),
            ResetTool()
        ],
        tooltips=tooltips,
        background_fill_alpha=0.7,
        border_fill_alpha=0.7,
    )

    # link points to exoplanet.eu
    url = 'http://www.exoplanet.eu/catalog/@name'
    taptool = plot.select(type=TapTool)
    taptool.callback = OpenURL(url=url.replace(' ', '_'))

    # label axes
    plot.xaxis.axis_label = 'Rank'
    plot.yaxis.axis_label = 'Decision Metric'
    fontsize = '12pt'
    plot.xaxis.axis_label_text_font_size = fontsize
    plot.yaxis.axis_label_text_font_size = fontsize

    # make data source
    source_dict = dict(
        rank=[i for i in range(1,
                               len(exoplanet_array) + 1)],
        decision_metric=[planet.decision_metric for planet in exoplanet_array],
    )
    source_dict.update(tooltip_dict)  # add tooltip info to data source
    source = ColumnDataSource(data=source_dict)

    # make colormap
    detection_methods = [
        'Primary Transit',
        'Radial Velocity',
        'Imaging',
        'Microlensing',
        'Timing',
        'Astrometry',
        'TTV',
        'Default',
        'Primary Transit, TTV',
        'Controversial',
    ]
    cmap = factor_cmap('detection_type',
                       palette=Category10[10],
                       factors=detection_methods)

    # plot graph
    plot.vbar(
        x='rank',
        top='decision_metric',
        color=cmap,
        bottom=1,  # so that log scale can work,
        width=0.9,
        legend_field='detection_type',
        source=source)

    # legend
    plot.legend.title = 'Detection method'
    plot.legend.location = 'top_right'
    plot.legend.background_fill_alpha = 0

    return file_html(gridplot([[plot]], sizing_mode='stretch_both'), CDN)
Exemplo n.º 10
0
def linked_scatter_graph(master_source_dict, xproperties, yproperties,
                         cproperties, sproperties, xlogs, ylogs, clogs, slogs,
                         errorbar_xs, errorbar_ys, x_hists, y_hists,
                         tooltip_list):
    '''Funtion to generate html for an interactive bokeh scatter/errorbar graph'''

    # copy source_dict to avoid overmapping
    source_dict = copy.deepcopy(master_source_dict)

    # size mapping (do before making the data source)
    for i, (sproperty, slog) in enumerate(zip(sproperties, slogs)):
        if sproperty == 'None':
            source_dict.update({'smap%i' % i: [4] * len(source_dict['name'])
                                })  # size 4 is default
        else:
            arr = source_dict[sproperty]
            if slog: arr = np.log(arr)
            source_dict.update({
                'smap%i' % i:
                np.nan_to_num(
                    np.multiply(np.subtract(arr, np.nanmin(arr)),
                                15 / np.nanmax(arr))).tolist()
            })

    # make data source
    source = ColumnDataSource(data=source_dict)

    plots = []
    for i in range(len(xproperties)):  # don't use i for loops inside this
        xproperty, yproperty, cproperty, sproperty, xlog, ylog, clog, slog, errorbar_x, errorbar_y, x_hist, y_hist = xproperties[
            i], yproperties[i], cproperties[i], sproperties[i], xlogs[
                i], ylogs[i], clogs[i], slogs[i], errorbar_xs[i], errorbar_ys[
                    i], x_hists[i], y_hists[i]

        if xproperty != 'None' and yproperty != 'None':
            # units
            units = [''] * 4
            properties = [xproperty, yproperty, cproperty, sproperty]
            for j, prop in enumerate(
                    properties):  # must use enumerate, not zip
                if prop != 'None':
                    if 'host.' in prop:
                        units[j] = Star.property_dict[prop.replace(
                            'host.', '')]
                    else:
                        units[j] = Exoplanet.property_dict[prop]
            (xunit, yunit, cunit, sunit) = (unit for unit in units)
            formatters = [''] * 4  # for datetime formatting in tooltips
            for j, unit in enumerate(units):
                if unit == 'date': formatters[j] = '{%F}'
                if unit == 'year': formatters[j] = '{%Y}'

            # axis scale
            if xlog: x_axis_type = 'log'
            else: x_axis_type = 'linear'
            if ylog: y_axis_type = 'log'
            else: y_axis_type = 'linear'
            if xunit == 'date' or xunit == 'year': x_axis_type = 'datetime'
            if yunit == 'date' or yunit == 'year': y_axis_type = 'datetime'

            # create tooltip table
            tooltips = [
                ('(%s, %s)' %
                 (xproperty.replace('.', '_'), yproperty.replace('.', '_')),
                 '(@{%s}%s, @{%s}%s)' %
                 (xproperty, formatters[0], yproperty, formatters[1])),
                ('(%s, %s)' %
                 (cproperty.replace('.', '_'), sproperty.replace('.', '_')),
                 '(@{%s}%s, @{%s}%s)' %
                 (cproperty, formatters[2], sproperty, formatters[3])),
            ]
            for prop in tooltip_list:
                tooltips.append((prop, '@%s' % prop))

            # create plot figure
            plot = figure(
                x_axis_type=x_axis_type,
                y_axis_type=y_axis_type,
                sizing_mode='stretch_both',
                tools=[
                    PanTool(),
                    BoxZoomTool(),
                    BoxSelectTool(),
                    LassoSelectTool(),
                    WheelZoomTool(),
                    TapTool(),
                    UndoTool(),
                    RedoTool(),
                    CrosshairTool(),
                    SaveTool(),
                    ResetTool(),
                    HoverTool(tooltips=tooltips,
                              formatters={
                                  '@{discovered}': 'datetime',
                                  '@{updated}': 'datetime'
                              })
                ],
                toolbar_location='above',
                # title=str(datetime.date.today()),
                background_fill_alpha=0.7,
                border_fill_alpha=0.7,
            )

            # invert scales for magnitudes
            if 'mag_' in xproperty: plot.x_range.flipped = True
            if 'mag_' in yproperty: plot.y_range.flipped = True

            # link points to exoplanet.eu
            url = 'http://www.exoplanet.eu/catalog/@name'
            taptool = plot.select(type=TapTool)
            taptool.callback = OpenURL(url=url.replace(' ', '_'))

            # label axes
            plot.xaxis.axis_label = xproperty.replace('_', ' ').replace(
                '.', ' ').capitalize() + ' (%s)' % xunit
            plot.yaxis.axis_label = yproperty.replace('_', ' ').replace(
                '.', ' ').capitalize() + ' (%s)' % yunit

            # font sizes
            fontsize = '12pt'
            plot.xaxis.axis_label_text_font_size = fontsize
            plot.yaxis.axis_label_text_font_size = fontsize

            # color mapping
            if cproperty == 'None': cmap = Category10[10][0]
            elif cproperty == 'detection_type':
                # detection type is categorical so needs special treatment
                detection_methods = [
                    'Primary Transit', 'Radial Velocity', 'Imaging',
                    'Microlensing', 'Timing', 'Astrometry', 'TTV', 'Default',
                    'Primary Transit, TTV', 'Controversial'
                ]
                cmap = factor_cmap('detection_type',
                                   palette=Category10[10],
                                   factors=detection_methods)

                # counts
                counts = {method: 0 for method in detection_methods}
                for j, method in enumerate(source_dict['detection_type']):
                    if np.isfinite(source_dict[xproperty][j]) and np.isfinite(
                            source_dict[yproperty][j]):
                        counts[method] += 1

                # need to create legend manually so we can place it outside the plot area
                # legend placement depends on whether histograms are present
                if y_hist:
                    blank = figure(
                        width_policy='min',
                        height_policy='min',
                        width=205,
                        height=290,
                        outline_line_color=None,
                        background_fill_alpha=0.7,
                        border_fill_alpha=0.7,
                    )
                    legend = categorical_legend(detection_methods,
                                                counts.values(),
                                                '',
                                                Category10[10],
                                                fig=blank)
                else:
                    legend = categorical_legend(detection_methods,
                                                counts.values(),
                                                '',
                                                Category10[10],
                                                fig=plot)
                    plot.add_layout(legend, 'right')
            else:
                if clog:
                    cmap = log_cmap(cproperty,
                                    palette=Turbo256,
                                    low=np.nanmin(source_dict[cproperty]),
                                    high=np.nanmax(source_dict[cproperty]))
                    color_bar = ColorBar(color_mapper=cmap['transform'],
                                         ticker=LogTicker(),
                                         width=8,
                                         location=(0, 0),
                                         background_fill_alpha=0)
                else:
                    cmap = linear_cmap(cproperty,
                                       palette=Turbo256,
                                       low=np.nanmin(source_dict[cproperty]),
                                       high=np.nanmax(source_dict[cproperty]))
                    color_bar = ColorBar(color_mapper=cmap['transform'],
                                         width=8,
                                         location=(0, 0),
                                         background_fill_alpha=0)
                plot.add_layout(color_bar, 'right')
                # bokeh does not have a native colorbar label item so we will use a plot title as a substitute
                plot.title.text = cproperty.replace('_', ' ').replace(
                    '.', ' ').capitalize() + ' (%s)' % cunit
                plot.title_location = 'right'
                plot.title.align = 'center'
                plot.title.text_font_size = fontsize
                plot.title.text_font_style = 'italic'

            # plot graph
            plot.scatter(
                xproperty,
                yproperty,
                color=cmap,
                size='smap%i' % i,
                source=source,
            )

            # errorbars
            if xproperty + '_error_min' in Exoplanet.property_dict or xproperty.replace(
                    'host.', '') + '_error_min' in Star.property_dict:
                wx = Whisker(
                    source=source,
                    dimension='width',
                    visible=errorbar_x,
                    base=yproperty,
                    upper=xproperty + '_error_max',
                    lower=xproperty + '_error_min',
                    line_color=cmap,
                    upper_head=None,
                    lower_head=None,
                )
                plot.add_layout(wx)
            if yproperty + '_error_min' in Exoplanet.property_dict or yproperty.replace(
                    'host.', '') + '_error_min' in Star.property_dict:
                wy = Whisker(
                    source=source,
                    dimension='height',
                    visible=errorbar_y,
                    base=xproperty,
                    upper=yproperty + '_error_max',
                    lower=yproperty + '_error_min',
                    line_color=cmap,
                    upper_head=None,
                    lower_head=None,
                )
                plot.add_layout(wy)

            # histograms
            full_colour = '#756bb1'
            sample_colour = '#74c476'
            if x_hist:
                # list setup
                full_list = source_dict[xproperty]
                short_list = [
                    xval for xval, yval in zip(source_dict[xproperty],
                                               source_dict[yproperty])
                    if not np.isnan(yval)
                ]
                min_ = np.nanmin(full_list)
                max_ = np.nanmax(full_list)

                # plot setup
                hxplot = figure(
                    x_range=plot.x_range,
                    x_axis_type=x_axis_type,
                    height=300,
                    sizing_mode='stretch_width',
                    background_fill_alpha=0.7,
                    border_fill_alpha=0.7,
                )
                hxplot.xaxis.axis_label = xproperty.replace('_', ' ').replace(
                    '.', ' ').capitalize() + ' (%s)' % xunit
                hxplot.yaxis.axis_label = 'Frequency'
                hxplot.xaxis.axis_label_text_font_size = fontsize
                hxplot.yaxis.axis_label_text_font_size = fontsize

                # bins
                if xlog:
                    bins = np.logspace(np.log10(min_), np.log10(max_), 100)
                else:
                    bins = np.linspace(min_, max_, 100)

                # full range histogram
                hist, edges = np.histogram(full_list, bins=bins)
                hxplot.quad(top=hist,
                            bottom=0,
                            left=edges[:-1],
                            right=edges[1:],
                            color=full_colour,
                            fill_alpha=0.5,
                            legend_label='All')

                # only plotted histogram
                hist, edges = np.histogram(short_list, bins=bins)
                hxplot.quad(top=hist,
                            bottom=0,
                            left=edges[:-1],
                            right=edges[1:],
                            color=sample_colour,
                            fill_alpha=0.5,
                            legend_label='Shown')

                # legend setup
                hxplot.legend.click_policy = 'hide'
                hxplot.legend.background_fill_alpha = 0

            if y_hist:
                # list setup
                full_list = source_dict[yproperty]
                short_list = [
                    yval for xval, yval in zip(source_dict[xproperty],
                                               source_dict[yproperty])
                    if not np.isnan(xval)
                ]
                min_ = np.nanmin(full_list)
                max_ = np.nanmax(full_list)

                # plot setup
                hyplot = figure(
                    y_range=plot.y_range,
                    y_axis_type=y_axis_type,
                    width=300,
                    sizing_mode='stretch_height',
                    background_fill_alpha=0.7,
                    border_fill_alpha=0.7,
                )
                hyplot.yaxis.axis_label = yproperty.replace('_', ' ').replace(
                    '.', ' ').capitalize() + ' (%s)' % yunit
                hyplot.xaxis.axis_label = 'Frequency'
                hyplot.xaxis.axis_label_text_font_size = fontsize
                hyplot.yaxis.axis_label_text_font_size = fontsize

                # bins
                if xlog:
                    bins = np.logspace(np.log10(min_), np.log10(max_), 100)
                else:
                    bins = np.linspace(min_, max_, 100)

                # full range histogram
                hist, edges = np.histogram(full_list, bins=bins)
                hyplot.quad(right=hist,
                            left=0,
                            top=edges[:-1],
                            bottom=edges[1:],
                            color=full_colour,
                            fill_alpha=0.5,
                            legend_label='All')

                # only plotted histogram
                hist, edges = np.histogram(short_list, bins=bins)
                hyplot.quad(right=hist,
                            left=0,
                            top=edges[:-1],
                            bottom=edges[1:],
                            color=sample_colour,
                            fill_alpha=0.5,
                            legend_label='Shown')

                # legend setup
                hyplot.legend.click_policy = 'hide'
                hyplot.legend.background_fill_alpha = 0

            # layouts
            if cproperty != 'detection_type':
                blank = None  # don't need this plot if no legend is present
            if x_hist and y_hist:
                layout = gridplot([[hxplot, blank], [plot, hyplot]],
                                  sizing_mode='stretch_both')
            elif x_hist:
                layout = gridplot([[hxplot], [plot]],
                                  sizing_mode='stretch_both')
            elif y_hist:
                layout = gridplot([[plot, hyplot, blank]],
                                  sizing_mode='stretch_both')
            else:
                layout = gridplot([[plot]], sizing_mode='stretch_both')
            plots.append(layout)

    # layout
    layout = column(row(plots), sizing_mode='stretch_both')

    return file_html(layout, CDN)
Exemplo n.º 11
0
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5)

    graph_renderer.inspection_policy = inspection_policy
    graph_renderer.selection_policy = selection_policy

    plot.renderers.append(graph_renderer)

    return plot

plot_1 = create_graph(nx.circular_layout, inspection_policy=NodesAndLinkedEdges(), scale=1, center=(0,0))
plot_1.title.text = "Circular Layout (NodesAndLinkedEdges inspection policy)"
plot_1.add_tools(HoverTool(tooltips=None))

plot_2 = create_graph(nx.spring_layout, selection_policy=NodesAndLinkedEdges(), scale=2, center=(0,0))
plot_2.title.text = "Spring Layout (NodesAndLinkedEdges selection policy)"
plot_2.add_tools(TapTool(), BoxSelectTool())

plot_3 = create_graph(nx.random_layout, inspection_policy=EdgesAndLinkedNodes(), center=(0,0))
plot_3.title.text = "Random Layout (EdgesAndLinkedNodes inspection policy)"
plot_3.add_tools(HoverTool(tooltips=None))

plot_4 = create_graph(nx.fruchterman_reingold_layout, selection_policy=EdgesAndLinkedNodes(), scale=2, center=(0,0), dim=2)
plot_4.title.text = "FR Layout (EdgesAndLinkedNodes selection policy)"
plot_4.add_tools(TapTool())

layout = Column(Row(plot_1, plot_2), Row(plot_3, plot_4))

doc = curdoc()
doc.add_root(layout)

show(layout)
Exemplo n.º 12
0
            fill_color="colors",
            line_color=None)
rect_renderer = plot.add_glyph(source, rect)

xaxis_above = CategoricalAxis(major_label_orientation=pi / 4)
plot.add_layout(xaxis_above, 'above')

xaxis_below = CategoricalAxis(major_label_orientation=pi / 4)
plot.add_layout(xaxis_below, 'below')

plot.add_layout(CategoricalAxis(), 'left')

url = "http://www.colors.commutercreative.com/@names/"
tooltips = """Click the color to go to:<br /><a href="{url}">{url}</a>""".format(
    url=url)

tap = TapTool(plot=plot, renderers=[rect_renderer], callback=OpenURL(url=url))
hover = HoverTool(plot=plot, renderers=[rect_renderer], tooltips=tooltips)
plot.tools.extend([tap, hover])

doc = Document()
doc.add_root(plot)

if __name__ == "__main__":
    doc.validate()
    filename = "colors.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "CSS3 Color Names"))
    print("Wrote %s" % filename)
    view(filename)
Exemplo n.º 13
0
# Add tiles
tile_provider = get_provider(Vendors.CARTODBPOSITRON)
p.add_tile(tile_provider)
print("HERE?")

# Have to add the patches after the tiles
input_areas = p.patches('xs',
                        'ys',
                        source=geosource,
                        fill_color='red',
                        line_color='gray',
                        line_width=0.25,
                        fill_alpha=.3)

taptool = TapTool(renderers=[input_areas])
hovertool = HoverTool(renderers=[input_areas], tooltips=[('Site', '@name')])

selected_patches = Patches(fill_color="yellow",
                           fill_alpha=.8,
                           line_width=1,
                           line_color="green")
input_areas.selection_glyph = selected_patches

geosource.selected.on_change('indices', tapselect_handler)

print("HERE?")

# CustomJS(code="""
# // comment....
# console.log("Somewhere to stop!");
Exemplo n.º 14
0
                y_range=DataRange1d(),
                map_options=map_options,
                title="India")

source = ColumnDataSource(lat_lon_df)

#circle = Circle(x="lon", y="lat", size=5, fill_color="blue", fill_alpha=0.7, line_color=None)
circle = Circle(x='lon', y='lat', size=5, fill_color='col_vals')

plot.add_glyph(source, circle)

plot.add_tools(
    PanTool(), WheelZoomTool(), BoxSelectTool(),
    HoverTool(tooltips=[('name', '@name'), ('No. of deps/week',
                                            '@num_deps'), ('Code', '@code')]),
    ResetTool(), TapTool())

import pickle
import numpy as np
from bokeh.charts import Bar, output_file, show, Dot
import pylab as pl
import seaborn as sbn
from bokeh import mpl as mpl
from bokeh.io import output_notebook, show
from bokeh.plotting import figure, show, output_file
from bokeh.models import FixedTicker, TickFormatter
import pandas as pd

dis_trains = pickle.load(open("data/dep_times_lat_lon.p", "rb"))

gradient = []
Exemplo n.º 15
0
    def __init__(self, scheduler, width=600, **kwargs):
        with log_errors():
            self.last = 0
            self.scheduler = scheduler
            self.source = ColumnDataSource({
                'nprocessing': [1, 2],
                'nprocessing-half': [0.5, 1],
                'nprocessing-color': ['red', 'blue'],
                'nbytes': [1, 2],
                'nbytes-half': [0.5, 1],
                'worker': ['a', 'b'],
                'y': [1, 2],
                'nbytes-color': ['blue', 'blue'],
                'bokeh_address': ['', '']
            })

            processing = figure(title='Tasks Processing',
                                tools='resize',
                                id='bk-nprocessing-plot',
                                width=int(width / 2),
                                **kwargs)
            processing.rect(source=self.source,
                            x='nprocessing-half',
                            y='y',
                            width='nprocessing',
                            height=1,
                            color='nprocessing-color')
            processing.x_range.start = 0

            nbytes = figure(title='Bytes stored',
                            tools='resize',
                            id='bk-nbytes-worker-plot',
                            width=int(width / 2),
                            **kwargs)
            nbytes.rect(source=self.source,
                        x='nbytes-half',
                        y='y',
                        width='nbytes',
                        height=1,
                        color='nbytes-color')
            nbytes.axis[0].ticker = BasicTicker(mantissas=[1, 256, 512],
                                                base=1024)
            nbytes.xaxis[0].formatter = NumeralTickFormatter(format='0.0 b')
            nbytes.xaxis.major_label_orientation = -math.pi / 12
            nbytes.x_range.start = 0

            for fig in [processing, nbytes]:
                fig.xaxis.minor_tick_line_alpha = 0
                fig.yaxis.visible = False
                fig.ygrid.visible = False

                tap = TapTool(callback=OpenURL(url='http://@bokeh_address/'))
                fig.add_tools(tap)

                fig.toolbar.logo = None
                fig.toolbar_location = None
                fig.yaxis.visible = False

            hover = HoverTool()
            hover.tooltips = "@worker : @nprocessing tasks.  Click for worker page"
            hover.point_policy = 'follow_mouse'
            processing.add_tools(hover)

            hover = HoverTool()
            hover.tooltips = "@worker : @nbytes bytes.  Click for worker page"
            hover.point_policy = 'follow_mouse'
            nbytes.add_tools(hover)

            self.processing_figure = processing
            self.nbytes_figure = nbytes

            processing.y_range = nbytes.y_range
            self.root = row(nbytes, processing, sizing_mode='scale_width')
Exemplo n.º 16
0
def dendrogram(D, figargs=None):
    '''Creates a dendrogram plot.
    This plot can show full structure of a given dendrogram.

    Args:
        D (henchman.selection.Dendrogram): An initialized dendrogram object

    Examples:
        >>> from henchman.selection import Dendrogram
        >>> from henchman.plotting import show
        >>> import henchman.plotting as hplot
        >>> D = Dendrogram(X)
        >>> plot = hplot.dendrogram(D)
        >>> show(plot)
    '''
    if figargs is None:
        return lambda figargs: dendrogram(D, figargs=figargs)
    G = nx.Graph()

    vertices_source = ColumnDataSource(
        pd.DataFrame({
            'index': D.columns.keys(),
            'desc': list(D.columns.values())
        }))
    edges_source = ColumnDataSource(
        pd.DataFrame(D.edges[0]).rename(columns={
            1: 'end',
            0: 'start'
        }))
    step_source = ColumnDataSource(
        pd.DataFrame({
            'step': [0],
            'thresh': [D.threshlist[0]],
            'components': [len(D.graphs[0])]
        }))

    G.add_nodes_from([str(x) for x in vertices_source.data['index']])
    G.add_edges_from(
        zip([str(x) for x in edges_source.data['start']],
            [str(x) for x in edges_source.data['end']]))

    graph_renderer = from_networkx(G,
                                   nx.circular_layout,
                                   scale=1,
                                   center=(0, 0))

    graph_renderer.node_renderer.data_source = vertices_source
    graph_renderer.node_renderer.view = CDSView(source=vertices_source)
    graph_renderer.edge_renderer.data_source = edges_source
    graph_renderer.edge_renderer.view = CDSView(source=edges_source)

    plot = Plot(plot_width=400,
                plot_height=400,
                x_range=Range1d(-1.1, 1.1),
                y_range=Range1d(-1.1, 1.1))
    plot.title.text = "Feature Connectivity"
    graph_renderer.node_renderer.glyph = Circle(size=5,
                                                fill_color=Spectral4[0])
    graph_renderer.node_renderer.selection_glyph = Circle(
        size=15, fill_color=Spectral4[2])
    graph_renderer.edge_renderer.data_source = edges_source
    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                                   line_alpha=0.6,
                                                   line_width=.5)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(
        line_color=Spectral4[2], line_width=3)
    graph_renderer.node_renderer.hover_glyph = Circle(size=5,
                                                      fill_color=Spectral4[1])
    graph_renderer.selection_policy = NodesAndLinkedEdges()
    graph_renderer.inspection_policy = NodesAndLinkedEdges()

    plot.renderers.append(graph_renderer)

    plot.add_tools(
        HoverTool(tooltips=[
            ("feature", "@desc"),
            ("index", "@index"),
        ]), TapTool(), BoxZoomTool(), SaveTool(), ResetTool())

    plot = _modify_plot(plot, figargs)

    if figargs['static']:
        return plot

    def modify_doc(doc, D, figargs):
        data_table = DataTable(source=step_source,
                               columns=[
                                   TableColumn(field='step', title='Step'),
                                   TableColumn(field='thresh', title='Thresh'),
                                   TableColumn(field='components',
                                               title='Components')
                               ],
                               height=50,
                               width=400)

        def callback(attr, old, new):
            try:
                edges = D.edges[slider.value]
                edges_source.data = ColumnDataSource(
                    pd.DataFrame(edges).rename(columns={
                        1: 'end',
                        0: 'start'
                    })).data
                step_source.data = ColumnDataSource({
                    'step': [slider.value],
                    'thresh': [D.threshlist[slider.value]],
                    'components': [len(D.graphs[slider.value])]
                }).data
            except Exception as e:
                print(e)

        slider = Slider(start=0,
                        end=(len(D.edges) - 1),
                        value=0,
                        step=1,
                        title="Step")
        slider.on_change('value', callback)

        doc.add_root(column(slider, data_table, plot))

    return lambda doc: modify_doc(doc, D, figargs)
Exemplo n.º 17
0
    def _make_graph_plot(self) -> Plot:
        """ Builds the graph portion of the final model.

        """
        import networkx as nx

        nodes = nx.nx_pydot.graphviz_layout(self._graph, prog="dot")
        node_x, node_y = zip(*nodes.values())
        models = [self._graph.nodes[x]["model"] for x in nodes]
        node_id = list(nodes.keys())
        node_source = ColumnDataSource({
            "x": node_x,
            "y": node_y,
            "index": node_id,
            "model": models
        })
        edge_x_coords = []
        edge_y_coords = []
        for start_node, end_node in self._graph.edges:
            edge_x_coords.extend([[nodes[start_node][0], nodes[end_node][0]]])
            edge_y_coords.extend([[nodes[start_node][1], nodes[end_node][1]]])
        edge_source = ColumnDataSource({
            "xs": edge_x_coords,
            "ys": edge_y_coords
        })

        p2 = Plot(outline_line_alpha=0.0)
        xinterval = max(max(node_x) - min(node_x), 200)
        yinterval = max(max(node_y) - min(node_y), 200)
        p2.x_range = Range1d(start=min(node_x) - 0.15 * xinterval,
                             end=max(node_x) + 0.15 * xinterval)
        p2.y_range = Range1d(start=min(node_y) - 0.15 * yinterval,
                             end=max(node_y) + 0.15 * yinterval)

        node_renderer = GlyphRenderer(
            data_source=node_source,
            glyph=Circle(x="x", y="y", size=15, fill_color="lightblue"),
            nonselection_glyph=Circle(x="x",
                                      y="y",
                                      size=15,
                                      fill_color="lightblue"),
            selection_glyph=Circle(x="x", y="y", size=15, fill_color="green"),
        )

        edge_renderer = GlyphRenderer(data_source=edge_source,
                                      glyph=MultiLine(xs="xs", ys="ys"))

        node_hover_tool = HoverTool(tooltips=[("id",
                                               "@index"), ("model", "@model")])
        node_hover_tool.renderers = [node_renderer]

        tap_tool = TapTool()
        tap_tool.renderers = [node_renderer]

        labels = LabelSet(
            x="x",
            y="y",
            text="model",
            source=node_source,
            text_font_size="8pt",
            x_offset=-20,
            y_offset=7,
        )

        help = Label(
            x=20,
            y=20,
            x_units="screen",
            y_units="screen",
            text_font_size="8pt",
            text_font_style="italic",
            text="Click on a model to see its attributes",
        )
        p2.add_layout(help)
        p2.add_layout(edge_renderer)
        p2.add_layout(node_renderer)
        p2.tools.extend(
            [node_hover_tool, tap_tool,
             BoxZoomTool(),
             ResetTool(),
             PanTool()])
        p2.renderers.append(labels)
        self._node_source = node_source
        self._edge_source = edge_source
        return p2
Exemplo n.º 18
0
proj_source = ColumnDataSource(dict(x=X[:, 0], y=X[:, 1], z=X_colors))
project_plot = figure(title=projection_selections.value,
                      tools=tools,
                      plot_width=300,
                      plot_height=300)
scatter_tap = project_plot.scatter('x',
                                   'y',
                                   marker='circle',
                                   size=10,
                                   fill_color='z',
                                   alpha=0.5,
                                   source=proj_source,
                                   legend=None)
project_plot.xaxis.axis_label = 'Dim 1'
project_plot.yaxis.axis_label = 'Dim 2'
taptool = TapTool()
project_plot.add_tools(taptool)

#Input text
text_review, words, word_embeddings = get_rawText_data(
    rawInput_selections.value, keys_raw, data_raw, testX, embed_mat)
w2v_labels, w2v_colors, _ = clustering.apply_cluster(
    np.array(word_embeddings),
    algorithm="KMeans - selected gate",
    n_clusters=int(clustering_selections[1].value),
    mode="wc")
rawInput_source = ColumnDataSource(dict(z=w2v_colors, w=words))

text_banner = Div(text=text_review, width=1300, height=100)
text_banner2 = Div(text=text_review, width=1300, height=100)
label_banner = Paragraph(
import panel as pn
from bokeh.palettes import Viridis256
from bokeh.models import LinearColorMapper, TapTool
from bokeh.sampledata.autompg import autompg_clean as df
from pcp import ParallelCoordinates

selection_line_color = {
    "field":
    df.columns[0],
    "transform":
    LinearColorMapper(palette=Viridis256,
                      low=df[df.columns[0]].min(),
                      high=df[df.columns[0]].max()),
}
wd = pn.widgets.DataFrame(df, sizing_mode="stretch_both", height=300)
pc = ParallelCoordinates(df,
                         drop=["name"],
                         selection_line_color=selection_line_color,
                         extra_kwargs=dict(extra_tools=[TapTool()]),
                         sizing_mode="stretch_both")
wd.link(pc, selection="selection", bidirectional=True)
template = pn.template.FastGridTemplate(title="Parallel Coordinates example")
template.sidebar.append(pc.controls()[0])
template.main[:2, :] = wd
template.main[2:6, :] = pc
template.servable()
        TableColumn(field="koi_score",
                    title="Disp Score",
                    formatter=NumberFormatter(format="0.00"))
    ]
    # Make the bokeh data table
    data_table = DataTable(source=source,
                           columns=columns,
                           height=300,
                           width=1000)

    # Do the Figure initially it is log period vs log planet radius
    # Include hovertool
    hover = HoverTool(tooltips=[("KOI", "@koi_number{0.00}")])

    data_figure = figure(height=600, width=1000,x_axis_label='Log Period [Day]', \
                    y_axis_label='Log Rp [Rearth]', tools=[hover, TapTool(), BoxZoomTool(), PanTool(), ZoomOutTool(), ZoomInTool(), ResetTool(), SaveTool()])
    data_figure.axis.axis_line_width = 3
    circle_handle = data_figure.circle(x='Logkoi_period',
                                       y='Logkoi_prad',
                                       source=source,
                                       size=10)
    data_figure.axis.axis_label_text_font_size = "20pt"
    data_figure.axis.major_label_text_font_size = "15pt"
    data_figure.axis.major_tick_line_width = 3
    xAxisHandle = data_figure.axis[0]
    yAxisHandle = data_figure.axis[1]
    # Include tap tool to open url with click on point
    taptool = data_figure.select(type=TapTool)
    taptool.callback = OpenURL(url="@koi_url")

    # START JAVASCRIPT literal code for handling figure data axis change
Exemplo n.º 21
0
def task_stream_figure(clear_interval="20s", **kwargs):
    """
    kwargs are applied to the bokeh.models.plots.Plot constructor
    """
    clear_interval = parse_timedelta(clear_interval, default="ms")

    source = ColumnDataSource(data=dict(
        start=[time() - clear_interval],
        duration=[0.1],
        key=["start"],
        name=["start"],
        color=["white"],
        duration_text=["100 ms"],
        worker=["foo"],
        y=[0],
        worker_thread=[1],
        alpha=[0.0],
    ))

    x_range = DataRange1d(range_padding=0)
    y_range = DataRange1d(range_padding=0)

    root = figure(name="task_stream",
                  title="Task Stream",
                  id="bk-task-stream-plot",
                  x_range=x_range,
                  y_range=y_range,
                  toolbar_location="above",
                  x_axis_type="datetime",
                  min_border_right=35,
                  tools="",
                  **kwargs)

    rect = root.rect(
        source=source,
        x="start",
        y="y",
        width="duration",
        height=0.4,
        fill_color="color",
        line_color="color",
        line_alpha=0.6,
        fill_alpha="alpha",
        line_width=3,
    )
    rect.nonselection_glyph = None

    root.yaxis.major_label_text_alpha = 0
    root.yaxis.minor_tick_line_alpha = 0
    root.yaxis.major_tick_line_alpha = 0
    root.xgrid.visible = False

    hover = HoverTool(
        point_policy="follow_mouse",
        tooltips="""
            <div>
                <span style="font-size: 12px; font-weight: bold;">@name:</span>&nbsp;
                <span style="font-size: 10px; font-family: Monaco, monospace;">@duration_text</span>
            </div>
            """,
    )

    tap = TapTool(callback=OpenURL(url="/profile?key=@name"))

    root.add_tools(
        hover,
        tap,
        BoxZoomTool(),
        ResetTool(),
        PanTool(dimensions="width"),
        WheelZoomTool(dimensions="width"),
    )
    if ExportTool:
        export = ExportTool()
        export.register_plot(root)
        root.add_tools(export)

    return source, root
Exemplo n.º 22
0
# tweet tags (topic, popularity, similarity)
tweet_tags = pandas.DataFrame(numpy.random.rand(len(tweet_list), 2),
                              columns={'x', 'y'})
tweet_tags['tweet_id'] = [item['id_str'] for item in tweet_list]

# build the plot
plot_source = ColumnDataSource(data=dict(
    x=tweet_tags['x'], y=tweet_tags['y'], tid=tweet_tags['tweet_id']))
hover = HoverTool(tooltips=[('index', '$index'), ('tweet_id', '@tid')])
p = figure(plot_width=500,
           tools=[
               PanTool(),
               WheelZoomTool(), hover,
               ResetTool(),
               TapTool(),
               LassoSelectTool()
           ])
p.circle('x', 'y', source=plot_source)
# scr, di = components(p)

plot_source2 = ColumnDataSource(data=dict(x=[], y=[]))
p2 = figure(plot_width=500, x_range=(0, 1), y_range=(0, 1))
p2.circle('x', 'y', source=plot_source2)
# scr2, di2 = components(p)

p3 = layouts.column(p, p2)
scr, di = components(p3)

plot_source.callback = CustomJS(args=dict(s2=plot_source2),
                                code="""
Exemplo n.º 23
0
    def setupMasterBoardWindow(self):
        #creates the main display window which shows squares and leds
        xRange = (-self.ledSize / 2,
                  6 * self.ledSpacing * self.numCols - self.ledSize / 2)
        yRange = (-self.ledSize / 2,
                  6 * self.ledSpacing * self.numRows - self.ledSize / 2)

        boardWindow = figure(plot_width=self.figureSize,
                             plot_height=self.figureSize,
                             x_range=xRange,
                             y_range=yRange,
                             toolbar_location=None,
                             name="board window",
                             tools="",
                             output_backend="webgl")

        boardWindow.grid.visible = False
        boardWindow.axis.visible = False

        ledXs = np.array([])
        ledYs = np.array([])

        for xInd in range(self.numCols):
            for yInd in range(self.numRows):
                x, y = self.generateLedCoords(self.ledSpacing, xInd, yInd)
                ledXs = np.append(ledXs, x)
                ledYs = np.append(ledYs, y)

        #draw the gridlines
        xTicks = np.linspace(xRange[0], xRange[1], self.numCols + 1)
        yTicks = np.linspace(yRange[0], yRange[1], self.numRows + 1)

        lineXs, lineYs = self.generateGridLineCoords(xTicks, yTicks)

        boardWindow.multi_line(xs=lineXs,
                               ys=lineYs,
                               line_color="#8073ac",
                               line_width=2)

        squareSizeMod = .9
        offset = 1 - squareSizeMod

        squareCoords = self.generateSquareCoords(self.numRows)
        squareXs = (squareCoords[:, 0])
        squareYs = (squareCoords[:, 1])

        # xRange = (offset,(self.squareSize * self.numRows) - offset)
        # yRange = (offset,(self.squareSize * self.numCols) - offset)

        self.leds = boardWindow.rect(x=ledXs,
                                     y=ledYs,
                                     width=self.ledSize,
                                     height=self.ledSize,
                                     color=self.ledColors,
                                     angle=0,
                                     height_units="data",
                                     fill_alpha=.5)

        self.squares = boardWindow.rect(x=squareXs,
                                        y=squareYs,
                                        width=self.squareSize * squareSizeMod,
                                        height=self.squareSize * squareSizeMod,
                                        color=self.squareColors,
                                        angle=0,
                                        height_units="data",
                                        fill_alpha=.5)

        #set these equal so the board doesn't go dark when a single led/square is clicked
        self.squares.nonselection_glyph = self.squares.selection_glyph
        self.leds.nonselection_glyph = self.leds.selection_glyph

        self.boardSelectTool = TapTool(renderers=[self.squares, self.leds])

        #set squares visible at start
        # self.squares.visible = False
        self.leds.visible = False

        boardWindow.add_tools(self.boardSelectTool)
        boardWindow.toolbar.active_tap = self.boardSelectTool

        self.boardWindow = boardWindow
Exemplo n.º 24
0
G = Graph()
G.linkNodes('Names_id_friends.csv')
#prop = G.CreateGraph()
#source = ColumnDataSource(data = G.get_Nodes_inSpace(prop))
#arrowSource = ColumnDataSource(G.get_Edges_inSpace(prop))

hovertool = HoverTool(
    tooltips=[('index',
               '@index'), ('friends',
                           '@friends'), ('avgCloseness', '@avgCloseness')])
f1 = figure(
    tools=[hovertool,
           WheelZoomTool(),
           ResetTool(),
           PanTool(),
           TapTool()],
    plot_width=1000,
    plot_height=900,
    title="NY MIST Network Graph")

#f1.add_tools(hovertool, WheelZoomTool(), ResetTool(), PanTool())
#f1.add_layout(Arrow(end=VeeHead(size=15), x_start='xs', y_start='ys', x_end='xe', y_end='ye', source=arrowSource, line_alpha=0.4))
#nodes = f1.circle('x', 'y', alpha=0.7, source=source, line_color=None, size=20, visible=False)

Gnx = G.CreateGraph(True)
prop = nx.spring_layout(Gnx)
source = ColumnDataSource(data=G.get_Nodes_inSpace(prop))
nodes = f1.circle('x',
                  'y',
                  alpha=0.7,
                  source=source,
Exemplo n.º 25
0
                  "rgb(0, 100, 120)", "green", "blue", "#2c7fb8", "#2c7fb8",
                  "rgba(120, 230, 150, 0.5)", "rgba(120, 230, 150, 0.5)"
              ]))

plot = MyPlot(gradient_angle=45)

circle = Circle(x="x",
                y="y",
                radius=0.2,
                fill_color="color",
                line_color="black")
circle_renderer = plot.add_glyph(source, circle)

plot.add_layout(LinearAxis(), 'below')
plot.add_layout(LinearAxis(), 'left')

tap = TapTool(renderers=[circle_renderer],
              callback=Popup(message="Selected color: @color"))
plot.add_tools(PanTool(), WheelZoomTool(), tap)

doc = Document()
doc.add_root(plot)

if __name__ == "__main__":
    doc.validate()
    filename = "custom.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Demonstration of user-defined models"))
    print("Wrote %s" % filename)
    view(filename)
Exemplo n.º 26
0
                y="y",
                radius=0.2,
                fill_color="color",
                line_color="black")
circle_renderer = plot.add_glyph(source, circle)

plot.add_layout(LinearAxis(), 'below')
plot.add_layout(LinearAxis(), 'left')

customjs = CustomJS(args=dict(source=source),
                    code="""
  const colors = source.selected.indices.map((i) => source.data["color"][i])
  window.alert("Selected colors: " + colors)
""")

tap = TapTool(renderers=[circle_renderer], callback=customjs)
plot.add_tools(PanTool(), WheelZoomTool(), tap)

doc = Document()
doc.add_root(plot)

if __name__ == "__main__":
    doc.validate()
    filename = "customjs.html"
    with open(filename, "w") as f:
        f.write(
            file_html(
                doc, INLINE,
                "Demonstration of custom callback written in TypeScript"))
    print("Wrote %s" % filename)
    view(filename)
Exemplo n.º 27
0
                     title="Time (in Days)",
                     width=500,
                     margin=(10, 10, 10, 20))
start_vals = [
    Sb[0] / 2.3, Eb[0], Ia_ukb[0], Ia_kb[0], Is_nhb[0], Is_hb[0], Rb[0] / 2.3,
    Db[0]
]
current_source = ColumnDataSource(data=dict(sizes=start_vals))
#updating the node sizes
graph_renderer.node_renderer.data_source.add(current_source.data['sizes'],
                                             'size')
graph_renderer.node_renderer.glyph = Circle(size='size', fill_color='color')

#when edge is hovered over, will display a description of the movement of individuals along that edge
hover_tool = HoverTool(tooltips=[("Path Movement", "@edge_names")])
plot.add_tools(hover_tool, TapTool(), BoxSelectTool(), ResetTool())

####### Bar Graph
proportion_pops = [
    Sb[0] / 1000, Eb[0] / 1000, Ia_ukb[0] / 1000, Ia_kb[0] / 1000,
    Is_nhb[0] / 1000, Is_hb[0] / 1000, Rb[0] / 1000, Db[0] / 1000
]
bar_source = ColumnDataSource(
    data=dict(tall=proportion_pops, names=class_names, colors=Colorblind8))
bargraph = figure(x_range=class_names,
                  y_range=Range1d(0, 1.04),
                  title="Proportion of Population in Each Class",
                  tools=("reset, box_zoom"),
                  height=600,
                  margin=(15, 10, 10, 10))
bargraph.vbar(x='names',
Exemplo n.º 28
0
def example_func_2():
    import math

    from bokeh.io import show, output_file
    from bokeh.plotting import figure
    from bokeh.models import GraphRenderer, StaticLayoutProvider, Oval
    from bokeh.palettes import Spectral11, Inferno256, Category20_20

    import networkx as nx
    from bokeh.models.graphs import from_networkx, NodesAndLinkedEdges, EdgesAndLinkedNodes

    from bokeh.models import Plot, Range1d, MultiLine, Circle, HoverTool, TapTool, BoxSelectTool
    from bokeh.palettes import Spectral4

    # N = 32 # 8
    # node_indices = list(range(N))
    # print(node_indices)
    box_limit = 2  # 1.1

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

    plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())

    # graph = GraphRenderer()
    g = nx.karate_club_graph()
    N = (len(g.nodes()))
    g_layout = nx.spring_layout(g)
    graph_layout = g_layout

    graph = from_networkx(g, g_layout, scale=2, center=(0, 0))

    colors = Category20_20 + Category20_20

    node_indices = list(range(N))

    graph.node_renderer.data_source.add(node_indices, 'index')
    graph.node_renderer.data_source.add(colors, 'color')

    graph.node_renderer.glyph = Oval(height=0.1,
                                     width=0.2,
                                     fill_color=Spectral4[0])  # 'color'
    graph.node_renderer.selection_glyph = Oval(height=0.1,
                                               width=0.2,
                                               fill_color=Spectral4[1])
    graph.node_renderer.hover_glyph = Oval(height=0.1,
                                           width=0.2,
                                           fill_color=Spectral4[2])

    graph.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                          line_alpha=0.8,
                                          line_width=5)
    graph.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2],
                                                    line_width=5)
    graph.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1],
                                                line_width=5)

    graph.selection_policy = NodesAndLinkedEdges()
    graph.inspection_policy = EdgesAndLinkedNodes()

    if True:
        if True:  # make edges only from node 0 to all others.
            graph.edge_renderer.data_source.data = dict(start=[0] * N,
                                                        end=node_indices)

        if False:  # change and make nodes positions on a circle
            ### start of layout code
            circ = [i * 2 * math.pi / N for i in node_indices]
            x = [math.cos(i) for i in circ]
            y = [math.sin(i) for i in circ]
            graph_layout = dict(zip(node_indices, zip(x, y)))
            graph.layout_provider = StaticLayoutProvider(
                graph_layout=graph_layout)

        ### Draw quadratic bezier paths
        def bezier(start, end, control, steps):
            return [(1 - s)**2 * start + 2 * (1 - s) * s * control + s**2 * end
                    for s in steps]

        xs, ys = [], []
        sx, sy = graph_layout[0]
        steps = [i / 100. for i in range(100)]
        # make run on all nodes. setting edges from [0] node to all others
        for node_index in node_indices:
            ex, ey = graph_layout[node_index]
            xs.append(bezier(sx, ex, 0, steps))
            ys.append(bezier(sy, ey, 0, steps))
        graph.edge_renderer.data_source.data['xs'] = xs
        graph.edge_renderer.data_source.data['ys'] = ys

    plot.renderers.append(graph)

    output_file("graph2.html")
    show(plot)
Exemplo n.º 29
0
    if len(content) == 0:
        break
    #     print(wordsResult[0])
    posWordsList.append(wordsResult[0])

posResult.close()

# -------------------- Setting a Plot option part --------------------

plot = Plot(plot_width=1000,
            plot_height=750,
            x_range=Range1d(-1.2, 1.2),
            y_range=Range1d(-1.2, 1.2))
plot.title.text = "My Positive Words Graph (hold 'shift' key for multi-clicking)"

plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())

# -------------------- Edge adding in Graph part --------------------

popular = dict()
G = nx.DiGraph()
for line in posWordsList:
    words = line.split()
    # adding edge
    G.add_edge(words[0], words[1])
    G.add_edge(words[1], words[2])
    # word-frequency
    for word in words:
        if word in popular.keys():
            popular[word] += 1
        else:
Exemplo n.º 30
0
    def __init__(self, scheduler, width=600, **kwargs):
        with log_errors():
            self.last = 0
            self.scheduler = scheduler
            self.source = ColumnDataSource({
                "memory": [1, 2],
                "memory-half": [0.5, 1],
                "memory_text": ["1B", "2B"],
                "utilization": [1, 2],
                "utilization-half": [0.5, 1],
                "worker": ["a", "b"],
                "gpu-index": [0, 0],
                "y": [1, 2],
                "escaped_worker": ["a", "b"],
            })

            memory = figure(title="GPU Memory",
                            tools="",
                            id="bk-gpu-memory-worker-plot",
                            width=int(width / 2),
                            name="gpu_memory_histogram",
                            **kwargs)
            rect = memory.rect(
                source=self.source,
                x="memory-half",
                y="y",
                width="memory",
                height=1,
                color="#76B900",
            )
            rect.nonselection_glyph = None

            utilization = figure(title="GPU Utilization",
                                 tools="",
                                 id="bk-gpu-utilization-worker-plot",
                                 width=int(width / 2),
                                 name="gpu_utilization_histogram",
                                 **kwargs)
            rect = utilization.rect(
                source=self.source,
                x="utilization-half",
                y="y",
                width="utilization",
                height=1,
                color="#76B900",
            )
            rect.nonselection_glyph = None

            memory.axis[0].ticker = BasicTicker(**TICKS_1024)
            memory.xaxis[0].formatter = NumeralTickFormatter(format="0.0 b")
            memory.xaxis.major_label_orientation = -math.pi / 12
            memory.x_range.start = 0

            for fig in [memory, utilization]:
                fig.xaxis.minor_tick_line_alpha = 0
                fig.yaxis.visible = False
                fig.ygrid.visible = False

                tap = TapTool(callback=OpenURL(
                    url="./info/worker/@escaped_worker.html"))
                fig.add_tools(tap)

                fig.toolbar.logo = None
                fig.toolbar_location = None
                fig.yaxis.visible = False

            hover = HoverTool()
            hover.tooltips = "@worker : @utilization %"
            hover.point_policy = "follow_mouse"
            utilization.add_tools(hover)

            hover = HoverTool()
            hover.tooltips = "@worker : @memory_text"
            hover.point_policy = "follow_mouse"
            memory.add_tools(hover)

            self.memory_figure = memory
            self.utilization_figure = utilization

            self.utilization_figure.y_range = memory.y_range
            self.utilization_figure.x_range.start = 0
            self.utilization_figure.x_range.end = 100
Exemplo n.º 31
0
    def process_file(self):
        potiron_path = potiron.potiron_path
        lentwo = False
        ck = self.red.sismember('CK', 'YES')
        for v in self.fieldvalues:
            # if any field value is in format 'value-protocol' (or 'value-all'), it means we want to display each protocol separatly
            if len(v.split('-')) >= 2:
                lentwo = True
        # Using the format 'value-protocol' is not possible if combined keys are not deployed in the current redis database
        if lentwo and not ck:
            sys.stderr.write('Combined keys are not used in this redis dataset')
            sys.exit(1)
        
        if not self.outputdir.endswith('/'):
            self.outputdir = "{}/".format(self.outputdir)
        if not os.path.exists(self.outputdir):
            os.makedirs(self.outputdir)
        # Definition of the protocols currently present in our dataset
        protocols = self.red.smembers('PROTOCOLS')
        
        # Define the strings used for legends, titles, etc. concerning fields
        field_string, field_in_file_name = field2string(self.field, potiron_path)
        
        field_data = create_dict(self.field, potiron_path)
        
        all_proto = False
        for fv in self.fieldvalues:
            v = fv.split('-')
            # If we want to display the values for all the procotols, we display the sum of all of them as well
            if len(v) >= 2 and (v[1] == '*' or v[1] == 'all'):
                all_proto = True
                self.fieldvalues.append(v[0])
        
        # Creation of the figure and the tools used on it
        namefile=self.output_name(field_in_file_name,lentwo, all_proto)
        
        # As displaying values for all the protocols may generate a lot of lines in the plot, 
        # We help users showing them the protocol when they have there cursor in the line
        if all_proto:
            hover = HoverTool(tooltips = [('count','@y'),('protocol','@prot')])
        else:
            hover = HoverTool(tooltips = [('count','@y')])
        taptool = TapTool()
        TOOLS = [hover,PanTool(),BoxZoomTool(),WheelZoomTool(), taptool, SaveTool(), ResetTool()]
        p = figure(width=self.plot_width,height=self.plot_height,tools=TOOLS)
        # Definition of some variables which will be used and modified with the iterations
        at_least_one = False
        days = calendar.monthrange(int(self.date[0:4]),int(self.date[4:6]))[1]
        maxVal = 0
        minVal = sys.maxsize
        maxDay = 0
        vlength = len(self.fieldvalues)
        actual_values = []
        nbLine = 0
#        day_string = "@x"
        for v in range(vlength): # For each selected field or occurrence
            value = self.fieldvalues[v].split('-')
            actual_field = value[0]
            if len(value) >= 2: # If we specified a or all protocol(s)
                protocol = value[1]
                if protocol == "*" or protocol == "all":
                    for prot in protocols:
                        score=[]
                        dayValue=[]
                        proto = prot.decode()
                        exists = False
                        keys = self.red.keys("{}:{}:{}*:{}".format(self.source,proto,self.date,self.field))
                        for k in sorted(keys):
                            redisKey = k.decode()
                            day = redisKey.split(':')[2][-2:]
                            countValue = self.red.zscore(redisKey, actual_field)
                            if countValue is not None:
                                exists = True
                                score.append(countValue)
                            else:
                                score.append(0)
                            dayValue.append(day)
                        if exists:
                            at_least_one = True
                            # We define the color of the line, draw it
                            color = palette[nbLine%10]
                            protos = []
                            for x in dayValue:
                                protos.append("{}_{}".format(x, proto))
                            prots = [proto] * len(score)
                            sourceplot = ColumnDataSource(data=dict(
                                    x = dayValue,
                                    y = score,
                                    protocol = protos,
                                    prot = prots
                                    ))
                            leg = def_legend(actual_field, proto, self.field, field_string, field_data)
                            p.line(x='x',y='y',legend=leg,line_color=color,line_width=2,source=sourceplot)
                            c = p.scatter(x='x',y='y',legend=leg,size=10,color=color,alpha=0.1,source=sourceplot)
                            taptool.renderers.append(c)     # In order to have the interaction on click
                            nbLine += 1
                            maxScore = max(score)       # Update the min and max scores scaling
                            if maxVal < maxScore:       # in order to define the lower and upper
                                maxVal = maxScore       # limits for the graph
                            minScore = min(score)
                            if minVal > minScore:
                                minVal = minScore
                            # Definition of the last day for which there is data to display
                            if int(dayValue[-1]) > maxDay:
                                maxDay = int(dayValue[-1])
                            actual_value = "{}-{}".format(actual_field, protocol)
                            actual_values.append(actual_value)
                else:
                    score=[]
                    dayValue=[]
                    exists = False
                    keys = self.red.keys("{}:{}:{}*:{}".format(self.source,protocol,self.date,self.field))
                    for k in sorted(keys):
                        redisKey = k.decode()
                        day = redisKey.split(':')[2][-2:]
                        countValue = self.red.zscore(redisKey, actual_field)
                        if countValue is not None:
                            exists = True
                            score.append(countValue)
                        else:
                            score.append(0)
                        dayValue.append(day)
                    if exists: # If at least one occurrence for the current value of field has been found
                        at_least_one = True
                        # We define the color of the line, draw it
                        color = palette[nbLine%10]
                        leg = def_legend(actual_field, protocol, self.field, field_string, field_data)
                        p.line(x=dayValue,y=score,legend=leg,line_color=color,line_width=2)
                        c = p.scatter(x=dayValue,y=score,legend=leg,size=10,color=color,alpha=0.1)
                        taptool.renderers.append(c)     # In order to have the interaction on click
                        nbLine += 1
                        maxScore = max(score)       # Update the min and max scores scaling
                        if maxVal < maxScore:       # in order to define the lower and upper
                            maxVal = maxScore       # limits for the graph
                        minScore = min(score)
                        if minVal > minScore:
                            minVal = minScore
                        # Definition of the last day for which there is data to display
                        if int(dayValue[-1]) > maxDay:
                            maxDay = int(dayValue[-1])
                        actual_value = "{}-{}".format(actual_field, protocol)
                        actual_values.append(actual_value)
            else: # on the other case, we don't split informations for each protocol
                score=[]
                dayValue=[]
                exists = False
                # If combined keys are used, we must by the way take data from all the keys (i.e for each protocol)
                if ck:
                    for d in range(1,days+1): # For each day with data stored in redis
                        exists_day = False
                        day = format(d, '02d')
                        countValue = 0
                        keys = self.red.keys("{}:*:{}{}:{}".format(self.source,self.date,day,self.field))
                        for k in keys:
                            redisKey = k.decode()
                            tmpscore = self.red.zscore(redisKey, actual_field)
                            countValue += tmpscore if tmpscore is not None else 0
                            exists_day = True
                        if exists_day:
                            if countValue > 0:
                                exists = True
                            score.append(countValue)
                            dayValue.append(day)
                else: # When combined keys are not used, we only need to read the scores for each day
                    keys = self.red.keys("{}:{}*:{}".format(self.source,self.date,self.field))
                    for k in sorted(keys):
                        redisKey = k.decode()
                        day = redisKey.split(':')[2][-2:]
                        countValue = self.red.zscore(redisKey, actual_field)
                        if countValue is not None:
                            exists = True
                            score.append(countValue)
                        else:
                            score.append(0)
                        dayValue.append(day)
                if exists: # If at least one occurrence for the current value of field has been found
                    at_least_one = True
                    # We define the color of the line, draw it
                    color = palette[nbLine%10]
                    leg = def_legend(actual_field, None, self.field, field_string, field_data)
                    if all_proto:
                        protos = []
                        for x in dayValue:
                            protos.append(x)
                        prots = ['all protocols'] * len(score)
                        sourceplot = ColumnDataSource(data=dict(
                                x = dayValue,
                                y = score,
                                protocol = protos,
                                prot = prots
                                ))
                        p.line(x='x',y='y',legend=leg,line_color=color,line_width=2,source=sourceplot)
                        c = p.scatter(x='x',y='y',legend=leg,size=10,color=color,alpha=0.1,source=sourceplot)
                    else:
                        p.line(x=dayValue,y=score,legend=leg,line_color=color,line_width=2)
                        c = p.scatter(x=dayValue,y=score,legend=leg,size=10,color=color,alpha=0.1)
                    taptool.renderers.append(c)     # In order to have the interaction on click
                    nbLine += 1
                    maxScore = max(score)       # Update the min and max scores scaling
                    if maxVal < maxScore:       # in order to define the lower and upper
                        maxVal = maxScore       # limits for the graph
                    minScore = min(score)
                    if minVal > minScore:
                        minVal = minScore
                    # Definition of the last day for which there is data to display
                    if int(dayValue[-1]) > maxDay:
                        maxDay = int(dayValue[-1])
                    actual_value = "{}".format(actual_field)
                    actual_values.append(actual_value)
        if at_least_one: # If at least one value has been found in redis with our selection
            if lentwo: # Defines the name of the files to call with a click on a point in the plot
                taptool.callback = OpenURL(url="{}_{}_with-protocols_{}-{}[email protected]".format(self.source,
                                           field_in_file_name,self.date[0:4],self.date[4:6]))
            else:
                taptool.callback = OpenURL(url="{}_{}_{}-{}[email protected]".format(self.source,
                                           field_in_file_name,self.date[0:4],self.date[4:6]))
            output_file("{}.html".format(namefile), title=namefile.split("/")[-1])
            # Definition of some parameters of the graph
            fieldvalues_string = plot_annotation(self.field, potiron_path, actual_values, field_string, field_data)
            p.title.text = "Number of {} {}seen each day in {} {}".format(field_string, 
                                      fieldvalues_string, potiron.year[self.date[4:6]], self.date[0:4])
            p.yaxis[0].formatter = BasicTickFormatter(use_scientific=False)
            p.xaxis.axis_label = "Days"
            p.yaxis.axis_label = "Count"
            p.legend.location = "top_left"
            p.legend.click_policy = "hide"
            # Definition of some parameters for the logo
            with Image.open(self.logofile) as im :
                im_width, im_height = im.size
            xdr = maxDay + 1
            upper_space = 10
            if nbLine > 2:
                upper_space *= (nbLine / 2)
            ydrmax = maxVal + maxVal * upper_space / 100
            ydrmin = minVal - maxVal * 5 / 100
            p.x_range = Range1d(0,xdr)
            p.y_range = Range1d(ydrmin,ydrmax)
            height = (ydrmax - ydrmin) / self.logo_y_scale
            width = xdr / ((self.logo_y_scale * im_height * self.plot_width) / (im_width * self.plot_height))
            p.image_url(url=[self.logofile],x=[xdr],y=[ydrmax-ydrmax*2/100],w=[width],h=[height],anchor="top_right")
            # Process the graph
            save(p)
            if self.links:
                export_csv = export_csv_all_days_per_month.Export_Csv(self.red, self.source, self.date, self.field, 10, ['-1'], self.outputdir, True, True, self.logofile, ck, lentwo)
                ck = True if red.sismember('CK', 'YES') else False
                export_csv.process_all_files()
        else:
            print ("There is no such value for a {} you specified: {}".format(field_string,self.fieldvalues))
Exemplo n.º 32
0
    <span style="font-size: 10px; color: #666;">(@Abbrev)</span>
</div>
<div>
    <span style="font-size: 17px; font-weight: bold;">@Time{0.00}</span>&nbsp;
    <span style="font-size: 10px; color: #666;">@Year</span>
</div>
<div style="font-size: 11px; color: #666;">@{MetersBack}{0.00} meters behind</div>
"""

plot.add_tools(HoverTool(tooltips=tooltips, renderers=[medal]))

from bokeh.models import CustomJS
open_url = CustomJS(args=dict(source=source),
                    code="""
    for (const index of source.inspected._1d.indices) {
        const name = source.data["Name"][index]
        const url = "http://en.wikipedia.org/wiki/" + encodeURIComponent(name)
        window.open(url)
    }
""")

#open_url = OpenURL(url="http://en.wikipedia.org/wiki/@Name")
plot.add_tools(
    TapTool(callback=open_url, renderers=[medal], behavior="inspect"))

legend = Legend(
    items=[LegendItem(label=dict(field="Medal"), renderers=[medal])],
    location="center_left")  # TODO: click_policy="hide"
plot.add_layout(legend)

save(plot, "sprint.html", INLINE, plot.title.text)