Ejemplo n.º 1
0
    def network_dynamic(self, df):
        graph = nx.from_pandas_edgelist(df, 'word1', 'word2', 'count')

        # Establish which categories will appear when hovering over each node
        HOVER_TOOLTIPS = [("", "@index")]

        # Create a plot — set dimensions, toolbar, and title
        plot = figure(tooltips=HOVER_TOOLTIPS,
                      tools="pan,wheel_zoom,save,reset",
                      active_scroll='wheel_zoom',
                      x_range=Range1d(-10.1, 10.1),
                      y_range=Range1d(-10.1, 10.1),
                      plot_width=1000,
                      title='')

        # Create a network graph object with spring layout
        network_graph = from_networkx(graph,
                                      nx.spring_layout,
                                      scale=10,
                                      center=(0, 0))

        # Set node size and color
        network_graph.node_renderer.glyph = Circle(size=15,
                                                   fill_color='skyblue')

        # Set edge opacity and width
        network_graph.edge_renderer.glyph = MultiLine(line_alpha=0.5,
                                                      line_width=1)

        #Add network graph to the plot
        plot.renderers.append(network_graph)

        script, div = components(plot)
        return script, div
Ejemplo n.º 2
0
 def set_landuse_circle(self, product):
     self._landuse_circle = Circle(x=self._center.lon(),
                                   y=self._center.lat(),
                                   size=fn.radius_deg(self, product),
                                   line_color="#3288bd",
                                   fill_color="white",
                                   line_width=3)
Ejemplo n.º 3
0
def scatter_glyphs(data, x_field):
    fields = data.columns.values
    sources = dict(zip(fields, np.zeros(len(fields))))
    glyphs = dict(zip(fields, np.zeros(len(fields))))
    for field in fields:
        sources[field] = ColumnDataSource(data=dict(x=data[x_field], y=data[field]))
        glyphs[field] = Circle(x="x", y="y", line_color="blue", fill_color="blue")
    return sources, glyphs
Ejemplo n.º 4
0
def circle_markers(data):
    fields = data.columns.values
    sources = dict(zip(fields, np.zeros(len(fields))))
    glyphs = dict(zip(fields, np.zeros(len(fields))))
    for field in fields:
        sources[field] = ColumnDataSource(data=dict(x=data.index.values, y=data[field].values))
        glyphs[field] = Circle(x="x", y="y", size=10, line_color="red", fill_color="red", fill_alpha=0.5)
    # plot.add_glyph(source, glyph)
    return sources, glyphs
Ejemplo n.º 5
0
    def _init_asterisk(self):
        ''' The asterisk is the mark for the current selected sample
                * self.asterisk - red asterisk on the background
                * self.aux_asterisk_asterisk - marked asterisk
                * self.aux_asteris_circle - center asterisk marked
        '''
        self.asterisk = self.plot.asterisk(
            x='{}_{}'.format(self.tab, self.x),
            y='{}_{}'.format(self.tab, self.y),
            size=20,
            line_color=Reds3[0],
            line_width=3,
            source=self.env.asterisk_source,
        )
        # NOTE: The following object is to avoid a shadow for a
        #       few ms when a new selection is made
        self.asterisk.nonselection_glyph = Asterisk(
            line_color=None, fill_color=None,
            line_alpha=0.0, fill_alpha=0.0
        )

        self.aux_asterisk = self.plot.asterisk(
            x='{}_{}'.format(self.tab, self.x),
            y='{}_{}'.format(self.tab, self.y),
            size=17,
            line_color='yellow',
            line_width=1,
            source=self.env.asterisk_source,
        )
        self.aux_asterisk.nonselection_glyph = Asterisk(
            line_color=None, fill_color=None,
            line_alpha=0.0, fill_alpha=0.0
        )

        self.aux_asterisk_circle = self.plot.circle(
            x='{}_{}'.format(self.tab, self.x),
            y='{}_{}'.format(self.tab, self.y),
            size=5,
            fill_color='yellow',
            line_width=None,
            source=self.env.asterisk_source,
        )
        self.aux_asterisk_circle.nonselection_glyph = Circle(
            line_color=None, fill_color=None,
            line_alpha=0.0, fill_alpha=0.0
        )
Ejemplo n.º 6
0
    def _visdata(self):
        self._setcolors()

        # make sure data is in list format
        datasets = [pytplot.data_quants[self.tvar_name]]
        for oplot_name in pytplot.data_quants[self.tvar_name].attrs['plot_options']['overplots']:
            datasets.append(pytplot.data_quants[oplot_name])
        
        for dataset in datasets:                
            # Get Linestyle
            line_style = None
            if 'line_style' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['line_opt']:
                line_style = pytplot.data_quants[self.tvar_name].attrs['plot_options']['line_opt']['line_style']

            coords = pytplot.tplot_utilities.return_interpolated_link_dict(dataset, ['alt'])
            t_link = coords['alt'].coords['time'].values
            x = coords['alt'].values
            df = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(dataset.name, no_spec_bins=True)
            # Create lines from each column in the dataframe
            for column_name in df.columns:
                y = df[column_name]

                t_tvar = df.index.values
                y = df.values
                while t_tvar[-1] > t_link[-1]:
                    t_tvar = np.delete(t_tvar, -1)
                    y = np.delete(y, -1)
                while t_tvar[0] < t_link[0]:
                    t_tvar = np.delete(t_tvar, 0)
                    y = np.delete(y, 0)
                
                if self._getyaxistype() == 'log':
                    y[y <= 0] = np.NaN

                line_source = ColumnDataSource(data=dict(x=x, y=y))
                if self.auto_color:
                    line = Circle(x='x', y='y', line_color=self.colors[self.linenum % len(self.colors)])
                else:
                    line = Circle(x='x', y='y')
                if 'line_style' not in pytplot.data_quants[self.tvar_name].attrs['plot_options']['line_opt']:
                    if line_style is not None:
                        line.line_dash = line_style[self.linenum % len(line_style)]
                else:
                    line.line_dash = pytplot.data_quants[self.tvar_name].attrs['plot_options']['line_opt']['line_style']
                self.lineglyphs.append(self.fig.add_glyph(line_source, line))
                self.linenum += 1
Ejemplo n.º 7
0
""",
width=1200, height=420)
curdoc().add_root(pre_intro)

##### PLOT FOR EACH MONTH #####################################################

monthView = figure(x_range=[0,13], tools=['wheel_zoom', 'pan', 'tap', 'reset'], title="Monthly Plot of Traffic by Car Type")
monthHover = HoverTool(tooltips=[('Car Type', '@cartype'), ('Count', '$y{00000}'), ('Month', '@month')])
monthView.add_tools(monthHover)
monthLines = monthView.multi_line(xs="x", ys="y", line_color="colors", line_width=3, alpha="alpha", legend="cartype", source=monthLineCDS)
monthCircles = monthView.circle(x="x", y="y", size=10, fill_color="colors", line_color="colors", alpha="alpha", source=monthCircleCDS)
monthView.xaxis.axis_label = "Month"
monthView.yaxis.axis_label = "Traffic activity"
monthView.xaxis.ticker = []
monthView.min_border_bottom=100;
monthCircles.selection_glyph = Circle(fill_alpha=0.8, line_alpha=0.8)
monthCircles.nonselection_glyph = Circle(fill_alpha=0.3, line_alpha=0.3)

monthLines.data_source.on_change('selected', line_callback)
monthCircles.data_source.on_change('selected', circle_callback)

##### PLOT FOR A WEEK #########################################################

weekView = figure(x_range=[-1,7], tools=['wheel_zoom', 'pan', 'tap', 'reset'], title="Plot of Traffic in January by Weekday and Car Type")
weekHover = HoverTool(tooltips=[('Car Type', '@cartype'), ('Count', '$y{0000}'), ('Day', '@weekday')])
weekView.add_tools(weekHover)
weekView.min_border_bottom=100;
weekLines = weekView.multi_line(xs='x', ys='y', line_color='colors', line_width=3, alpha="alpha", source=weekLineCDS)
weekCircles = weekView.circle(x="x", y="y", size=6, fill_color="colors", line_color="colors", alpha="alpha", source=weekCircleCDS)
weekView.xaxis.axis_label = "Week"
weekView.yaxis.axis_label = "Traffic activity"
Ejemplo n.º 8
0
    def plotbokeh(self, glyphType="line", glyphSize=1, fillColor="red",
                  lineColor="black", lineAlpha=1, fillAlpha=0.1, lineDash='solid'):

        # glyphs
        from bokeh.models.glyphs import Rect, Line
        from bokeh.models.renderers import GlyphRenderer
        from bokeh.models.markers import (Circle, Cross,
                                          Diamond, Square,
                                          Triangle)

        # data
        from bokeh.models import ColumnDataSource

        # Parameters of the histogram
        lo = self.low
        hi = self.high
        num = self.num
        bin_width = (hi-lo)/num
        x = list()
        y = list()
        center = lo
        for v in self.values:
            if not math.isnan(v.mean):
                y.append(v.mean)
                x.append(center+bin_width/2)
                center += bin_width

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

        glyph = None
        if glyphType == "square":
            glyph = Square(
                x='x',
                y='y',
                line_color=lineColor,
                fill_color=fillColor,
                line_alpha=lineAlpha,
                size=glyphSize,
                line_dash=lineDash)
        elif glyphType == "diamond":
            glyph = Diamond(
                x='x',
                y='y',
                line_color=lineColor,
                fill_color=fillColor,
                line_alpha=lineAlpha,
                size=glyphSize,
                line_dash=lineDash)
        elif glyphType == "cross":
            glyph = Cross(
                x='x',
                y='y',
                line_color=lineColor,
                fill_color=fillColor,
                line_alpha=lineAlpha,
                size=glyphSize,
                line_dash=lineDash)
        elif glyphType == "triangle":
            glyph = Triangle(
                x='x',
                y='y',
                line_color=lineColor,
                fill_color=fillColor,
                line_alpha=lineAlpha,
                size=glyphSize,
                line_dash=lineDash)
        elif glyphType == "circle":
            glyph = Circle(
                x='x',
                y='y',
                line_color=lineColor,
                fill_color=fillColor,
                line_alpha=lineAlpha,
                size=glyphSize,
                line_dash=lineDash)
        elif glyphType == "histogram":
            w = [bin_width for _ in x]
            h = y
            y = [yy/2 for yy in y]
            source = ColumnDataSource(dict(x=x, y=y, w=w, h=h))
            glyph = Rect(
                x='x',
                y='y',
                width='w',
                height='h',
                fill_alpha=fillAlpha,
                line_color=lineColor,
                fill_color=fillColor)
        else:
            glyph = Line(
                x='x',
                y='y',
                line_color=lineColor,
                line_alpha=lineAlpha,
                line_width=glyphSize,
                line_dash=lineDash)

        return GlyphRenderer(glyph=glyph, data_source=source)
Ejemplo n.º 9
0
    def plotbokeh(self, glyphType="line", glyphSize=1, fillColor="red",
                  lineColor="black", lineAlpha=1, fillAlpha=0.1, lineDash='solid'):

        # glyphs
        from bokeh.models.glyphs import Rect, Line
        from bokeh.models.renderers import GlyphRenderer
        from bokeh.models.markers import (Circle, Cross,
                                          Diamond, Square,
                                          Triangle)

        # data
        from bokeh.models import ColumnDataSource

        # Parameters of the histogram
        lo = self.low
        hi = self.high
        num = self.numFilled
        bin_width = (hi-lo)/num
        x = list()
        center = lo
        for _ in range(num):
            x.append(center+bin_width/2)
            center += bin_width
        y = [v.entries for _, v in sorted(self.bins.items())]

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

        glyph = None
        if glyphType == "square":
            glyph = Square(
                x='x',
                y='y',
                line_color=lineColor,
                fill_color=fillColor,
                line_alpha=lineAlpha,
                size=glyphSize,
                line_dash=lineDash)
        elif glyphType == "diamond":
            glyph = Diamond(
                x='x',
                y='y',
                line_color=lineColor,
                fill_color=fillColor,
                line_alpha=lineAlpha,
                size=glyphSize,
                line_dash=lineDash)
        elif glyphType == "cross":
            glyph = Cross(
                x='x',
                y='y',
                line_color=lineColor,
                fill_color=fillColor,
                line_alpha=lineAlpha,
                size=glyphSize,
                line_dash=lineDash)
        elif glyphType == "triangle":
            glyph = Triangle(
                x='x',
                y='y',
                line_color=lineColor,
                fill_color=fillColor,
                line_alpha=lineAlpha,
                size=glyphSize,
                line_dash=lineDash)
        elif glyphType == "circle":
            glyph = Circle(
                x='x',
                y='y',
                line_color=lineColor,
                fill_color=fillColor,
                line_alpha=lineAlpha,
                size=glyphSize,
                line_dash=lineDash)
        elif glyphType == "rect":
            glyph = Rect(
                x='x',
                y='y',
                width=bin_width,
                height=0.1,
                fill_alpha=fillAlpha,
                line_color=lineColor,
                fill_color=fillColor)
        elif glyphType == "errors":
            ci = [2.*v for v in self.confidenceIntervalValues()]
            source = ColumnDataSource(data=dict(x=x, y=y, ci=ci))
            glyph = Rect(
                x='x',
                y='y',
                width=bin_width,
                height='ci',
                fill_alpha=fillAlpha,
                line_color=lineColor,
                fill_color=fillColor)
        elif glyphType == "histogram":
            h = y
            y = [yy/2 for yy in y]
            source = ColumnDataSource(dict(x=x, y=y, h=h))
            glyph = Rect(
                x='x',
                y='y',
                width=bin_width,
                height='h',
                fill_alpha=fillAlpha,
                line_color=lineColor,
                fill_color=fillColor)
        else:
            glyph = Line(
                x='x',
                y='y',
                line_color=lineColor,
                line_alpha=lineAlpha,
                line_width=glyphSize,
                line_dash=lineDash)

        return GlyphRenderer(glyph=glyph, data_source=source)
Ejemplo n.º 10
0
def create_bar_chart(data, title, hover_tool, colors):
    """Creates a bar chart plot with the exact styling for the centcom
       dashboard. Pass in data as a dictionary, desired plot title,
       name of x axis, y axis and the hover tool HTML.
    """

    xdr = DataRange1d(bounds='auto')
    ydr = DataRange1d(bounds='auto')

    hover = HoverTool(tooltips="""
            <div>
            	<p><span style="font-weight: bold;">%s</span> - %s</p>
				<p>%s million %s passengers</p>
			</div>
    	""" % ("@airline", "@date{%b %Y}", "$y", "$name"),
                      formatters={'date': 'datetime'},
                      names=['domestic', 'international', 'total'])

    tools = [
        hover, 'pan', 'box_zoom', 'zoom_in', 'zoom_out', 'wheel_zoom', 'reset'
    ]

    plot = figure(title=title,
                  x_range=xdr,
                  y_range=ydr,
                  plot_width=1200,
                  plot_height=800,
                  h_symmetry=False,
                  v_symmetry=False,
                  min_border=0,
                  toolbar_location="above",
                  tools=tools,
                  outline_line_color="#666666",
                  x_axis_type='datetime',
                  border_fill_color='#DBECFC')

    plot.left[0].formatter.use_scientific = False

    legendItems = []

    for airline in data:

        color = colors[airline]
        source = ColumnDataSource(data=data[airline])
        legendItems.append(([airline,
                             "Domestic"], (plot.line(x='date',
                                                     y='domestic',
                                                     line_color=color,
                                                     line_width=2,
                                                     line_alpha=0.6,
                                                     line_dash='dashed',
                                                     source=source))))
        legendItems.append(([airline, "Domestic"],
                            plot.circle(x='date',
                                        y='domestic',
                                        size=5,
                                        fill_color=color,
                                        source=source,
                                        name='domestic',
                                        line_color=color)))
        legendItems[-1][1].hover_glyph = Circle(line_width=6,
                                                line_color=color,
                                                line_alpha=0.2,
                                                fill_color=color)

        source = ColumnDataSource(data=data[airline])
        legendItems.append(([airline, "Total"],
                            plot.line(x='date',
                                      y='total',
                                      line_color=color,
                                      line_width=2,
                                      line_alpha=0.6,
                                      source=source)))
        legendItems.append(([airline, "Total"],
                            plot.circle(x='date',
                                        y='total',
                                        size=8,
                                        fill_color=color,
                                        line_color=color,
                                        source=source,
                                        name='total')))
        legendItems[-1][1].hover_glyph = Circle(line_width=9,
                                                line_color=color,
                                                line_alpha=0.2,
                                                fill_color=color)

        source = ColumnDataSource(data=data[airline])
        legendItems.append(([airline, "International"],
                            plot.line(x='date',
                                      y='international',
                                      line_color=color,
                                      line_width=2,
                                      line_alpha=0.6,
                                      line_dash='dotted',
                                      source=source)))
        legendItems.append(([airline, "International"],
                            plot.circle(x='date',
                                        y='international',
                                        size=5,
                                        fill_color=color,
                                        line_color=color,
                                        source=source,
                                        name='international')))
        legendItems[-1][1].hover_glyph = Circle(line_width=6,
                                                line_color=color,
                                                line_alpha=0.2,
                                                fill_color=color)

#Create legend for airline
    legendAirlines = CategorialLegend(items=legendItems, click_policy='hide')
    plot.add_layout(legendAirlines, 'right')

    xaxis = LinearAxis()
    yaxis = LinearAxis()

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
    plot.toolbar.logo = None
    plot.min_border_top = 0
    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = "#999999"
    plot.ygrid.grid_line_alpha = 0.1

    #Style Y axis
    plot.yaxis.axis_label = "Number of Passengers (Millions)"
    plot.yaxis.axis_label_text_font_size = '12pt'
    plot.yaxis.axis_label_text_font_style = 'normal'

    #Style X axis
    plot.xaxis.axis_label = "Year"
    plot.xaxis.major_label_orientation = 1
    plot.xaxis.axis_label_text_font_size = '12pt'
    plot.xaxis.axis_label_text_font_style = 'normal'
    plot.xaxis[0].formatter.days = '%b %Y'

    return plot
Ejemplo n.º 11
0
N = 9
x = np.linspace(-2, 2, N)
y = x**2
sizes = np.linspace(10, 20, N)

source = ColumnDataSource(dict(x=x, y=y, sizes=sizes))

plot = Plot(title=None,
            plot_width=300,
            plot_height=300,
            min_border=0,
            toolbar_location=None)

glyph = Circle(x="x",
               y="y",
               size="sizes",
               line_color="#3288bd",
               fill_color="white",
               line_width=3)
plot.add_glyph(source, glyph)

xaxis = LinearAxis()
plot.add_layout(xaxis, 'below')

yaxis = LinearAxis()
plot.add_layout(yaxis, 'left')

plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

curdoc().add_root(plot)
Ejemplo n.º 12
0
    def bokeh(self,
              glyphType="line",
              glyphSize=1,
              fillColor="red",
              lineColor="black",
              lineAlpha=1,
              fillAlpha=0.1,
              lineDash='solid'):

        #glyphs
        from bokeh.models.glyphs import Rect, Segment, Line, Patches, Arc
        from bokeh.models.renderers import GlyphRenderer
        from bokeh.models.markers import (Marker, Asterisk, Circle,
                                          CircleCross, CircleX, Cross, Diamond,
                                          DiamondCross, InvertedTriangle,
                                          Square, SquareCross, SquareX,
                                          Triangle, X)

        #data
        from bokeh.models import ColumnDataSource

        from math import sqrt

        #Parameters of the histogram
        l = self.low
        h = self.high
        num = self.num
        bin_width = (h - l) / num
        x = list()
        y = list()
        center = l
        for v in self.values:
            if not math.isnan(v.mean):
                y.append(v.mean)
                x.append(center + bin_width / 2)
                center += bin_width

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

        glyph = None
        if glyphType == "square":
            glyph = Square(x='x',
                           y='y',
                           line_color=lineColor,
                           fill_color=fillColor,
                           line_alpha=lineAlpha,
                           size=glyphSize,
                           line_dash=lineDash)
        elif glyphType == "diamond":
            glyph = Diamond(x='x',
                            y='y',
                            line_color=lineColor,
                            fill_color=fillColor,
                            line_alpha=lineAlpha,
                            size=glyphSize,
                            line_dash=lineDash)
        elif glyphType == "cross":
            glyph = Cross(x='x',
                          y='y',
                          line_color=lineColor,
                          fill_color=fillColor,
                          line_alpha=lineAlpha,
                          size=glyphSize,
                          line_dash=lineDash)
        elif glyphType == "triangle":
            glyph = Triangle(x='x',
                             y='y',
                             line_color=lineColor,
                             fill_color=fillColor,
                             line_alpha=lineAlpha,
                             size=glyphSize,
                             line_dash=lineDash)
        elif glyphType == "circle":
            glyph = Circle(x='x',
                           y='y',
                           line_color=lineColor,
                           fill_color=fillColor,
                           line_alpha=lineAlpha,
                           size=glyphSize,
                           line_dash=lineDash)
        elif glyphType == "errors":
            w = [bin_width for _ in x]
            h = [
                sqrt(v.variance / v.entries) if v.entries > 0 else 0.0
                for v in self.values
            ]
            source = ColumnDataSource(dict(x=x, y=y, w=w, h=h))
            glyph = Rect(x='x',
                         y='y',
                         width='w',
                         height='h',
                         fill_alpha=fillAlpha,
                         line_color=lineColor,
                         fill_color=fillColor)
        elif glyphType == "histogram":
            w = [bin_width for _ in x]
            h = y
            y = [yy / 2 for yy in y]
            source = ColumnDataSource(dict(x=x, y=y, w=w, h=h))
            glyph = Rect(x='x',
                         y='y',
                         width='w',
                         height='h',
                         fill_alpha=fillAlpha,
                         line_color=lineColor,
                         fill_color=fillColor)
        else:
            glyph = Line(x='x',
                         y='y',
                         line_color=lineColor,
                         line_alpha=lineAlpha,
                         line_width=glyphSize,
                         line_dash=lineDash)

        return GlyphRenderer(glyph=glyph, data_source=source)
Ejemplo n.º 13
0
def winLossChatPlot(request, hero_id):

    # assemble data
    heroInstance = models.Hero.objects.get(valveID=hero_id)
    args = ['heroes', str(heroInstance.valveID), 'matchups']

    # list of dicts sorted by n_matches keyed on heroID
    # {'hero_id': 56, 'games_played': 6, 'wins': 6}
    heroMatchupData = query_opendota_api_route_args(args, sleepTime=0.)

    TOOLTIPS = [
        ('Hero', '@hero'),
        ('Win, Loss', '($x{int}, $y{int})'),
    ]

    TOOLS = 'pan,wheel_zoom,box_zoom,reset'

    # init scatter plot
    bokehAx = bp.figure(width=750, sizing_mode='scale_height', tools=TOOLS)

    sourceDict = {
        'url': [],
        'x': [],
        'y': [],
        'hero': [],
    }

    # populate the source dict with matchup data
    for matchupDict in heroMatchupData:
        heroMatchup = models.Hero.objects.get(valveID=matchupDict['hero_id'])
        heroIconURL = heroMatchup.get_absolute_image_url
        heroIconURL = request.build_absolute_uri(heroMatchup.icon.url)
        nGames = matchupDict['games_played']
        nWins = matchupDict['wins']
        nLosses = nGames - nWins

        sourceDict['url'].append(heroIconURL)
        sourceDict['x'].append(nWins)
        sourceDict['y'].append(nLosses)
        sourceDict['hero'].append(heroMatchup.prettyName)

    # plot it
    source = ColumnDataSource(sourceDict)

    # HoverTool doesn't work with ImageURL, so plot transparent glyphs
    circle_glyph = Circle(x='x',
                          y='y',
                          size=10,
                          line_color='white',
                          fill_color='white',
                          line_alpha=1.,
                          fill_alpha=1.)
    circle_renderer = bokehAx.add_glyph(source, circle_glyph)

    icon = ImageURL(url='url', x='x', y='y', w=None, h=None, anchor="center")
    bokehAx.add_glyph(source, icon)

    # tooltips
    hover = HoverTool(renderers=[circle_renderer], tooltips=TOOLTIPS)
    bokehAx.tools.append(hover)

    # labels etc
    bokehAx.title.text = ''
    bokehAx.xaxis.axis_label = 'Wins (professional games)'
    bokehAx.yaxis.axis_label = 'Losses (professional games)'
    plotResponse = file_html(bokehAx, CDN, 'winLossChatPlot')

    return HttpResponse(plotResponse)
Ejemplo n.º 14
0
hover.point_policy = "follow_mouse"
hover.tooltips = [
    ("name", "@name"),
    ("area", "@area"),
    ("vegetarians", "@veges"),
    ("(long, lat)", "($x, $y)"),
]

r = [fn.radius_deg(selected_country, beef)]
x = [selected_country.get_center().lon()]
y = [selected_country.get_center().lat()]

source_circle = ColumnDataSource(data=dict(x=x, y=y, r=r))
glyph = Circle(x="x",
               y="y",
               radius="r",
               line_color="#3288bd",
               fill_color="white",
               line_width=3)
p.add_glyph(source_circle, glyph)

# widgets
slider_vegetarians = Slider(title="Vegetarians in " +
                            selected_country.get_name() + " in percent",
                            value=selected_country.get_veges(),
                            start=0.0,
                            end=100.0,
                            step=0.1)

checkbox_button_group = CheckboxButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
Ejemplo n.º 15
0
    def plot_urls(self):
        """
        Visualize crawler activity by showing the most recently crawled URLs and the fetch time.
        """

        self.session.load_document(self.document)
        plot = self.document.context.children[0]

        # don't plot if no URLs available
        if not (self.open_urls or self.closed_urls):
            return

        # x0/x0, left and right boundaries of segments, correspond to fetch time
        x0 = []
        x = []
        # y-axis, name of URL being fetched
        urls = []

        # maintain x and URL of circles in a separate list
        circles = []
        circle_urls = []

        current_time = np.datetime64(datetime.now())

        # For open URLs (not completed fetching), draw a segment from start time to now
        for url, start_t in self.open_urls.items():
            url = NutchUrlTrails.strip_url(url)
            x0.append(start_t)
            x.append(current_time)
            urls.append(url)

        # For closed URLs (completed fetching), draw a segment from start to end time, and a circle as well.
        for url, (start_t, end_t) in self.closed_urls.items():
            url = NutchUrlTrails.strip_url(url)
            x0.append(start_t)
            x.append(end_t)
            circles.append(end_t)
            urls.append(url)
            circle_urls.append(url)

        x0 = np.asarray(x0)
        x = np.asarray(x)
        circles = np.asarray(circles)

        # sort segments
        sort_index = np.argsort(x0)[::-1]
        x0 = x0[sort_index]
        x = x[sort_index]
        urls = [urls[i] for i in sort_index]

        # sort circles
        if self.closed_urls:
            circle_sort_index = np.argsort(circles)[::-1]
            circles = circles[circle_sort_index]
            circle_urls = [circle_urls[i] for i in circle_sort_index]

        # Filter to latest num_url URLs (ascending order)
        # filter segments
        active_x0 = x0[:self.num_urls]
        active_x = x[:self.num_urls]
        active_urls = urls[:self.num_urls]

        min_x = min(active_x0)
        plot.x_range.start = min_x
        plot.x_range.end = np.datetime64(datetime.now())
        plot.y_range.factors = active_urls

        # make sure these are turned back on!
        # turn y axis grid lines back on
        for r in plot.renderers:
            if type(r) == Grid:
                r.grid_line_color = 'black'
                break

        # turn tickers and their labels back on
        plot.right[0].minor_tick_line_color = 'black'
        plot.right[0].major_tick_line_color = 'black'
        plot.right[0].major_label_text_font_size = '12pt'
        plot.below[0].minor_tick_line_color = 'black'
        plot.below[0].major_tick_line_color = 'black'
        plot.below[0].major_label_text_font_size = '12pt'

        # TODO: Find a more correct way to remove old segment/circle glyphs
        if self.old_circles:
            plot.renderers.pop()
            self.old_circles = None
        if self.old_segments:
            plot.renderers.pop()
            self.old_segments = None

        segment_source = ColumnDataSource(
            dict(x0=active_x0, x1=active_x, urls=active_urls))

        self.old_segments = Segment(x0="x0",
                                    y0="urls",
                                    x1="x1",
                                    y1="urls",
                                    line_color="orange",
                                    line_width=10)
        plot.add_glyph(segment_source, self.old_segments)

        if self.closed_urls and PLOT_CIRCLES:
            # filter circles (some of these might not be displayed)
            active_circles = circles[:self.num_urls]
            active_circle_urls = circle_urls[:self.num_urls]

            circle_source = ColumnDataSource(
                dict(x=active_circles, urls=active_circle_urls))

            self.old_circles = Circle(x="x",
                                      y="urls",
                                      size=12,
                                      fill_color="green",
                                      line_color="orange",
                                      line_width=2)
            plot.add_glyph(circle_source, self.old_circles)

        self.session.store_document(self.document, dirty_only=False)
Ejemplo n.º 16
0
# LatexLabelSet has to be added to the layout after LatexLegend! Otherwise the labels won't show.
figure1_labels = LatexLabelSet(x='x',
                               y='y',
                               text='names',
                               level='glyph',
                               x_offset=0,
                               y_offset=0,
                               source=f1.Perm_Label_source)

figure1.add_layout(figure1_labels)

### Figure 2: Define Geometry
Mohr_Circle_glyph = Circle(x='x',
                           y='y',
                           radius='radius',
                           radius_dimension='y',
                           fill_color='#c3c3c3',
                           fill_alpha=0.5)
Wedge_glyph = Wedge(x="x",
                    y="y",
                    radius="radius",
                    start_angle="sA",
                    end_angle="eA",
                    fill_color="firebrick",
                    fill_alpha=0.6,
                    direction="clock")
### Figure 2: Define Figure and add Geometry
figure2 = figure(title=figure_texts.data['text'][5],
                 tools="pan,save,wheel_zoom,reset",
                 x_range=(-25.5, 25.5),
                 y_range=(-25.5, 25.5),
Ejemplo n.º 17
0
    def bokeh(self,
              glyphType="line",
              glyphSize=1,
              fillColor="red",
              lineColor="black",
              lineAlpha=1,
              fillAlpha=0.1,
              lineDash='solid'):

        #glyphs
        from bokeh.models.glyphs import Rect, Segment, Line, Patches, Arc
        from bokeh.models.renderers import GlyphRenderer
        from bokeh.models.markers import (Marker, Asterisk, Circle,
                                          CircleCross, CircleX, Cross, Diamond,
                                          DiamondCross, InvertedTriangle,
                                          Square, SquareCross, SquareX,
                                          Triangle, X)

        #data
        from bokeh.models import ColumnDataSource

        #Parameters of the histogram
        l = self.low
        h = self.high
        num = self.num
        bin_width = (h - l) / num
        x = list()
        center = l
        for _ in range(num):
            x.append(center + bin_width / 2)
            center += bin_width
        y = self.numericalValues
        ci = [2. * v for v in self.confidenceIntervalValues()]

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

        glyph = None
        if glyphType == "square":
            glyph = Square(x='x',
                           y='y',
                           line_color=lineColor,
                           fill_color=fillColor,
                           line_alpha=lineAlpha,
                           size=glyphSize,
                           line_dash=lineDash)
        elif glyphType == "diamond":
            glyph = Diamond(x='x',
                            y='y',
                            line_color=lineColor,
                            fill_color=fillColor,
                            line_alpha=lineAlpha,
                            size=glyphSize,
                            line_dash=lineDash)
        elif glyphType == "cross":
            glyph = Cross(x='x',
                          y='y',
                          line_color=lineColor,
                          fill_color=fillColor,
                          line_alpha=lineAlpha,
                          size=glyphSize,
                          line_dash=lineDash)
        elif glyphType == "triangle":
            glyph = Triangle(x='x',
                             y='y',
                             line_color=lineColor,
                             fill_color=fillColor,
                             line_alpha=lineAlpha,
                             size=glyphSize,
                             line_dash=lineDash)
        elif glyphType == "circle":
            glyph = Circle(x='x',
                           y='y',
                           line_color=lineColor,
                           fill_color=fillColor,
                           line_alpha=lineAlpha,
                           size=glyphSize,
                           line_dash=lineDash)
        elif glyphType == "rect":
            glyph = Rect(x='x',
                         y='y',
                         width=bin_width,
                         height=0.1,
                         fill_alpha=fillAlpha,
                         line_color=lineColor,
                         fill_color=fillColor)
        elif glyphType == "errors":
            glyph = Rect(x='x',
                         y='y',
                         width=bin_width,
                         height='ci',
                         fill_alpha=fillAlpha,
                         line_color=lineColor,
                         fill_color=fillColor)
        elif glyphType == "histogram":
            h = y
            y = [yy / 2 for yy in y]
            source = ColumnDataSource(dict(x=x, y=y, h=h))
            glyph = Rect(x='x',
                         y='y',
                         width=bin_width,
                         height='h',
                         fill_alpha=fillAlpha,
                         line_color=lineColor,
                         fill_color=fillColor)
        else:
            glyph = Line(x='x',
                         y='y',
                         line_color=lineColor,
                         line_alpha=lineAlpha,
                         line_width=glyphSize,
                         line_dash=lineDash)

        return GlyphRenderer(glyph=glyph, data_source=source)
Ejemplo n.º 18
0
    def __init__(self, model):
        """
        Construct separation dashboard
        """
        # Save reference to model
        self.model = model

        ################################
        # Process button
        ################################

        self.process = Button(label="Generate",
                              button_type="primary",
                              name='process',
                              sizing_mode='scale_width',
                              css_classes=['generate'])
        self.process.js_on_click(CustomJS(code="toggleLoading()"))

        ################################
        # Widgets
        ################################

        # Data type selection
        self.data_type = RadioButtonGroup(
            labels=["All Data", "Experimental", "Simulated"],
            active=0,
            css_classes=['dtypes'])

        # Adsorbate drop-down selections
        self.g1_sel = Select(title="Adsorbate 1",
                             options=self.model.ads_list,
                             value=self.model.g1,
                             css_classes=['g-selectors'])
        self.g2_sel = Select(title="Adsorbate 2",
                             options=self.model.ads_list,
                             value=self.model.g2)

        # Temperature selection
        self.t_absolute = Spinner(value=self.model.t_abs,
                                  title='Temperature:',
                                  css_classes=['t-abs'])
        self.t_tolerance = Spinner(value=self.model.t_tol,
                                   title='Tolerance:',
                                   css_classes=['t-tol'])

        # Combined in a layout
        self.dsel_widgets = layout([
            [self.data_type],
            [self.g1_sel, self.g2_sel, self.t_absolute, self.t_tolerance],
        ],
                                   sizing_mode='scale_width',
                                   name="widgets")

        ################################
        # KPI Plots
        ################################

        # Top graph generation
        tooltip = load_tooltip()
        self.p_henry, rend1 = self.top_graph("K", "Henry coefficient (log)",
                                             self.model.data,
                                             self.model.errors, tooltip)
        self.p_loading, rend2 = self.top_graph(
            "L", "Uptake at selected pressure (bar)", self.model.data,
            self.model.errors, tooltip)
        self.p_wc, rend3 = self.top_graph(
            "W", "Working capacity in selected range (bar)", self.model.data,
            self.model.errors, tooltip)

        # Give graphs the same hover and select effect
        sel = Circle(fill_alpha=1, fill_color="red", line_color=None)
        nonsel = Circle(fill_alpha=0.2, fill_color="blue", line_color=None)
        for rend in [rend1, rend2, rend3]:
            rend.selection_glyph = sel
            rend.nonselection_glyph = nonsel
            rend.hover_glyph = sel

        # Pressure slider
        self.p_slider = Slider(
            title="Pressure (bar)",
            value=0.5,
            start=0,
            end=20,
            step=0.5,
            callback_policy='throttle',
            callback_throttle=200,
        )

        # Working capacity slider
        self.wc_slider = RangeSlider(
            title="Working capacity (bar)",
            value=(0.5, 5),
            start=0,
            end=20,
            step=0.5,
            callback_policy='throttle',
            callback_throttle=200,
        )

        # Material datatable
        self.mat_list = DataTable(
            columns=[
                TableColumn(field="labels", title="Material", width=300),
                TableColumn(field="sel",
                            title="KH2/KH1",
                            width=35,
                            formatter=NumberFormatter(format='‘0.0a’')),
                TableColumn(field="psa_W",
                            title="PSA-API",
                            width=35,
                            formatter=NumberFormatter(format='‘0.0a’')),
            ],
            source=self.model.data,
            index_position=None,
            selectable='checkbox',
            scroll_to_selection=True,
            width=400,
            fit_columns=True,
        )

        # Custom css classes for interactors
        self.p_henry.css_classes = ['g-henry']
        self.p_loading.css_classes = ['g-load']
        self.p_wc.css_classes = ['g-wcap']
        self.mat_list.css_classes = ['t-details']

        # Generate the axis labels
        self.top_graph_labels()

        self.kpi_plots = layout([
            [
                gridplot([[self.mat_list, self.p_henry],
                          [self.p_loading, self.p_wc]],
                         sizing_mode='scale_width')
            ],
            [self.p_slider, self.wc_slider],
        ],
                                sizing_mode='scale_width',
                                name="kpiplots")
        self.kpi_plots.children[0].css_classes = ['kpi']
        self.kpi_plots.children[1].css_classes = ['p-selectors']

        ################################
        # Isotherm details explorer
        ################################

        # Isotherm display graphs
        self.p_g1iso = self.bottom_graph(self.model.g1_iso_sel, self.model.g1)
        self.p_g2iso = self.bottom_graph(self.model.g2_iso_sel, self.model.g2)

        # Isotherm display palette
        self.c_cyc = cycle(gen_palette(20))

        self.detail_plots = layout([
            [self.p_g1iso, self.p_g2iso],
        ],
                                   sizing_mode='scale_width',
                                   name="detailplots")
        self.detail_plots.children[0].css_classes = ['isotherms']
Ejemplo n.º 19
0
    def __init__(self, data, visuals={}):

        p = figure(plot_width=visuals['figure_width'],
                   plot_height=visuals['figure_height'],
                   title=TITLE_LABEL,
                   toolbar_location=None)

        # Create the column data source and glyphs scatter data
        legend_items = []
        for i, point_set in enumerate(data):
            col_data = ColumnDataSource({
                'x': point_set['x'],
                'y': point_set['y'],
                's': [10] * len(point_set['x'])
            })
            glyph = Circle(x='x',
                           y='y',
                           size='s',
                           fill_color=point_set['color'],
                           line_color=None,
                           name=point_set['label'])
            renderer = p.add_glyph(col_data, glyph)
            renderer.name = glyph.name
            legend_items.append((renderer.name, [renderer]))

        if 'draw_legend' in visuals and visuals['draw_legend']:

            alpha = 1.0 if visuals['legend_border'] else 0.0
            border_color = "black" if visuals['legend_border'] else None

            legend = Legend(
                items=legend_items,
                location=visuals['legend_position'],
                name="the_legend",
                margin=0,
                background_fill_alpha=alpha,
                border_line_color=border_color,
                label_text_font_size=visuals['legend_label_font_size'],
                orientation=visuals['legend_orientation'])

            if visuals['legend_inside']:
                p.add_layout(legend)
            else:
                p.add_layout(legend, visuals['legend_layout_position'])

        # Set identifiers for the figure elements
        p.xaxis.name = X_AXIS_ID
        p.xaxis.axis_label = X_AXIS_LABEL
        p.yaxis.name = Y_AXIS_ID
        p.yaxis.axis_label = Y_AXIS_LABEL
        p.title.name = TITLE_ID

        if visuals['draw_gridlines']:
            if p.grid[0].dimension == 0:
                p.grid[0].name = X_GRID_ID
                p.grid[1].name = Y_GRID_ID
            else:
                p.grid[0].name = Y_GRID_ID
                p.grid[1].name = X_GRID_ID
        else:
            p.grid[0].visible = False
            p.grid[1].visible = False

        self.figure = p
Ejemplo n.º 20
0
    p = figure(plot_width=400, plot_height=400, title="title_title", toolbar_location=None)
    x = [1,2,3,4,5]
    sizes = [10]*len(x)
    circles = [1]*len(x)
    crosses = [2]*len(x)
    triangles = [3]*len(x)
    exes = [4]*len(x)
    asterisks = [5]*len(x)
    diamonds = [6]*len(x)
    squares = [7]*len(x)

    scatter_data = ColumnDataSource(dict(x=x, circles=circles, crosses=crosses, triangles=triangles, exes=exes, asterisks=asterisks, diamonds=diamonds, squares=squares, sizes=sizes))

    glyphs = []
    glyphs.append(Circle(x="x", y="circles", size="sizes", fill_color="red", name="the_circles"))
    glyphs.append(Cross(x="x", y="crosses", size="sizes", fill_color="blue", name="the_crosses"))
    glyphs.append(Triangle(x="x", y="triangles", size="sizes", fill_color="green", name="the_triangles"))
    glyphs.append(X(x="x", y="exes", size="sizes", fill_color="purple", name="the_xs"))
    glyphs.append(Asterisk(x="x", y="asterisks", size="sizes", fill_color="orange", name="the_asterisks"))
    glyphs.append(Diamond(x="x", y="diamonds", size="sizes", fill_color="yellow", name="the_diamonds"))
    glyphs.append(Square(x="x", y="squares", size="sizes", fill_color="gray", name="the_squares"))

    legend_items = []
    for glyph in glyphs:
        renderer = p.add_glyph(scatter_data, glyph)
        renderer.name = glyph.name
        legend_items.append((renderer.name, [renderer]))
    
    legend = Legend(
        items=legend_items,
Ejemplo n.º 21
0
(by number of songs) for our analysis. The analyzed data contains 21247 songs""",
                    width=1200,
                    height=150)
curdoc().add_root(pre_intro)

artist_xy_plot = figure(plot_width=450,
                        plot_height=450,
                        tools=[hover, 'tap', 'reset'],
                        toolbar_location='above')
artist_xy_circle = artist_xy_plot.circle('x',
                                         'y',
                                         size=15,
                                         source=artist_xy_source,
                                         fill_alpha=0.7)
# setting unselected selected render properties
artist_xy_circle.selection_glyph = Circle(fill_color='firebrick',
                                          fill_alpha=0.8)
artist_xy_circle.nonselection_glyph = Circle(fill_color='yellow',
                                             fill_alpha=0.2)
# setting artist_xy_plot properties
artist_xy_plot.xaxis.axis_label = "Average Words/Song"
artist_xy_plot.yaxis.axis_label = "Average Word Length"

artist_wordfreq_plot = figure(plot_width=1000,
                              plot_height=450,
                              x_range=artist_wordfreq_source.data['x'],
                              toolbar_location='above',
                              tools=['xpan, reset'])
artist_wordfreq_plot.vbar(x='x',
                          top='y',
                          width=0.25,
                          source=artist_wordfreq_source)
Ejemplo n.º 22
0
def launch(allSubreddits, allConnections, maxSubreddits, maxTimeSteps):
    # Matrices containing constants for each pickles
    numPickles = len(pickles)
    maxReddits = 20  # Guessing at maximum length

    # Store the position, number of subreddits, a
    X = np.zeros((numPickles, maxSubreddits))
    Y = np.zeros((numPickles, maxSubreddits))
    R = np.zeros((numPickles, maxSubreddits))
    N = np.zeros((numPickles, maxSubreddits))
    names = np.array([], [])
    for i in range(len(numPickles)):
        names = names.append('')

    infected = np.zeros((numPickles, maxSubreddits, maxTimeSteps))
    colors = np.zeros((numPickles, maxSubreddits, maxTimeSteps))

    ## Unload parameters #######################################################
    for l in range(len(allSubreddits)):
        subreddits = allsubReddits[l]
        connections = allConnections[l]
        total = len(connections)  # Number of SubReddits Investigated
        timeSteps = len(subreddits.values(
            0))  # Length of the arrays (number of time steps)
        x = np.zeros(N)  # x Position
        y = np.zeros(N)  # y position
        r = np.zeros(N)  # radius of node
        thisColors = np.zeros([])  # Color for each node at each time
        names = np.array([])  # SubReddit name
        thisInfected = np.array([])

        for name in subreddits:  # Loop through dictionary and store keys and values in arrays
            names = np.append(names, name)
            infected = np.append(infected, subreddits[name])

            for i in range(N):  # For each sub reddit
                x[i] = np.random.randint(N)  # point's x value
                y[i] = np.random.randint(N)  # point's y value
                r[i] = np.random.randint(40, 60)  # radius
                subs[i] = np.random.randint(40, 60)  # radius
                for j in range(10):
                    thisInfected[i][j] = 1
                    thisColors[i][j] = RGB(255 * infected[i], 20,
                                           180 * (1 - infected[i]))
        #Add the current subreddit data to the Matrices
        X[l] = x
        Y[l] = y
        R[l] = r
        N[l] = total
        infected[l] = thisInfected
        colors[l] = thisColors

    ## Plotting code ########################################################

    xdr = DataRange1d()
    ydr = DataRange1d()

    source = ColumnDataSource(
        dict(x=X[0], y=Y[0], r=R[0], infect=infected[0], subs=sub[0]))

    plot = figure(title=None,
                  x_range=xdr,
                  y_range=ydr,
                  plot_width=1100,
                  plot_height=700,
                  h_symmetry=False,
                  v_symmetry=False,
                  min_border=0,
                  toolbar_location=None)
    plot.axis.visible = None
    plot.xgrid.visible = False
    plot.ygrid.visible = False

    plot.add_tools(
        HoverTool(tooltips=[('Sub-Reddit Name',
                             '@name'), ('URL',
                                        '@URL'), ('Subscriber Count',
                                                  '@subs')]))

    # Add lines connecting each glyph
    for i in range(N):
        for j in range(N):
            if j <= i:
                rgbval = 255 - 255 * connections[i][
                    j]  # Shade from white to black based on connection strength
                lineColor = RGB(rgbval, rgbval, rgbval)
                width = connections[i][j]
                plot.line([x[i], x[j]], [y[i], y[j]],
                          line_width=np.random.randint(7),
                          line_color=lineColor)

    curTimeIdx = 0

    # Add all the glyphs to the main plot
    glyph = Circle(x="x", y="y", size="r", fill_color="colors", line_width=1)
    plot.add_glyph(source, glyph)
    ## Bokeh Widget and JS Code ##############################################

    text = PreText(text="""
    This will be HTML-compatible text
    """,
                   width=200,
                   height=400)

    layout = row(widgetbox(text), plot)

    show(layout)