Exemplo n.º 1
0
    def populate_glyphs(self):
        self.plot.renderers=[]
        self.plot.tools=[]
        if self._show_counties:
            print "showing you the counties"
            #datasource = ColumnDataSource(county_data)
            #apatch = Patches(xs=county_xs, ys=county_ys, fill_color='white')
            #apatch = Patches(xs='xs', ys='ys', fill_color='colors', fill_alpha="alpha")
            apatch = Patches(xs='xs', ys='ys', fill_color='thecolors', fill_alpha='alpha')
            self.plot.add_glyph(self.county_source, apatch, name='counties')

        if self._show_hotels:
            print "showing you the hotels"
            circle2 = Circle(x="lon", y="lat", size=10, fill_color="fill2", fill_alpha=1.0, line_alpha=0.0)
            circle = Circle(x="lon", y="lat", size=10, fill_color="fill", fill_alpha=1.0, line_color="black")
            #print "source is ", self.source['lon'], self.source['lat'], self.source['f1ll']
            self.plot.add_glyph(self.source, circle, nonselection_glyph=circle2, name='hotels')
            #county_xs, county_ys = get_some_counties()

        rndr = self.plot.renderers[-1]
        pan = PanTool()
        wheel_zoom = WheelZoomTool()
        box_select = BoxSelectTool()
        box_select.renderers = [rndr]
        tooltips = "@name"
        tooltips = "<span class='tooltip-text'>@names</span>\n<br>"
        tooltips += "<span class='tooltip-text'>Reviews: @num_reviews</span>"
        hover = HoverTool(tooltips=tooltips, names=['hotels'])
        tap = TapTool(names=['hotels'])
        self.plot.add_tools(pan, wheel_zoom, box_select, hover, tap)
        overlay = BoxSelectionOverlay(tool=box_select)
        self.plot.add_layout(overlay)
Exemplo n.º 2
0
    def __init__(self, scheduler, width=800, **kwargs):
        self.scheduler = scheduler
        self.names = [
            'worker', 'ncores', 'cpu', 'memory', 'memory_limit',
            'memory_percent', 'num_fds', 'read_bytes', 'write_bytes',
            'cpu_fraction'
        ]

        table_names = [
            'worker', 'ncores', 'cpu', 'memory', 'memory_limit',
            'memory_percent', 'num_fds', 'read_bytes', 'write_bytes'
        ]

        self.source = ColumnDataSource({k: [] for k in self.names})

        columns = {
            name: TableColumn(field=name, title=name.replace('_percent', ' %'))
            for name in table_names
        }

        formatters = {
            'cpu': NumberFormatter(format='0.0 %'),
            'memory_percent': NumberFormatter(format='0.0 %'),
            'memory': NumberFormatter(format='0 b'),
            'memory_limit': NumberFormatter(format='0 b'),
            'read_bytes': NumberFormatter(format='0 b'),
            'write_bytes': NumberFormatter(format='0 b'),
            'num_fds': NumberFormatter(format='0'),
            'ncores': NumberFormatter(format='0')
        }

        table = DataTable(
            source=self.source,
            columns=[columns[n] for n in table_names],
            row_headers=False,
            reorderable=True,
            sortable=True,
            width=width,
        )

        for name in table_names:
            if name in formatters:
                table.columns[table_names.index(
                    name)].formatter = formatters[name]

        hover = HoverTool(point_policy="follow_mouse",
                          tooltips="""
                <div>
                  <span style="font-size: 10px; font-family: Monaco, monospace;">@host: </span>
                  <span style="font-size: 10px; font-family: Monaco, monospace;">@memory_percent</span>
                </div>
                """)

        mem_plot = figure(title='Memory Use (%)',
                          toolbar_location=None,
                          x_range=(0, 1),
                          y_range=(-0.1, 0.1),
                          height=60,
                          width=width,
                          tools='',
                          **kwargs)
        mem_plot.circle(source=self.source,
                        x='memory_percent',
                        y=0,
                        size=10,
                        fill_alpha=0.5)
        mem_plot.ygrid.visible = False
        mem_plot.yaxis.minor_tick_line_alpha = 0
        mem_plot.xaxis.visible = False
        mem_plot.yaxis.visible = False
        mem_plot.add_tools(hover, BoxSelectTool())

        hover = HoverTool(point_policy="follow_mouse",
                          tooltips="""
                <div>
                  <span style="font-size: 10px; font-family: Monaco, monospace;">@worker: </span>
                  <span style="font-size: 10px; font-family: Monaco, monospace;">@cpu</span>
                </div>
                """)

        cpu_plot = figure(title='CPU Use (%)',
                          toolbar_location=None,
                          x_range=(0, 1),
                          y_range=(-0.1, 0.1),
                          height=60,
                          width=width,
                          tools='',
                          **kwargs)
        cpu_plot.circle(source=self.source,
                        x='cpu_fraction',
                        y=0,
                        size=10,
                        fill_alpha=0.5)
        cpu_plot.ygrid.visible = False
        cpu_plot.yaxis.minor_tick_line_alpha = 0
        cpu_plot.xaxis.visible = False
        cpu_plot.yaxis.visible = False
        cpu_plot.add_tools(hover, BoxSelectTool())
        self.cpu_plot = cpu_plot

        if 'sizing_mode' in kwargs:
            sizing_mode = {'sizing_mode': kwargs['sizing_mode']}
        else:
            sizing_mode = {}

        self.root = column(cpu_plot,
                           mem_plot,
                           table,
                           id='bk-worker-table',
                           **sizing_mode)
Exemplo n.º 3
0
v = np.arctan(x)
r = np.tan(x)

e = ColumnDataSource(dict(x=x, y=v))
f = ColumnDataSource(dict(x=x, y=r))

list_of_axis = [(a, b), (c, d), (e, f)]

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

Tools = [
    TapTool(),
    BoxZoomTool(),
    BoxSelectTool(),
    PreviewSaveTool(),
    ResetTool()
]


def update_title(new, radio, sources):

    print("hello")
    active_source = sources[radio.active]
    factor = float(new)

    x = active_source.data["x"]
    y = factor * active_source.data["y"]

    active_source.data = dict(x=x, y=y)
Exemplo n.º 4
0
    def CreateGraphVisualization(self):
        Col1 = 120
        Col2 = 10
        Layouts = {
            'Circular': nx.circular_layout,
            'Spring': nx.spring_layout,
            'Fruchterman': nx.fruchterman_reingold_layout,
            'Spectral': nx.spectral_layout,
            'Random': nx.random_layout,
            'Shell': nx.shell_layout,
        }

        NodeColorProperty = self._settings['NodeColorProperty']
        LineColorProperty = self._settings['LineColorProperty']
        Iterations = self._settings['Iterations']
        Layout = self._settings['Layout']
        ShowRefNode = self._settings['ShowRefNode']
        NodeSize = self._settings['NodeSize']
        OpenBrowser = self._settings['Open plots in browser']

        NodeDict = self.__CreateUniqueNodePropertyDict(NodeColorProperty)
        LineDict = self.__CreateUniqueLinePropertyDict(LineColorProperty)
        ColorList = list(colors.cnames.keys())

        NodeColor = [
            ColorList[Col2 + NodeDict[i[1][NodeColorProperty]]]
            for i in self.__dssGraph.nodes(data=True)
        ]
        self.__NodeList = list(NodeDict.keys())
        self.__LineList = list(LineDict.keys())
        self.__NodeColor = [
            ColorList[Col2 + x] for x in range(len(self.__NodeList))
        ]
        self.__LineColor = [
            ColorList[Col1 + x] for x in range(len(self.__LineList))
        ]
        try:
            layout = Layouts[Layout](self.__dssGraph, iterations=Iterations)
        except:
            layout = Layouts[Layout](
                self.__dssGraph
            )  #, k = 1.1/sqrt(self.__dssGraph.number_of_nodes()), iterations= 50)
        NodeData = pd.DataFrame([[
            i[0], layout[i[0]][0], layout[i[0]][1], i[1]['kVBase'],
            i[1]['TotalMiles'], i[1]['NumNodes'], i[1]['N_Customers'],
            i[1]['Distance'], i[1]['ConnectedPDs'], i[1]['ConnectedPCs']
        ] for i in self.__dssGraph.nodes(data=True)],
                                columns=[
                                    'Name',
                                    'X',
                                    'Y',
                                    'kVBase',
                                    'TotalMiles',
                                    'NumNodes',
                                    'N_Customers',
                                    'Distance',
                                    'ConnectedPDs',
                                    'ConnectedPCs',
                                ]).set_index('Name')

        NodeData['colors'] = NodeColor
        self.DataSource = ColumnDataSource(NodeData)
        hoverBus = HoverTool(tooltips=[
            ('Name', '@Name'),
            ("(x,y)", "(@X, @Y)"),
            ('kVBase', '@kVBase'),
            ('TotalMiles', '@TotalMiles'),
            ('NumNodes', '@NumNodes'),
            ('N_Customers', '@N_Customers'),
            ('Distance', '@Distance'),
            ('Connected PDs', '@ConnectedPDs'),
            ('Connected PCs', '@ConnectedPCs'),
        ])
        Xs = []
        Ys = []
        LineColors = []

        for Edge in self.__dssGraph.edges():
            Node1 = list(Edge)[0]
            Node2 = list(Edge)[1]
            if ShowRefNode:
                Xs.append([NodeData.loc[Node1]['X'], NodeData.loc[Node2]['X']])
                Ys.append([NodeData.loc[Node1]['Y'], NodeData.loc[Node2]['Y']])
                LineColors.append(ColorList[Col1 + LineDict[
                    self.__dssGraph[Node1][Node2][LineColorProperty]]])
            else:
                if Node2 != 'Ref Ground Node':
                    Xs.append(
                        [NodeData.loc[Node1]['X'], NodeData.loc[Node2]['X']])
                    Ys.append(
                        [NodeData.loc[Node1]['Y'], NodeData.loc[Node2]['Y']])
                    LineColors.append(ColorList[Col1 + LineDict[
                        self.__dssGraph[Node1][Node2][LineColorProperty]]])
        self.__Figure = figure(
            tools=[
                ResetTool(), hoverBus,
                BoxSelectTool(),
                SaveTool(),
                BoxZoomTool(),
                WheelZoomTool(),
                PanTool()
            ],
            title="Distribution network graph representation",
            plot_width=650,
            plot_height=600,
        )

        if NodeSize:
            C = self.__Figure.circle('X',
                                     'Y',
                                     source=self.DataSource,
                                     size=NodeSize,
                                     level='overlay',
                                     color='colors',
                                     legend='Nodes')
        else:
            C = self.__Figure.circle('X',
                                     'Y',
                                     source=self.DataSource,
                                     level='overlay',
                                     color='colors',
                                     legend='Nodes')

        L = self.__Figure.multi_line(Xs, Ys, color=LineColors, legend='Edges')
        self.__Figure.legend.location = "top_left"
        self.__Figure.legend.click_policy = "hide"
        output_file(
            os.path.join(self._settings['OutputPath'],
                         self._settings['OutputFile']))

        doc = curdoc()
        doc.add_root(self.__Figure)
        doc.title = "PyDSS"
        self.session = push_session(doc)
        return
Exemplo n.º 5
0
def save_graph(fol_path):
    df = folderstats.folderstats(fol_path, ignore_hidden=True)

    df.loc[list(np.where(df["folder"] == True)[0]),
           "name"] = df[df["folder"] == True]["path"].apply(ret_name).values

    #     df["name"] = df["name"]+"."+df["extension"]
    df_sorted = df.sort_values(by='id')

    G = nx.Graph()
    for i, row in df_sorted.iterrows():
        if row.parent:
            G.add_edge(row.id, row.parent)

    plot = Plot(plot_width=1000,
                plot_height=1000,
                x_range=Range1d(-1.1, 1.1),
                y_range=Range1d(-1.1, 1.1))
    plot.title.text = "File System"

    plot.add_tools(TapTool(), BoxSelectTool(), BoxZoomTool(), ResetTool(),
                   WheelZoomTool(), PanTool())

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

    graph_renderer.node_renderer.data_source.data["id"] = df_sorted[
        "id"].astype('str').values

    graph_renderer.node_renderer.data_source.data["name"] = df_sorted["name"]
    graph_renderer.node_renderer.data_source.data["links"] = df_sorted["path"]
    graph_renderer.node_renderer.data_source.add(Spectral8, 'color')
    graph_renderer.node_renderer.glyph = Circle(size=20, fill_color="color")
    graph_renderer.node_renderer.selection_glyph = Circle(size=20,
                                                          fill_color="color")
    graph_renderer.node_renderer.hover_glyph = Circle(size=20,
                                                      fill_color="color")

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

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

    pos = graph_renderer.layout_provider.graph_layout
    x, y = zip(*pos.values())

    url = "@links"

    code = """
    console.log(source.data)
    var data = source.data.file;
    var ind= cb_data.source.selected.indices;
    console.log(data[ind])
    window.open(data[ind])
    //window.location.href = data[ind]

    """

    source = ColumnDataSource({
        'x': x,
        'y': y,
        'field': df_sorted["name"].values,
        'file': df_sorted["path"].values
    })
    labels = LabelSet(x='x', y='y', text='field', source=source)

    taptool = plot.select(type=TapTool)
    taptool.callback = CustomJS(args=dict(source=source), code=code)

    plot.renderers.append(graph_renderer)
    plot.renderers.append(labels)
    output_file("interactive_graphs.html")
    show(plot)
Exemplo n.º 6
0
source_low = ColumnDataSource(data=dict(
    lat=full_data.query('interest_level=="low"')["latitude"].tolist(),
    lon=full_data.query('interest_level=="low"')["longitude"].tolist()))
circle_low = Circle(x="lon",
                    y="lat",
                    size=2,
                    fill_color="green",
                    fill_alpha=0.3,
                    line_color=None)

plot.add_glyph(source_high, circle_high)
plot.add_glyph(source_medium, circle_medium)
plot.add_glyph(source_low, circle_low)

plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())
output_file("gmap_plot.html")
show(plot)

# # Conclusion

train_size = train_data.shape[0]

full_data['created_datetime'] = pd.to_datetime(full_data['created'],
                                               format="%Y-%m-%d %H:%M:%S")
full_data['created_epoch'] = full_data['created_datetime'].apply(
    lambda x: x.value // 10**9)
date_num_vars = ['created_epoch']

LBL = preprocessing.LabelEncoder()
LE_vars = []
Exemplo n.º 7
0
                        <img 
                        src="static/icons/date.png" height="25" alt="static/icons/date.png" width="25"
                        style="vertical-align: middle;"
                        ></img>
                        <pbokeh style="vertical-align: middle; font-size: 15px; font-weight: bold;">@Date_String<pbokeh>
                        
                        <img 
                        src="static/icons/time.png" height="25" alt="static/icons/time.png" width="25"
                        style="vertical-align: middle;"
                        ></img>
                        <pbokeh style="vertical-align: middle; font-size: 15px; font-weight: bold;">@Time_String</pbokeh>
                    </div>
                </div>
""")
wheel_zoom_tool = WheelZoomTool()
box_select_tool = BoxSelectTool()
callback = CustomJS(args=dict(source=source),
                    code="""
                  var selected=source.selected['1d']['indices']
                  window.open(source.data.Url[selected]);                  
""")
tap_tool = TapTool(callback=callback)
pan_tool = PanTool()
fig.toolbar_location = 'above'
fig.toolbar.logo = None
fig.add_tools(pan_tool, wheel_zoom_tool, box_select_tool, hover_tool, tap_tool)
fig.toolbar.active_scroll = wheel_zoom_tool
fig.toolbar.active_drag = pan_tool
fig.toolbar.active_inspect = hover_tool

#set the google api key
Exemplo n.º 8
0
color_palette = list(reversed(Viridis11[:8]))
mapper = LinearColorMapper(palette=color_palette, low=min_value, high=max_value)
color_bar = ColorBar(color_mapper = mapper, border_line_color = None, location = (0,0))


plot_color = figure(title="", x_axis_location="above", x_range=names2, y_range=list(reversed(names2)),toolbar_location = 'below')
plot_color.plot_width = 650
plot_color.plot_height = 650
plot_color.grid.grid_line_color = None
plot_color.axis.axis_line_color = None
plot_color.axis.major_tick_line_color = None
plot_color.axis.major_label_text_font_size = "5pt"
plot_color.axis.major_label_standoff = 0
plot_color.xaxis.major_label_orientation = np.pi/3
plot_color.add_tools(hover_am)
plot_color.add_tools(BoxSelectTool())

plot_color.rect('xname', 'yname', 0.9, 0.9, source=source, line_color=None, hover_line_color='black', fill_color={'field': 'count', 'transform': mapper})
plot_color.add_layout(color_bar, 'right')

# alpha matrix
plot_alpha = figure(title="", x_axis_location="above", x_range=names2, y_range=list(reversed(names2)),toolbar_location = 'below')
plot_alpha.plot_width = 650
plot_alpha.plot_height = 650
plot_alpha.grid.grid_line_color = None
plot_alpha.axis.axis_line_color = None
plot_alpha.axis.major_tick_line_color = None
plot_alpha.axis.major_label_text_font_size = "5pt"
plot_alpha.axis.major_label_standoff = 0
plot_alpha.xaxis.major_label_orientation = np.pi/3
plot_alpha.add_tools(hover_am)
Exemplo n.º 9
0
    def generate_chart(self):
        """
        Description:

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

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

        Ouput:
        """

        if self.colors == []:
            self.no_colors_set = True
            self.colors = ["#8735fb"] * len(self.y)

        if len(self.title) == 0:
            self.title = "Stacked Line plots on x-axis: " + self.x

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

        self.chart.add_tools(BoxSelectTool(dimensions="width"))

        if self.legend:
            mapper = LinearColorMapper(palette=self.colors,
                                       low=1,
                                       high=len(self.y))
            self.color_bar = ColorBar(
                color_mapper=mapper,
                location=(0, 0),
                ticker=FixedTicker(ticks=list(range(1,
                                                    len(self.y) + 1))),
                major_label_overrides=dict(
                    zip(list(range(1,
                                   len(self.y) + 1)), self.y)),
                major_label_text_baseline="top",
                major_label_text_align="left",
                major_tick_in=0,
                major_tick_out=0,
            )
            self.chart.add_layout(self.color_bar, self.legend_position)

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

        if self.x_axis_tick_formatter:
            self.chart.xaxis.formatter = self.x_axis_tick_formatter
        if self.y_axis_tick_formatter:
            self.chart.yaxis.formatter = self.y_axis_tick_formatter

        self.interactive_image = InteractiveImage(
            self.chart,
            self.generate_InteractiveImage_callback(),
            data_source=self.source,
            timeout=self.timeout,
            x_dtype=self.x_dtype,
            y_dtype=self.y_dtype,
        )
Exemplo n.º 10
0
 def _init_fig(self):
     self.fig.add_tools(BoxSelectTool(dimensions="width"))
     self.fig.plot_height = 500
     self.source = ColumnDataSource({'timestamp': [], self.feature: []})
     self.fig.line('timestamp', self.feature, source=self.source)
Exemplo n.º 11
0
p2 = figure(
    # axis properties
    x_range=ageQuantile,
    y_range=(0, int(max(percentageAge)) + 1),
    y_axis_label="Percentage of age group with a positive Covid-19 test",
    x_axis_label="Age quantiles",

    # plot properties
    plot_height=250,
    title="Percentage positive tests per age quantile",
    toolbar_location="right",
    tools=[
        WheelZoomTool(),
        ResetTool(),
        PanTool(),
        BoxSelectTool(), "save", "tap"
    ],
)

p2.x_range.max_interval = 19  # sets x-axis maximum

vbar_renderer = p2.vbar(  # creates bars
    x='x',
    top='y',
    width=0.5,
    source=sourcep2,  # defines source
    color='blue',  # default color of the bars
)

vbar_selected = VBar(  # defines how a selected bar looks
    fill_alpha=0.2,
Exemplo n.º 12
0
    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())
def plot_data(data_df, connections, year, geoSource_new):

    data_df_countries = data_df  #.drop_duplicates(subset=None, keep='first', inplace=True)
    connections_df = connections

    node_source = ColumnDataSource(
        data_df_countries[["country_id", "Country", "Longitude", "Latitude"]])
    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_data, Patches(xs='xs', ys='ys', line_color='grey'
    #                      , line_width=.5, fill_color=Set3_12[6], fill_alpha=0.25))

    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.25))

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

    hover = HoverTool(
        show_arrow=True,  # tooltips=  # [("Country Involved: ", "@Country")],
        tooltips="""
                                <div>
                                    <div>
                                        <span style="font-size: 15px;">Country Information </span>
                                        <span style="font-size: 12px; color: #696;">@Destination_Country </span>
                                    </div>
                                </div>
                                """,
        renderers=[graph])
    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 = 3
    plot.add_tile(STAMEN_TONER_LABELS)

    return plot
Exemplo n.º 14
0
            ("Length", "@length bp"),
            ("Protein Families", "@single_copy_PFAMs"),
            ("# Single Copies", "@num_single_copies"),
            ("GC%", "@gc %"),
            ("Kingdom", "@kingdom"),
            ("Phylum", "@phylum"),
            ("Class", "@class"),
            ("Order", "@order"),
            ("Family", "@family"),
            ("Genus", "@genus"),
            ("Species", "@species"),
            ("Tax ID", "@taxid"),
        ],
        formatters={"Coverage": "printf", "Length": "printf", "GC%": "printf"},
    ),
    BoxSelectTool(callback=contig_selection(source=source, source2=contigsList)),
    LassoSelectTool(callback=contig_selection(source=source, source2=contigsList)),
    TapTool(),
)

if args["legend"]:
    cluster_plot.scatter(
        x="bh_tsne_x",
        y="bh_tsne_y",
        source=source,
        legend="cluster",
        color="cluster",
        fill_color=factor_cmap(
            "cluster", palette=crcolor, factors=list(df.cluster.unique())
        ),
    )
view_green_s4 = CDSView(source=s4, filters=[GroupFilter(column_name='ann', group='N')])
view_red_s4 = CDSView(source=s4, filters=[GroupFilter(column_name='ann', group='V')])
view_blue_s4 = CDSView(source=s4, filters=[GroupFilter(column_name='noise', group='True')])


# output to static HTML file
output_file("Poincare.html")

data.to_csv(r'C:\Users\Sujith Tenali\Desktop\zero11.csv')


# ------------------------------------------ FIGURE 1 ----------------------------------------------------------
# # configure visual properties on a plot's figure attribute

p1 = figure(output_backend="webgl", plot_width=700, plot_height=700) 
p1.add_tools(BoxSelectTool()) 
p1.add_tools(PolySelectTool())
p1.toolbar.active_drag =BoxSelectTool()
p1.toolbar.active_scroll = None
p1.toolbar.active_tap = None
p1.toolbar.active_inspect = None

# p1.add_tools(TapTool())
p1.add_tools(HoverTool(
    tooltips=[
        	('index', '$index'),
	    	('(x,y)', '($x, $y)'),
    		('time', '@localtime{%c}'),
    ],

    formatters={
Exemplo n.º 16
0
    def generate_chart(self):
        """
        Description:

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

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

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

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

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

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

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

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

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

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

        if self.legend_added is False:
            self.render_legend()
def generateAreaSelection(dataframe, userWidth, userHeight, position_min,
                          position_max):
    snps = dataframe
    snps["log10"] = -numpy.log10(snps.pvalue_assoc)  #transformation
    snps = snps.sort_values(by="pvalue_assoc")  # SORT BY P-VALUE
    max_pvalue = int(snps.log10[0:1])  # GET MINIMUM P-VALUE
    #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
    #NEW COLUMNS AND RENAMING
    #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
    snps['imp'] = numpy.where(snps['info_assoc'] == 1, snps['log10'],
                              'NaN')  # gather information on imputed snps
    snps['Imputed'] = numpy.where(
        snps['info_assoc'] == 1, True,
        False)  #discriminate between imputed and genotyped for table
    snps['interest'] = numpy.where(snps['log10'] >= (-numpy.log10(0.00000005)),
                                   snps['log10'],
                                   'NaN')  #select snp of interest

    #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
    source = ColumnDataSource(snps)  # SOURCE DATA FOR BOKEH PLOT
    TOOLS = [
        HoverTool(tooltips=[("SNP", "@rs_id_assoc"), (
            "Gene", "@gene"), ("P-value", "@pvalue_assoc"), ("Region",
                                                             "@func")]),
        CrosshairTool(),
        WheelZoomTool(),
        BoxSelectTool(),
        BoxZoomTool(),
        ResizeTool(),
        ResetTool(),
        PanTool(),
        PreviewSaveTool(),
        TapTool()
    ]

    stringLegend = "pvalue < " + str(0.001)
    plot = figure(webgl=True,
                  tools=TOOLS,
                  x_axis_label='Position',
                  y_axis_label='-log10(p)',
                  plot_width=userWidth,
                  plot_height=userHeight,
                  x_range=(position_min - 150000, position_max + 150000),
                  y_range=(-3.2, max_pvalue + 3)
                  # y_range = (-1, max_pvalue+1)
                  )
    plot.circle('position', 'log10', source=source, size=7, legend='Genotyped')
    plot.square('position',
                'imp',
                source=source,
                size=7,
                color="olive",
                legend='Imputed')
    plot.circle('position',
                'interest',
                source=source,
                size=7,
                color="red",
                legend=stringLegend)

    snps = snps.sort_values(by="position")  # SORT POSITIONS
    snps.drop_duplicates(subset=('gene'), inplace=True,
                         keep="last")  # TAKE GENE NAME DUPLICATES OFF

    # for i in range(0,10):
    #     snps['ligne'+str(i+1)] = snps.start_gen[i:len(snps):10]
    #     snps['Fligne'+str(i+1)] = snps.end_gen[i:len(snps):10]
    #
    # positions = {
    #     'ligne1' : -0.30,
    #     'ligne2' : -0.55,
    #     'ligne3' : -0.85,
    #     'ligne4' : -1.15,
    #     'ligne5' : -2.95,
    #     'ligne6' : -2.65,
    #     'ligne7' : -2.35,
    #     'ligne8' : -2.05,
    #     'ligne9' : -1.75,
    #     'ligne10' : -1.45
    # }
    # for key, value in positions.items():
    #     print key, value
    #     plot.segment(snps[key], [value]*(len(snps)), snps['F'+key],[value]*(len(snps)), line_width=6, line_color="#8b4513",)          #ligne 1
    #     # plot.text(snps[key]+((snps['F'+key]-snps[key])/2), [value-0.05]*(len(snps)), text=snps.gene, text_color='black', text_align='center', text_font_size='5pt', text_font_style='bold')

    snps['ligne1'] = snps.start_gen[0:len(snps):10]
    snps['Fligne1'] = snps.end_gen[0:len(snps):10]

    snps['ligne2'] = snps.start_gen[1:len(snps):10]
    snps['Fligne2'] = snps.end_gen[1:len(snps):10]

    snps['ligne3'] = snps.start_gen[2:len(snps):10]
    snps['Fligne3'] = snps.end_gen[2:len(snps):10]

    snps['ligne4'] = snps.start_gen[3:len(snps):10]
    snps['Fligne4'] = snps.end_gen[3:len(snps):10]

    snps['ligne5'] = snps.start_gen[4:len(snps):10]
    snps['Fligne5'] = snps.end_gen[4:len(snps):10]

    snps['ligne6'] = snps.start_gen[5:len(snps):10]
    snps['Fligne6'] = snps.end_gen[5:len(snps):10]

    snps['ligne7'] = snps.start_gen[6:len(snps):10]
    snps['Fligne7'] = snps.end_gen[6:len(snps):10]

    snps['ligne8'] = snps.start_gen[7:len(snps):10]
    snps['Fligne8'] = snps.end_gen[7:len(snps):10]

    snps['ligne9'] = snps.start_gen[8:len(snps):10]
    snps['Fligne9'] = snps.end_gen[8:len(snps):10]

    snps['ligne10'] = snps.start_gen[9:len(snps):10]
    snps['Fligne10'] = snps.end_gen[9:len(snps):10]

    plot.segment(
        snps.ligne1,
        [-0.30] * (len(snps)),
        snps.Fligne1,
        [-0.30] * (len(snps)),
        line_width=6,
        line_color="#8b4513",
    )  #ligne 1
    plot.text(snps.ligne1 + ((snps.Fligne1 - snps.ligne1) / 2),
              [-0.25] * (len(snps)),
              text=snps.gene,
              text_color='black',
              text_align='center',
              text_font_size='1em',
              text_font_style='bold')

    plot.segment(
        snps.ligne2,
        [-0.55] * (len(snps)),
        snps.Fligne2,
        [-0.55] * (len(snps)),
        line_width=6,
        line_color="#8b4513",
    )  #ligne 2
    plot.text(snps.ligne2 + ((snps.Fligne2 - snps.ligne2) / 2),
              [-0.50] * (len(snps)),
              text=snps.gene,
              text_color='black',
              text_align='center',
              text_font_size='1em',
              text_font_style='bold')

    plot.segment(
        snps.ligne3,
        [-0.85] * (len(snps)),
        snps.Fligne3,
        [-0.85] * (len(snps)),
        line_width=6,
        line_color="#8b4513",
    )  #ligne 3
    plot.text(snps.ligne3 + ((snps.Fligne3 - snps.ligne3) / 2),
              [-0.80] * (len(snps)),
              text=snps.gene,
              text_color='black',
              text_align='center',
              text_font_size='1em',
              text_font_style='bold')

    plot.segment(
        snps.ligne4,
        [-1.15] * (len(snps)),
        snps.Fligne4,
        [-1.15] * (len(snps)),
        line_width=6,
        line_color="#8b4513",
    )  #ligne 4
    plot.text(snps.ligne4 + ((snps.Fligne4 - snps.ligne4) / 2),
              [-1.10] * (len(snps)),
              text=snps.gene,
              text_color='black',
              text_align='center',
              text_font_size='1em',
              text_font_style='bold')

    plot.segment(
        snps.ligne10,
        [-1.45] * (len(snps)),
        snps.Fligne10,
        [-1.45] * (len(snps)),
        line_width=6,
        line_color="#8b4513",
    )  #ligne 5
    plot.text(snps.ligne10 + ((snps.Fligne10 - snps.ligne10) / 2),
              [-1.40] * (len(snps)),
              text=snps.gene,
              text_color='black',
              text_align='center',
              text_font_size='1em',
              text_font_style='bold')

    plot.segment(
        snps.ligne9,
        [-1.75] * (len(snps)),
        snps.Fligne9,
        [-1.75] * (len(snps)),
        line_width=6,
        line_color="#8b4513",
    )  #ligne 6
    plot.text(snps.ligne9 + ((snps.Fligne9 - snps.ligne9) / 2),
              [-1.70] * (len(snps)),
              text=snps.gene,
              text_color='black',
              text_align='center',
              text_font_size='1em',
              text_font_style='bold')

    plot.segment(
        snps.ligne8,
        [-2.05] * (len(snps)),
        snps.Fligne8,
        [-2.05] * (len(snps)),
        line_width=6,
        line_color="#8b4513",
    )  #ligne 7
    plot.text(snps.ligne8 + ((snps.Fligne8 - snps.ligne8) / 2),
              [-2.00] * (len(snps)),
              text=snps.gene,
              text_color='black',
              text_align='center',
              text_font_size='1em',
              text_font_style='bold')

    plot.segment(
        snps.ligne7,
        [-2.35] * (len(snps)),
        snps.Fligne7,
        [-2.35] * (len(snps)),
        line_width=6,
        line_color="#8b4513",
    )  #ligne 8
    plot.text(snps.ligne7 + ((snps.Fligne7 - snps.ligne7) / 2),
              [-2.30] * (len(snps)),
              text=snps.gene,
              text_color='black',
              text_align='center',
              text_font_size='1em',
              text_font_style='bold')

    plot.segment(
        snps.ligne6,
        [-2.65] * (len(snps)),
        snps.Fligne6,
        [-2.65] * (len(snps)),
        line_width=6,
        line_color="#8b4513",
    )  #ligne 9
    plot.text(snps.ligne6 + ((snps.Fligne6 - snps.ligne6) / 2),
              [-2.60] * (len(snps)),
              text=snps.gene,
              text_color='black',
              text_align='center',
              text_font_size='1em',
              text_font_style='bold')

    plot.segment(
        snps.ligne5,
        [-2.95] * (len(snps)),
        snps.Fligne5,
        [-2.95] * (len(snps)),
        line_width=6,
        line_color="#8b4513",
    )  #ligne 10
    plot.text(snps.ligne5 + ((snps.Fligne5 - snps.ligne5) / 2),
              [-2.90] * (len(snps)),
              text=snps.gene,
              text_color='black',
              text_align='center',
              text_font_size='1em',
              text_font_style='bold')

    plot.grid.grid_line_color = None  # TAKE GRID LINES OFF THE GRAPH
    graph, div1 = components(plot, CDN)
    return graph, div1
Exemplo n.º 18
0
def create_plot(G, layout):
    '''
        Returns a bokeh plot using the given netowrkx graph and layout. 
        Depending on the layout the dimensions of the graphs grid change

            Parameters:
                G (networkx graph) : Netoworkx graph that will be plotted
                layout (networkx layout): The layout of the network graph
            Return:
                plot (bokeh Plot): the plot generated using bokehs functions
    '''

    # the grouped layout is a special layout that uses the positions generated
    # by makegraph.py
    if layout == "grouped":
        G, sidel = get_vertices()
        hsidel = sidel / 2
        plot = Plot(plot_width=1200,
                    plot_height=600,
                    x_range=Range1d(-(hsidel + .1), hsidel + .1),
                    y_range=Range1d(-(hsidel + .1), hsidel + .1),
                    align='center')
    else:
        plot = Plot(plot_width=1200,
                    plot_height=600,
                    x_range=Range1d(-2.1, 2.1),
                    y_range=Range1d(-2.1, 2.1),
                    align='center')
    plot.title.text = "TV Shows Connected By Recommendation"
    plot.background_fill_color = "black"
    plot.background_fill_alpha = 0.1

    if layout == "grouped":
        pos_dict = {}
        for node in G.nodes:
            pos_dict[node] = G.nodes[node]["pos"]
        graph_renderer = from_networkx(G,
                                       pos_dict,
                                       scale=hsidel,
                                       center=(0, 0))

    # The discover layout uses the positions assigned in discover.py
    elif layout == "discover":
        pos_dict = {}
        for node in G.nodes:
            pos_dict[node] = G.nodes[node]["pos"]
        graph_renderer = from_networkx(G, pos_dict, scale=2, center=(0, 0))
    else:
        graph_renderer = from_networkx(G, layout, scale=2, center=(0, 0))

    # The colors for each node is assigned using a scale and if the number of nodes goes over
    # 256 the same color is used for the remaining nodes
    if len(G.nodes) > 256:
        Inferno = [Spectral4[1]] * len(G.nodes) - 256
        Inferno.extend(viridis(len(G.nodes)))
    else:
        Inferno = list(viridis(len(G.nodes)))
    source = graph_renderer.node_renderer.data_source
    nodes = graph_renderer.node_renderer
    edges = graph_renderer.edge_renderer
    source.data['name'] = [x for x in source.data['index']]
    source.data['colors'] = Inferno
    nodes.glyph = Circle(size=15,
                         fill_color='colors',
                         fill_alpha=0.9,
                         line_color='colors')
    nodes.selection_glyph = Circle(size=15,
                                   fill_color=Plasma11[10],
                                   fill_alpha=0.8)
    nodes.hover_glyph = Circle(size=15, fill_color=Plasma11[9])
    nodes.glyph.properties_with_values()

    edges.glyph = MultiLine(line_color="black", line_alpha=0.1, line_width=2)
    edges.selection_glyph = MultiLine(line_color=Plasma11[10], line_width=2)
    edges.hover_glyph = MultiLine(line_color=Plasma11[9], line_width=2)

    # This functions allow nodes to be highlighted when hovered over or clicked on
    graph_renderer.selection_policy = NodesAndLinkedEdges()
    graph_renderer.inspection_policy = NodesAndLinkedEdges()
    #graph_renderer.selection_policy = EdgesAndLinkedNodes()

    # The tooltips to show the data for the plots
    if layout == "grouped":
        node_hover_tool = HoverTool(tooltips=[("", "@name"), ("", "@genre")])
    else:
        node_hover_tool = HoverTool(tooltips=[("", "@name")])
    plot.add_tools(node_hover_tool, WheelZoomTool(), TapTool(),
                   BoxSelectTool())

    plot.renderers.append(graph_renderer)
    return plot
Exemplo n.º 19
0
plot = GMapPlot(
    x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options)
    
plot.title.text = "London Crime Correlation Heatmap"

# For GMaps to function, Google requires you obtain and enable an API key:
plot.api_key = "[ENTER YOUR GOOGLE MAP API KEY HERE]"
    
hover = HoverTool(tooltips=[("CountySel", "@acounty"),
                            ("CountyComp", "@county"),
                            ("Crime", "@acrime"),
                            ("Lag","@lag")])
circle = Circle(x="longitude", y="latitude", size="size_mult", fill_color="color", fill_alpha=0.8, line_color=None)
plot.add_glyph(source, circle)

plot.add_tools(ResetTool(), PanTool(), WheelZoomTool(), BoxSelectTool(),hover)
 
def generic_update(attr,old, new):
    global df, colors
    df2 = df[(df.acounty==county_select.value) & (df.acrime == crime_select.value)]
    source.data = dict(
        acounty = df2.acounty,
        acrime = df2.acrime,
        county = df2.bcounty,
        crime = df2.bcrime,
        lag = df2.lag,
        calc_cor = df2.calc_cor,
        latitude= df2.latitude,
        longitude = df2.longitude,
        size_mult = df2.size_mult,
        color = df2.color)
Exemplo n.º 20
0
mapper = LinearColorMapper(palette=Purples9, low=user_node, high=0)
connections = list(node_color.values())
eigenv = list(eigenv.values())
between = list(between.values())

source = ColumnDataSource(pd.DataFrame.from_dict({k:v for k,v in BA.nodes(data=True)},orient='index'))
source.add(connections, "connections")
source.add(eigenv, "eigenv")
source.add(between, "between")

boxcolor = BoxAnnotation(fill_color='white', line_color='black')

plot_option = {
'background_fill_color': 'gray',
'background_fill_alpha': .5,
'tools': [PanTool(), WheelZoomTool(), TapTool(), BoxZoomTool(overlay=boxcolor), BoxSelectTool(overlay=boxcolor), ResetTool()],
'x_range': Range1d(-2,2), 
'y_range': Range1d(-2,2),
}

plot = figure(**plot_option, x_axis_location=None, y_axis_location=None)
plot.title.text = "Barabasi-Albert Graph"
graph = from_networkx(BA, nx.spring_layout)
graph.node_renderer.data_source = source
graph.node_renderer.glyph = Circle(name="Node", size='node_size', fill_color={'field': 'node_color', 'transform': mapper})
graph.edge_renderer.selection_glyph = MultiLine(line_color='white', line_width=3)
plot.add_tools(HoverTool(name="Node", tooltips=[('Node', '$index'), 
                        ('Connections', '@connections'), ('Eigen Value', '@eigenv{.000000}'), ('Betweenness', '@between{.000000}'), 
                        ]))
graph.selection_policy = NodesAndLinkedEdges()
plot.renderers.append(graph)
Exemplo n.º 21
0
    def create(self):
        manufacturers = sorted(mpg["manufacturer"].unique())
        models = sorted(mpg["model"].unique())
        transmissions = sorted(mpg["trans"].unique())
        drives = sorted(mpg["drv"].unique())
        classes = sorted(mpg["class"].unique())

        manufacturer_select = Select(title="Manufacturer:", value="All", options=["All"] + manufacturers)
        manufacturer_select.on_change('value', self.on_manufacturer_change)
        model_select = Select(title="Model:", value="All", options=["All"] + models)
        model_select.on_change('value', self.on_model_change)
        transmission_select = Select(title="Transmission:", value="All", options=["All"] + transmissions)
        transmission_select.on_change('value', self.on_transmission_change)
        drive_select = Select(title="Drive:", value="All", options=["All"] + drives)
        drive_select.on_change('value', self.on_drive_change)
        class_select = Select(title="Class:", value="All", options=["All"] + classes)
        class_select.on_change('value', self.on_class_change)

        columns = [
            TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=manufacturers), formatter=StringFormatter(font_style="bold")),
            TableColumn(field="model",        title="Model",        editor=StringEditor(completions=models)),
            TableColumn(field="displ",        title="Displacement", editor=NumberEditor(step=0.1),              formatter=NumberFormatter(format="0.0")),
            TableColumn(field="year",         title="Year",         editor=IntEditor()),
            TableColumn(field="cyl",          title="Cylinders",    editor=IntEditor()),
            TableColumn(field="trans",        title="Transmission", editor=SelectEditor(options=transmissions)),
            TableColumn(field="drv",          title="Drive",        editor=SelectEditor(options=drives)),
            TableColumn(field="class",        title="Class",        editor=SelectEditor(options=classes)),
            TableColumn(field="cty",          title="City MPG",     editor=IntEditor()),
            TableColumn(field="hwy",          title="Highway MPG",  editor=IntEditor()),
        ]
        data_table = DataTable(source=self.source, columns=columns, editable=True)

        plot = Plot(title=None, x_range= DataRange1d(), y_range=DataRange1d(), plot_width=1000, plot_height=300)

        # Set up x & y axis
        plot.add_layout(LinearAxis(), 'below')
        yaxis = LinearAxis()
        plot.add_layout(yaxis, 'left')
        plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

        # Add Glyphs
        cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5)
        hwy_glyph = Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5)
        cty = plot.add_glyph(self.source, cty_glyph)
        hwy = plot.add_glyph(self.source, hwy_glyph)

        # Add the tools
        tooltips = [
            ("Manufacturer", "@manufacturer"),
            ("Model", "@model"),
            ("Displacement", "@displ"),
            ("Year", "@year"),
            ("Cylinders", "@cyl"),
            ("Transmission", "@trans"),
            ("Drive", "@drv"),
            ("Class", "@class"),
        ]
        cty_hover_tool = HoverTool(renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")])
        hwy_hover_tool = HoverTool(renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")])
        select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions=['width'])
        plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool)


        controls = VBox(children=[
            manufacturer_select, model_select, transmission_select,
             drive_select, class_select])
        top_panel = HBox(children=[controls, plot])
        layout = VBox(children=[top_panel, data_table])

        return layout
Exemplo n.º 22
0
def make_pdf_plot(title, data, label='Temperature', pdf_function=norm):
    x_length = 10000
    if pdf_function == norm:
        upper = data[1] + (data[2] * 5)  #max(data[1] + 1,
        lower = data[1] - (data[2] * 5
                           )  #min(data[1] - 1, data[1] - (data[2] * 5))
    elif pdf_function == beta:
        upper = 1
        lower = 0
    else:  #Gamma
        lower = 0
        upper = 1.5
    step_size = (upper - lower) / x_length
    x = np.linspace(lower, upper, x_length)
    if pdf_function == gamma:
        pdf = pdf_function.pdf(x, data[1], scale=data[2])
        cdf = pdf_function.cdf(x, data[1], scale=data[2])
    else:
        pdf = pdf_function.pdf(x, data[1], data[2])
        cdf = pdf_function.cdf(x, data[1], data[2])
    if pdf_function != norm:
        maximizer = lower + step_size * np.argmax(pdf)
    else:
        maximizer = data[1]
    source = ColumnDataSource(
        data=dict(x=[], y=[], width=[], height=[], prob=[], x0=[], x1=[]))
    cdf = ColumnDataSource(data=dict(cdf=cdf))
    bounds = ColumnDataSource(
        data=dict(upper=[upper], lower=[lower], step=[step_size]))
    #prob = ColumnDataSource(data=dict(prob=[0.0]))

    callback = CustomJS(args=dict(source=source, cdf=cdf, bounds=bounds),
                        code="""
            // get data source from Callback args
            var data = source.data;
            var cdf = cdf.data['cdf'];
            //var prob = prob.data;
            /// get BoxSelectTool dimensions from cb_data parameter of Callback
            var geometry = cb_data['geometry'];
            /// calculate Rect attributes
            var x1 = geometry['x1']
            var x0 = geometry['x0']
            var width = geometry['x1'] - geometry['x0'];
            var height = geometry['y1'] - geometry['y0'];
            var x = geometry['x0'] + width/2;
            //var y = geometry['y0'] + height/2;
            var y = 0 + height/2;
            var cdf1 = 0;
            var cdf2 = 0;
            var upper = bounds.data['upper'][0];
            var lower = bounds.data['lower'][0];
            var step = bounds.data['step'][0];
            if (x0 >= upper) {
                var cdf0 = cdf[9999];
            } else if (x0 <= lower) {
                var cdf0 = cdf[0];
            } else {
                var cdf0 = cdf[Math.round((x0 - lower) / step)];
            }
            if (x1 >= upper) {
                var cdf1 = cdf[9999];
            } else if (x1 <= lower) {
                var cdf1 = cdf[0];
            } else {
                var cdf1 = cdf[Math.round((x1 - lower) / step)];
            }
            /// update data source with new Rect attributes
            data['x'].pop();
            data['y'].pop();
            data['width'].pop();
            data['height'].pop();
            data['x'].push(x);
            data['y'].push(y);
            data['width'].push(width);
            data['height'].push(height);
            data['prob'].pop();
            data['prob'].push(cdf1 - cdf0);
            data['x0'].pop();
            data['x1'].pop();
            data['x0'].push(x0)
            data['x1'].push(x1)
            // emit update of data source
            source.change.emit();
        """)

    box_select = BoxSelectTool(callback=callback, dimensions="width")
    hover = HoverTool(tooltips=[
        ("Prob", "@prob"),
        ("(x0,x1)", "(@x0, @x1)"),
    ])
    rect = Rect(
        x='x',
        y='y',
        width='width',
        height='height',
        #tags=['cdf', cdf],
        fill_alpha=0.3,
        fill_color='#009933')

    title = "%s: %f" % (title, maximizer)
    p1 = figure(title=title,
                tools="wheel_zoom,pan,reset,save",
                background_fill_color="#E8DDCB",
                toolbar_location="right")
    p1.add_tools(box_select)
    p1.add_tools(hover)
    p1.toolbar.active_drag = box_select
    p1.line(x, pdf, line_color="#D95B43", line_width=8,
            alpha=0.7)  #legend="PDF")
    p1.legend.location = "center_right"
    p1.legend.background_fill_color = "darkgrey"
    p1.xaxis.axis_label = label
    p1.yaxis.axis_label = 'Density'  #'Pr(' + label +  ')'
    p1.add_glyph(source, rect, selection_glyph=rect, nonselection_glyph=rect)
    return p1
Exemplo n.º 23
0
                plot_height=800,
                plot_width=1500)
plot.title.text = "United States"

source = ColumnDataSource(data=dict(
    lat=lat + 0.01 * np.random.normal(size=lat.size),
    lon=lng + 0.01 * np.random.normal(size=lng.size),
    ids=ids,
))
circle = Circle(x="lon",
                y="lat",
                size=8,
                fill_color=(150, 0, 0),
                fill_alpha=1,
                line_color=None)
plot.add_glyph(source, circle)

hover = HoverTool()
hover.tooltips = collections.OrderedDict([
    ("ID", "@ids"),
])

plot.add_tools(hover, PanTool(), WheelZoomTool(), BoxSelectTool(), SaveTool())
output_file("gmap_plot.html", mode='inline')

show(plot)  # opens a browser

# In[32]:

np.random.normal()
Exemplo n.º 24
0
def clusterPlot(data_csv, l, kl, ku):
    #  data_csv = '../data/CA_WHS_HOUSEHOLD.csv'
    #  pick columns as field features
    # l = ['HOUSEHOLD_CLAIMED_FAMILY_SIZE',
    # 	'HOUSEHOLD_REFUGEE_STATUS']

    (kmeans, store_clusters, reduced_data,
     clusters) = Cluster(data_csv, l, 2, 7)

    colors = getcolors(clusters)
    print(colors)

    # clustering
    output_file("clustering.html", title="Clustering Bokeh example")

    #initialize our bokeh plot

    x_min, x_max = reduced_data[:, 0].min() - 1, reduced_data[:, 0].max() + 1
    y_min, y_max = reduced_data[:, 1].min() - 1, reduced_data[:, 1].max() + 1

    tools = [
        PanTool(),
        BoxSelectTool(),
        BoxZoomTool(),
        ResetTool(),
        HoverTool(tooltips=[("(x,y)", "($x, $y)")])
    ]

    plot = figure(width=500,
                  height=500,
                  title='Clusters',
                  y_range=(y_min, y_max),
                  x_range=(x_min, x_max),
                  tools=tools)

    #plot centroid / cluster center / group mean for each group

    clus_xs = []

    clus_ys = []

    #we get the  cluster x / y values from the k-means algorithm

    for entry in kmeans.cluster_centers_:

        clus_xs.append(entry[0])

        clus_ys.append(entry[1])

    #the cluster center is marked by a circle, with a cross in it

    plot.circle_cross(x=clus_xs,
                      y=clus_ys,
                      size=40,
                      fill_alpha=0,
                      line_width=2,
                      color=colors)

    plot.text(text=[''], x=clus_xs, y=clus_ys, text_font_size=['30pt'])

    #text = ['setosa', 'versicolor', 'virginica']

    i = 0  #counter

    #begin plotting each petal length / width

    #We get our x / y values from the original plot data.

    #The k-means algorithm tells us which 'color' each plot point is,

    #and therefore which group it is a member of.

    for k, v in store_clusters.items():
        v = np.asarray(v)
        plot.scatter(v[:, 0], v[:, 1], color=colors[k], size=5)
        #plot.select(dict(type=HoverTool)).tooltips = {"x":"$x", "y":"$y"}

    script, div = components(plot)

    #Export html construct for plotting in template
    return script, div


##show(plot)
Exemplo n.º 25
0
import networkx as nx

from bokeh.io import output_file, show
from bokeh.models import (BoxSelectTool, Circle, HoverTool, MultiLine,
                          NodesAndAdjacentNodes, Plot, Range1d, TapTool)
from bokeh.palettes import Spectral4
from bokeh.plotting import from_networkx

G=nx.karate_club_graph()

plot = Plot(width=400, height=400,
            x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
plot.title.text = "Graph Interaction Demonstration"

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

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

graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])

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

graph_renderer.selection_policy = NodesAndAdjacentNodes()
graph_renderer.inspection_policy = NodesAndAdjacentNodes()

plot.renderers.append(graph_renderer)
Exemplo n.º 26
0
    def plot_hotspots(self,centroids, centroid_dictionary,num_datapoints, completed_rides=None, unfulfilled_rides=None):
        '''
        Takes in centroid values from self.create_centroids() and centroid_dictionary and plots the centroids relative to their
        intensity. Optional inputs for the lat-long columns for completed_rides (green) and unfulfilled_rides(blue).

        INPUT:
        - centroids (numpy array)
        - centroid_dict (dictionary)
        - copmleted_rides (dataframe)(optional)
        - unfulfilled_rides (dataframe)(optional)

        OUTPUT:
        -None
        '''
        #creating the plot
        map_options = GMapOptions(lat=30.29, lng=-97.73, map_type="roadmap", zoom=11)
        plot = GMapPlot(
            x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options
        )
        plot.title.text = "Austin"
        plot.api_key = "AIzaSyBx-cLXm4jxpg0aX_nnUnwd2hir3Ve0j9w"

        #create alpha based on intensity
        alpha = []
        for key, value in centroid_dictionary.iteritems():
            al_value = value[2]/float(num_datapoints)
            al_fixed = al_value+.25
            alpha.insert(key,al_fixed)

        #try if completed_rides is populated
        try:
            completed_lats = list(completed_rides['start_location_lat'])
            completed_longs = list(completed_rides['start_location_long'])
            completed_source = ColumnDataSource( data=dict(
                lat=completed_lats,
                lon=completed_longs,))
            completed_dots = Circle(x="lon", y="lat", size=15, fill_color="green", fill_alpha=0.1, line_color=None)
            plot.add_glyph(completed_source, completed_dots)
        except:
            pass

        #try if unfulfilled_rides is populated
        try:
            unfulfilled_lats = list(unfulfilled_rides['start_location_lat'])
            unfulfilled_longs = list(unfulfilled_rides['start_location_long'])
            unfulfilled_source = ColumnDataSource(
            data=dict(
                lat=unfulfilled_lats,
                lon=unfulfilled_longs,))
            unfulfilled_dots = Circle(x="lon", y="lat", size=15, fill_color="blue", fill_alpha=0.8, line_color=None)
            plot.add_glyph(unfulfilled_source, unfulfilled_dots)
        except:
            pass
        #creating centroid source and circle
        centroidlats = centroids[:,0]
        centroidlongs = centroids[:,1]
        centroid_source = ColumnDataSource(
            data=dict(
                lat=centroidlats,
                lon=centroidlongs,
                 alpha=alpha))
        centroid_dots = Circle(x="lon", y="lat", size=45, fill_color='#8B008B', fill_alpha='alpha', line_color=None)
        plot.add_glyph(centroid_source, centroid_dots)

        #finishing the plot
        plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())
        show(plot)
def tripsPlot():

    weights_y = None

    df_solo_trips = []
    df_companion_trips = []

    try:
        df_solo_trips = pd.read_sql_query("select * from trips where passenger_companion = '' ",
                                 app.config['SQLALCHEMY_DATABASE_URI'])
    except Exception as e:
        pass

    try:
        df_companion_trips = pd.read_sql_query("select * from trips where passenger_companion != '' ",
                                 app.config['SQLALCHEMY_DATABASE_URI'])
    except Exception as e:
        pass


    if (len(df_solo_trips) == 0 
        and len(df_companion_trips) == 0):
        return ["","",""]

    # Make sure we have a default bar height
    # in case there is no Weight data to show
    weights_y = weights_y if weights_y is not None else [0,9]
    highestWeight_y = int(sorted(weights_y)[-1])
    lowestWeight_y = int(sorted(weights_y)[0])

    # tripsBarHeight = height of the vertical bar 
    #                   which depends on max height of weights_y
    #                   + 10%
    # tripsBarStart = left start of the bar
    # tripsBarEnd = right end of the bar
    # tripsBarColors = global if one "color",
    #                   individual if an array
    #                   ["color_1", "color_2" [,...]]

    # Solo trips horizontal bars data
    tripsBarHeight = (highestWeight_y - lowestWeight_y) + (highestWeight_y - lowestWeight_y)*0.1
    tripsBarStart = df_solo_trips['departure_date']
    tripsBarEnd = df_solo_trips['return_date']
    tripsBarColors = "red" # Or individual colors for each value ["Cyan", "red",...]

    # Group trips horizontal bars data
    tripsBarGroupStart = df_companion_trips['departure_date']
    tripsBarGroupEnd = df_companion_trips['return_date']
    tripsBarGroupColors = "blue"

    # designing the plot style and information
    hover = HoverTool(show_arrow=True,
                      point_policy='follow_mouse',
                      tooltips=[
                      ("Trip from", " @left{%F}"),
                      ("to", " @right{%F}")],
                      formatters={
                        # use 'datetime' formatter for 'date' fields
                        # default 'numeral' formatter for other fields            
                        '@left' : 'datetime',
                        '@right' : 'datetime'})
    box = BoxSelectTool()
    wheel = WheelZoomTool()
    panTool = PanTool()
    boxZoomTool = BoxZoomTool()
    resetTool = ResetTool()

    TOOLS = [hover, box, wheel, panTool, boxZoomTool, resetTool]

    fig = figure(title = 'Trips dates',
                 x_axis_label='Dates',
                 x_axis_type="datetime",
                 plot_width=650,
                 plot_height=450,
                 sizing_mode='scale_both',
                 tools=TOOLS)

    fig.hbar(name = "red",
             y = highestWeight_y*0.96,
             height = tripsBarHeight,
             left = tripsBarStart,
             right = tripsBarEnd,
             color = tripsBarColors)

    fig.hbar(name = "blue",
             y = highestWeight_y*0.96,
             height = tripsBarHeight,
             left = tripsBarGroupStart,
             right = tripsBarGroupEnd,
             color = tripsBarGroupColors)

    # Technicalities to show the graph
    curdoc().add_root(fig)

    cdn_javascript = CDN.js_files[0]
    bokehScriptComponent, bokehDivComponent = components(fig)
    graph = [cdn_javascript, bokehScriptComponent, bokehDivComponent]

    return graph
Exemplo n.º 28
0
plot.title.text = "Austin"

source = ColumnDataSource(
    data=dict(
        lat=[30.2861, 30.2855, 30.2869],
        lon=[-97.7394, -97.7390, -97.7405],
        fill=['orange', 'blue', 'green']
    )
)

circle = Circle(x="lon", y="lat", size=15, fill_color="fill", line_color="black")
plot.add_glyph(source, circle)

pan = PanTool()
wheel_zoom = WheelZoomTool()
box_select = BoxSelectTool()

plot.add_tools(pan, wheel_zoom, box_select)

xformatter = MercatorTickFormatter(dimension="lon")
xticker = MercatorTicker(dimension="lon")
xaxis = LinearAxis(formatter=xformatter, ticker=xticker)
plot.add_layout(xaxis, 'below')

yformatter = MercatorTickFormatter(dimension="lat")
yticker = MercatorTicker(dimension="lat")
yaxis = LinearAxis(formatter=yformatter, ticker=yticker)
plot.add_layout(yaxis, 'left')

doc = Document()
doc.add_root(plot)
Exemplo n.º 29
0
    def makeMatrix(self, ds, filterMin, filterMax, reorder):
        # getting data from FileLoader and creating the right format

        dataSetSort = DataSetSort()
        if reorder == 0:
            nodes = ds.getDoubleList(filterMin, filterMax, True)
        elif reorder == 1:
            dsCopy = DataSet(ds.getNodes())
            dsCopy.makeUndirectionalAdd()
            nodes = dsCopy.getDoubleList(filterMin, filterMax, True)
        elif reorder == 2:
            dataSetSort.DesConnectionSort(ds)
            nodes = ds.getDoubleList(filterMin, filterMax, True)
        elif reorder == 3:
            dataSetSort.DesStrengthSort(ds)
            nodes = ds.getDoubleList(filterMin, filterMax, True)
        elif reorder == 4:
            nodes = ds.distanceMatrix(True)
        elif reorder == 5:
            dataSetSort.robinsonSort(ds)
            nodes = ds.getDoubleList(filterMin, filterMax, True)

        names = ds.getNames()
        yNames = names.copy()
        yNames.reverse()

        df = pd.DataFrame(
            nodes,
            columns=yNames,
            index=names)
        df.index.name = 'X'
        df.columns.name = 'Y'

        # Prepare data.frame in the right format
        df = df.stack().rename("value").reset_index()


        # Making the plot html file
        output_file("matrixPlot.html")

        # Creating the array containing the colors
        colorList = []

        i = 0
        while i < 256:
            color = wc.rgb_to_hex((255-(i-10), 255-(i-20), 255-(i-30)))
            colorList.append(color)
            i = i + 10

        #colorList = [(23, 165, 137), (19, 141, 117), (40, 180, 99), (36, 113, 163)
        #             , (31, 97, 141), (17, 122, 101), (46, 134, 193), (34, 153, 84)]#,(202, 111, 30), (186, 74, 0)]
        #colors = []
        #for i in colorList:
        #    color = wc.rgb_to_hex(i)
        #    colors.append(color)

        colors = colorList

        # This part maps the colors at intervals
        mapper = LinearColorMapper(
            palette=colors, low=df.value.min(), high=df.value.max())

        # Creating the figure
        p = figure(
            plot_width=500,
            plot_height=500,
            x_range=list(df.X.drop_duplicates()),
            y_range=list(df.Y.drop_duplicates()),

            # Adding a toolbar
            #toolbar_location="right",
            #tools="hover,pan,box_zoom,undo,redo,reset,save",
            x_axis_location="above")

        node_hover_tool = HoverTool(tooltips=[("Name X Axis", "@X"), ("Name Y Axis", "@Y"), ("Relation Strength", "@value")])

        # plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool())
        p.add_tools(node_hover_tool, TapTool(), BoxSelectTool(), BoxZoomTool(), UndoTool(), RedoTool())
        p.toolbar_location = 'right'

        # Create rectangle for heatmap
        p.rect(
            x="X",
            y="Y",
            width=1,
            height=1,
            source=ColumnDataSource(df),
            line_color=None,
            fill_color=transform('value', mapper))

        # Add legend
        color_bar = ColorBar(
            color_mapper=mapper,
            location=(0, 0),
            ticker=BasicTicker(desired_num_ticks=len(colors)))

        if len(list(df.X.drop_duplicates())) > p.plot_width / 10:
            p.xaxis.visible = False
        else:
            pass
        if len(list(df.Y.drop_duplicates())) > p.plot_height / 10:
            p.yaxis.visible = False
        else:
            pass

        p.xaxis.major_label_orientation = 'vertical'
        p.add_layout(color_bar, 'right')
        return p
Exemplo n.º 30
0
                   line_alpha=0.5)
cty = plot.add_glyph(source, cty_glyph)
hwy = plot.add_glyph(source, hwy_glyph)

# Add the tools
tooltips = [
    ("Manufacturer", "@manufacturer"),
    ("Model", "@model"),
    ("Displacement", "@displ"),
    ("Year", "@year"),
    ("Cylinders", "@cyl"),
    ("Transmission", "@trans"),
    ("Drive", "@drv"),
    ("Class", "@class"),
]
cty_hover_tool = HoverTool(renderers=[cty],
                           tooltips=tooltips + [("City MPG", "@cty")])
hwy_hover_tool = HoverTool(renderers=[hwy],
                           tooltips=tooltips + [("Highway MPG", "@hwy")])
select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions=['width'])
plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool)

layout = vplot(plot, data_table)

if __name__ == "__main__":
    filename = "data_tables.html"
    with open(filename, "w") as f:
        f.write(file_html(layout, INLINE, "Data Tables"))
    print("Wrote %s" % filename)
    view(filename)
Exemplo n.º 31
0
def large_plot(n):
    from bokeh.models import (Plot, LinearAxis, Grid, GlyphRenderer,
                              ColumnDataSource, DataRange1d, PanTool,
                              ZoomInTool, ZoomOutTool, WheelZoomTool,
                              BoxZoomTool, BoxSelectTool, SaveTool, ResetTool)
    from bokeh.models.layouts import Column
    from bokeh.models.glyphs import Line

    col = Column()
    objects = set([col])

    for i in xrange(n):
        source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1]))
        xdr = DataRange1d()
        ydr = DataRange1d()
        plot = Plot(x_range=xdr, y_range=ydr)
        xaxis = LinearAxis(plot=plot)
        yaxis = LinearAxis(plot=plot)
        xgrid = Grid(plot=plot, dimension=0)
        ygrid = Grid(plot=plot, dimension=1)
        tickers = [
            xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter
        ]
        glyph = Line(x='x', y='y')
        renderer = GlyphRenderer(data_source=source, glyph=glyph)
        plot.renderers.append(renderer)
        pan = PanTool()
        zoom_in = ZoomInTool()
        zoom_out = ZoomOutTool()
        wheel_zoom = WheelZoomTool()
        box_zoom = BoxZoomTool()
        box_select = BoxSelectTool()
        save = SaveTool()
        reset = ResetTool()
        tools = [
            pan, zoom_in, zoom_out, wheel_zoom, box_zoom, box_select, save,
            reset
        ]
        plot.add_tools(*tools)
        col.children.append(plot)
        objects |= set([
            xdr,
            ydr,
            xaxis,
            yaxis,
            xgrid,
            ygrid,
            renderer,
            renderer.view,
            glyph,
            source,
            source.selected,
            source.selection_policy,
            plot,
            plot.x_scale,
            plot.y_scale,
            plot.toolbar,
            plot.title,
            box_zoom.overlay,
            box_select.overlay,
        ] + tickers + tools)

    return col, objects