コード例 #1
0
ファイル: main.py プロジェクト: CyanideTD/aws-taxi
    def trip_fare_init(self, width=310, height=350, webgl=True):
        def ticker():
            labels = {
                0: '0~5',
                1: '5~10',
                2: '10~25',
                3: '25~50',
                4: '50~100',
                5: '>100'
            }
            return labels[tick]

        self.trip_fare = figure(webgl=webgl,
                                toolbar_location=None,
                                width=width,
                                height=height,
                                title='Fare (US dolloars)')
        self.trip_fare_source = ColumnDataSource(
            data=dict(x=range(6), fare=self.data.get_fare()))
        vbar = self.trip_fare.vbar(width=1,
                                   bottom=0,
                                   x='x',
                                   top='fare',
                                   source=self.trip_fare_source,
                                   fill_alpha=0.7,
                                   line_color="white",
                                   color='#ffcc5c')
        self.trip_fare.y_range.start = 0
        self.trip_fare.xaxis.major_tick_line_color = None
        self.trip_fare.xaxis.minor_tick_line_color = None
        self.trip_fare.xaxis.formatter = FuncTickFormatter.from_py_func(ticker)

        self.trip_fare.select(dict(type=GlyphRenderer))
        self.trip_fare.add_tools(
            HoverTool(renderers=[vbar], tooltips=[("Trips", "@fare")]))
コード例 #2
0
ファイル: plots.py プロジェクト: ADEQUATeDQ/portalmonitor
def systemEvolutionBarPlot(df, yLabel, values):
    with Timer(key='systemEvolutionBarPlot', verbose=True):
        p = Bar(df, label='snapshot', values=values, agg='sum', stack='software',
            legend='bottom_left', bar_width=0.5, xlabel="Snapshots", ylabel=yLabel, responsive=True, height=200,tools='hover')

        glyph_renderers = p.select(GlyphRenderer)
        bar_source = [glyph_renderers[i].data_source for i in range(len(glyph_renderers))]
        hover = p.select(HoverTool)
        hover.tooltips = [
            ('software',' @software'),
            ('value', '@height'),
        ]
        p.xaxis.formatter=FuncTickFormatter.from_py_func(getWeekStringTick)
        p.axis.minor_tick_line_color = None

        p.background_fill_color = "#fafafa"
        p.legend.location = "top_left"
        p.toolbar.logo = None
        p.toolbar_location = None

        legend=p.legend[0].legends
        p.legend[0].legends=[]
        l = Legend( location=(0, -30))
        l.items=legend
        p.add_layout(l, 'right')

        return p
コード例 #3
0
ファイル: element.py プロジェクト: vascotenner/holoviews
    def _axis_properties(self,
                         axis,
                         key,
                         plot,
                         dimension,
                         ax_mapping={
                             'x': 0,
                             'y': 1
                         }):
        """
        Returns a dictionary of axis properties depending
        on the specified axis.
        """
        axis_props = {}
        if ((axis == 'x' and self.xaxis in ['bottom-bare', 'top-bare']) or
            (axis == 'y' and self.yaxis in ['left-bare', 'right-bare'])):
            axis_props['axis_label'] = ''
            axis_props['major_label_text_font_size'] = '0pt'
            axis_props['major_tick_line_color'] = None
            axis_props['minor_tick_line_color'] = None
        else:
            rotation = self.xrotation if axis == 'x' else self.yrotation
            if rotation:
                axis_props['major_label_orientation'] = np.radians(rotation)
            ticker = self.xticks if axis == 'x' else self.yticks
            if isinstance(ticker, Ticker):
                axis_props['ticker'] = ticker
            elif isinstance(ticker, int):
                axis_props['ticker'] = BasicTicker(desired_num_ticks=ticker)
            elif isinstance(ticker, (tuple, list)):
                if all(isinstance(t, tuple) for t in ticker):
                    pass
                else:
                    axis_props['ticker'] = FixedTicker(ticks=ticker)

        if FuncTickFormatter is not None and ax_mapping and dimension:
            formatter = None
            if dimension.value_format:
                formatter = dimension.value_format
            elif dimension.type in dimension.type_formatters:
                formatter = dimension.type_formatters[dimension.type]
            if formatter:
                msg = ('%s dimension formatter could not be '
                       'converted to tick formatter. ' % dimension.name)
                try:
                    formatter = FuncTickFormatter.from_py_func(formatter)
                except RuntimeError:
                    self.warning(msg + 'Ensure Flexx is installed '
                                 '("conda install -c bokeh flexx" or '
                                 '"pip install flexx")')
                except Exception as e:
                    error = 'Pyscript raised an error: {0}'.format(e)
                    error = error.replace('%', '%%')
                    self.warning(msg + error)
                else:
                    axis_props['formatter'] = formatter
        return axis_props
コード例 #4
0
def test_functickformatter_from_py_func_no_args():
    def convert_to_minutes():
        return tick * 60  # noqa

    formatter = FuncTickFormatter.from_py_func(convert_to_minutes)
    js_code = flexx.pyscript.py2js(convert_to_minutes, 'formatter')

    function_wrapper = formatter.code.replace(js_code, '')

    assert function_wrapper == "return formatter();\n"
コード例 #5
0
def test_functickformatter_from_py_func():
    def convert_to_minutes(seconds):
        return seconds * 60

    formatter = FuncTickFormatter.from_py_func(convert_to_minutes)
    js_code = pyscript.py2js(convert_to_minutes, 'formatter')

    function_wrapper = formatter.code.replace(js_code, '')

    assert function_wrapper == "function (seconds) {return formatter(seconds)};"
コード例 #6
0
ファイル: test_formatters.py プロジェクト: soerendip/bokeh
def test_functickformatter_from_py_func_no_args():

    def convert_to_minutes():
        return tick * 60 # noqa

    formatter = FuncTickFormatter.from_py_func(convert_to_minutes)
    js_code = flexx.pyscript.py2js(convert_to_minutes, 'formatter')

    function_wrapper = formatter.code.replace(js_code, '')

    assert function_wrapper == "formatter();\n"
コード例 #7
0
ファイル: plots.py プロジェクト: ADEQUATeDQ/portalmonitor
def evolutionCharts(df):


    df['week']= df['snapshot'].apply(getWeekString)
    df = df[df['end'].notnull()]
    df=df.sort(['snapshot'], ascending=[1])
    df['snapshotId']= range(1, len(df) + 1)

    source = ColumnDataSource(df)




    plots={'size':evolSize(source,df)}

    last=None
    for q in qa:
        pt = figure(   plot_width=600, plot_height=200
                , min_border=10, min_border_left=50
                , toolbar_location="above",responsive=True)
        pt.background_fill_color = "#fafafa"
        pt.legend.location = "top_left"
        pt.toolbar.logo = None
        pt.toolbar_location = None
        hit_renderers = []
        legends=[]
        for m,v in q['metrics'].items():
            l=pt.line(x='snapshotId',y=m.lower(), line_width=2,source=source, color=v['color'])
            c=pt.circle(x='snapshotId',y=m.lower(), line_width=2,source=source, color=v['color'])
            # invisible circle used for hovering
            hit_target =Circle(x='snapshotId',y=m.lower(), size=10,line_color=None, fill_color=None)
            hit_renderer = pt.add_glyph(source, hit_target)

            legends.append((v['label']+" ["+m.lower()+"]",[l,c]))

            pt.add_tools(HoverTool(renderers=[hit_renderer], tooltips={'Metric':v['label'], "Week": "@week", 'Value':"@"+m.lower()}))
            pt.xaxis[0].ticker.desired_num_ticks = df.shape[0]/2


        pt.xaxis.formatter=FuncTickFormatter.from_py_func(getWeekStringTick)
        pt.axis.minor_tick_line_color = None

        legend = Legend(location=(0, -30))
        legend.items=legends
        pt.add_layout(legend, 'right')

        pt.xaxis[0].axis_label = 'Snapshot'
        pt.yaxis[0].axis_label = 'Average quality'

        plots[q['dimension']]=pt
        last=pt

    return plots
コード例 #8
0
ファイル: test_formatters.py プロジェクト: Apple3124/bokeh
def test_functickformatter_from_py_func():

    def convert_to_minutes(seconds):
        return seconds * 60

    formatter = FuncTickFormatter.from_py_func(convert_to_minutes)
    js_code = pyscript.py2js(convert_to_minutes, 'formatter')

    function_wrapper = formatter.code.replace(js_code, '')

    assert function_wrapper == "function (seconds) {return formatter(seconds)};"
    assert formatter.lang == "javascript"
コード例 #9
0
ファイル: test_formatters.py プロジェクト: soerendip/bokeh
def test_functickformatter_from_py_func_with_args():

    slider = Slider()

    def convert_to_minutes(x=slider):
        return tick * 60 # noqa

    formatter = FuncTickFormatter.from_py_func(convert_to_minutes)
    js_code = flexx.pyscript.py2js(convert_to_minutes, 'formatter')

    function_wrapper = formatter.code.replace(js_code, '')

    assert function_wrapper == "formatter(x);\n"
    assert formatter.args['x'] is slider
コード例 #10
0
ファイル: element.py プロジェクト: graphbio/holoviews
    def _axis_properties(self, axis, key, plot, dimension,
                         ax_mapping={'x': 0, 'y': 1}):
        """
        Returns a dictionary of axis properties depending
        on the specified axis.
        """
        axis_props = {}
        if ((axis == 'x' and self.xaxis in ['bottom-bare', 'top-bare']) or
            (axis == 'y' and self.yaxis in ['left-bare', 'right-bare'])):
            axis_props['axis_label'] = ''
            axis_props['major_label_text_font_size'] = '0pt'
            axis_props['major_tick_line_color'] = None
            axis_props['minor_tick_line_color'] = None
        else:
            rotation = self.xrotation if axis == 'x' else self.yrotation
            if rotation:
                axis_props['major_label_orientation'] = np.radians(rotation)
            ticker = self.xticks if axis == 'x' else self.yticks
            if isinstance(ticker, Ticker):
                axis_props['ticker'] = ticker
            elif isinstance(ticker, int):
                axis_props['ticker'] = BasicTicker(desired_num_ticks=ticker)
            elif isinstance(ticker, (tuple, list)):
                if all(isinstance(t, tuple) for t in ticker):
                    pass
                else:
                    axis_props['ticker'] = FixedTicker(ticks=ticker)

        if FuncTickFormatter is not None and ax_mapping and dimension:
            formatter = None
            if dimension.value_format:
                formatter = dimension.value_format
            elif dimension.type in dimension.type_formatters:
                formatter = dimension.type_formatters[dimension.type]
            if formatter:
                msg = ('%s dimension formatter could not be '
                       'converted to tick formatter. ' % dimension.name)
                try:
                    formatter = FuncTickFormatter.from_py_func(formatter)
                except RuntimeError:
                    self.warning(msg+'Ensure Flexx is installed '
                                 '("conda install -c bokeh flexx" or '
                                 '"pip install flexx")')
                except Exception as e:
                    error = 'Pyscript raised an error: {0}'.format(e)
                    error = error.replace('%', '%%')
                    self.warning(msg+error)
                else:
                    axis_props['formatter'] = formatter
        return axis_props
コード例 #11
0
def test_functickformatter_from_py_func_with_args():

    slider = Slider()

    def convert_to_minutes(x=slider):
        return tick * 60  # noqa

    formatter = FuncTickFormatter.from_py_func(convert_to_minutes)
    js_code = flexx.pyscript.py2js(convert_to_minutes, 'formatter')

    function_wrapper = formatter.code.replace(js_code, '')

    assert function_wrapper == "return formatter(x);\n"
    assert formatter.args['x'] is slider
コード例 #12
0
def evolutionCharts(df):

    df['week'] = df['snapshot'].apply(getWeekString)
    df = df[df['end'].notnull()]
    df=df.sort_values(['snapshot'], ascending=[1])
    df['snapshotId']= range(1, len(df) + 1)
    print(df)
    source = ColumnDataSource(df)

    plots={'size':evolSize(source,df)}

    for q in qa:
        pt = figure(plot_width=600, plot_height=200
                , min_border=10, min_border_left=50
                , toolbar_location="above")
        pt.background_fill_color = "#fafafa"
        pt.legend.location = "top_left"
        pt.toolbar.logo = None
        pt.toolbar_location = None
        legends=[]
        marker = [pt.circle, pt.x, pt.cross, pt.square, pt.diamond, pt.triangle, pt.inverted_triangle, pt.asterisk, pt.square_cross]
        colors = brewer['BrBG'][max(3, min(len(q['metrics']), 11))]
        i = 0
        for m,v in q['metrics'].items():
            if m.lower() in df:
                l=pt.line(x='snapshotId',y=m.lower(), line_width=2,source=source, color=colors[i%len(colors)])
                c=marker[i%len(marker)](x='snapshotId',y=m.lower(), line_width=4,source=source, color=colors[i%len(colors)])
                # invisible circle used for hovering
                hit_target =Circle(x='snapshotId',y=m.lower(), size=10,line_color=None, fill_color=None)
                hit_renderer = pt.add_glyph(source, hit_target)

                legends.append((v['label']+" ["+m.lower()+"]",[l,c]))

                pt.add_tools(HoverTool(renderers=[hit_renderer], tooltips={'Metric':v['label'], "Week": "@week", 'Value':"@"+m.lower()}))
                pt.xaxis[0].ticker.desired_num_ticks = df.shape[0]
                i += 1

        pt.xaxis.formatter=FuncTickFormatter.from_py_func(getWeekStringTick)
        pt.axis.minor_tick_line_color = None

        legend = Legend(location=(0, -30))
        legend.items=legends
        pt.add_layout(legend, 'right')

        pt.xaxis[0].axis_label = 'Snapshot'
        pt.yaxis[0].axis_label = 'Average quality'

        plots[q['dimension']]=pt

    return plots
コード例 #13
0
ファイル: plots.py プロジェクト: ADEQUATeDQ/portalmonitor
def fetchProcessChart(data,cnts):

    bp = figure(plot_width=600, plot_height=300,y_axis_type="datetime",responsive=True,tools='')#,toolbar_location=None
    bp.toolbar.logo = None
    bp.toolbar_location = None

    bp.xaxis[0].formatter = NumeralTickFormatter(format="0.0%")
    bp.yaxis[0].formatter=FuncTickFormatter.from_py_func(hm)
    bp.xaxis[0].axis_label = '% of portals'
    bp.yaxis[0].axis_label = 'Time elapsed'

    mx=None
    c=0

    for sn in sorted(data.keys()):
        d=data[sn]

        d_sorted = np.sort(np.array(d))
        y=[e for e in d_sorted] #datetime.datetime.fromtimestamp(e)
        x = 1. * arange(len(d)) / (len(d) - 1)
        mx=max(x) if max(x)>mx else mx

        if sn == max(data.keys()):
            ci=bp.circle(x,y, size=5, alpha=0.5,  color='red', legend="current week: "+getWeekString(sn))
            li=bp.line(x,y, line_width=2,line_color='red', legend="current week: "+getWeekString(sn))
        else:
            ci=bp.circle(x,y, size=5, alpha=0.5,  color='gray')
            li=bp.line(x,y, line_width=2,line_color='gray')
            #hit_target =Circle(x,y, size=10,line_color=None, fill_color=None)


            #c.select(dict(type=HoverTool)).tooltips = {"Week": "@week",m:"@"+m.lower()}
            #hit_renderers.append(hit_renderer)

            bp.add_tools(HoverTool(renderers=[li], tooltips={"Week": getWeekString(sn)}))

        c+=1
        #bp.text(,y[-1], line_width=2,line_color=OrRd9[c],legend=str(sn))
        no_olympics_glyph = Text(x=x[-1], y=y[-1], x_offset=100, text=["%s of %s portals"%(len(d), cnts[sn])],
            text_align="right", text_baseline="top",
            text_font_size="9pt", text_font_style="italic", text_color="black")
        bp.add_glyph(no_olympics_glyph)

    bp.x_range=Range1d(0, mx*1.2)
    bp.background_fill_color = "#fafafa"

    bp.legend.location = "top_left"

    return bp
コード例 #14
0
ファイル: plots.py プロジェクト: ADEQUATeDQ/portalmonitor
def evolSize(source,df):
    p = figure(   plot_width=600, plot_height=200
                , min_border=10, min_border_left=50
                , toolbar_location="above",responsive=True)
    p.background_fill_color = "#fafafa"
    p.legend.location = "top_left"
    p.toolbar.logo = None
    p.toolbar_location = None

    legends=[]

    l=p.line(x='snapshotId',y='datasetcount', line_width=2,source=source)
    c=p.circle(x='snapshotId',y='datasetcount', line_width=2,source=source)

    hit_target =Circle(x='snapshotId',y='datasetcount', size=10,line_color=None, fill_color=None)
    hit_renderer = p.add_glyph(source, hit_target)

    legends.append(("Datasets",[l,c]))
    p.add_tools(HoverTool(renderers=[hit_renderer], tooltips={'Metric':"Size", "Week": "@week", 'Value':"@datasetcount"}))

    #######
    l=p.line(x='snapshotId',y='resourcecount', line_width=2,source=source)
    c=p.circle(x='snapshotId',y='resourcecount', line_width=2,source=source)

    hit_target =Circle(x='snapshotId',y='resourcecount', size=10,line_color=None, fill_color=None)
    hit_renderer = p.add_glyph(source, hit_target)

    legends.append(("Resources",[l,c]))
    p.add_tools(HoverTool(renderers=[hit_renderer], tooltips={'Metric':"Size", "Week": "@week", 'Value':"@resourcecount"}))


    p.xaxis[0].ticker.desired_num_ticks = df.shape[0]/2

    p.xaxis.formatter=FuncTickFormatter.from_py_func(getWeekStringTick)
    p.axis.minor_tick_line_color = None

    legend = Legend( location=(0, -30))
    legend.items = legends
    p.add_layout(legend, 'right')

    p.xaxis[0].axis_label = 'Snapshot'
    p.yaxis[0].axis_label = 'Count'

    return p
コード例 #15
0
ファイル: test_formatters.py プロジェクト: yiyuan1840/bokeh
def test_functickformatter_bad_pyfunc_formats():
    def has_positional_arg(x):
        return None
    with pytest.raises(ValueError):
        FuncTickFormatter.from_py_func(has_positional_arg)

    def has_positional_arg_with_kwargs(y, x=5):
        return None
    with pytest.raises(ValueError):
        FuncTickFormatter.from_py_func(has_positional_arg_with_kwargs)

    def has_non_Model_keyword_argument(x=10):
        return None
    with pytest.raises(ValueError):
        FuncTickFormatter.from_py_func(has_non_Model_keyword_argument)
コード例 #16
0
ファイル: test_formatters.py プロジェクト: soerendip/bokeh
def test_functickformatter_bad_pyfunc_formats():
    def has_positional_arg(x):
        return None
    with pytest.raises(ValueError):
        FuncTickFormatter.from_py_func(has_positional_arg)

    def has_positional_arg_with_kwargs(y, x=5):
        return None
    with pytest.raises(ValueError):
        FuncTickFormatter.from_py_func(has_positional_arg_with_kwargs)

    def has_non_Model_keyword_argument(x=10):
        return None
    with pytest.raises(ValueError):
        FuncTickFormatter.from_py_func(has_non_Model_keyword_argument)
コード例 #17
0
ファイル: BarChart.py プロジェクト: Irfan6220c/Test
    def __init__(self, xVals, yVals, colours=None, width=None):
        Max = 0
        Min = 0
        N = len(xVals)
        # create list of colours
        if (colours == None):
            colours = list(xVals)
            for i in range(0, N):
                colours[i] = "red"
        else:
            if (not isinstance(colours, list)):
                colours = [colours]
                for i in range(1, N):
                    colours.append(colours[0])
        # create list of widths
        if (width == None):
            width = []
            for i in range(0, N):
                width.append(1)
        # initialise values for loop
        self.fig = figure(tools="")
        self.barSources = []
        x = 0
        places = []
        label_places = []
        index = {}
        for i in range(0, N):
            # add ColumnDataSource describing each bar
            self.barSources.append(
                ColumnDataSource(
                    data=dict(x=[x, x, x + width[i], x + width[i]],
                              y=[0, yVals[i], yVals[i], 0])))
            # update Max and Min for y_range
            if (yVals[i] + 1 > Max):
                Max = yVals[i] + 1
            elif (yVals[i] < 0 and yVals[i] - 1 < Min):
                Min = yVals[i] - 1
            # create bar
            self.fig.patch(x='x',
                           y='y',
                           fill_color=colours[i],
                           source=self.barSources[i],
                           line_color=None)
            br = xVals[i].find('\n')
            places.append(x + width[i] / 2.0)
            if (br == -1):
                # remember bar position
                label_places.append(x + width[i] / 2.0)
                # remember label that should be written at that postion
                index[str(int(100 * (x + width[i] / 2.0)))] = [xVals[i]]
            else:
                label = []
                while (br != -1):
                    label.append(xVals[i][0:br])
                    xVals[i] = xVals[i][br + 1:]
                    br = xVals[i].find('\n')
                label.append(xVals[i])
                N = len(label)
                for j in range(0, N):
                    index[str(int(100 * (x + width[i] * (j + 1) /
                                         (N + 1.0))))] = [label[j]]
                    label_places.append((floor(100 * (x + width[i] * (j + 1) /
                                                      (N + 1.0))) / 100.0))
            # increase x
            x += width[i] + 1

        # set figure properties
        self.fig.x_range = Range1d(-1, x)
        self.fig.y_range = Range1d(Min, Max)
        self.fig.grid.visible = False
        self.fig.xaxis.major_label_text_font_size = "15pt"
        self.fig.xaxis.major_tick_line_color = None
        self.fig.xaxis.major_label_orientation = 0
        self.fig.yaxis.axis_label = "speed (m/second)"
        self.fig.yaxis.axis_label_text_font_size = "14pt"
        self.fig.min_border_bottom = 5
        self.fig.title.text = 'Boat'
        self.fig.title_location = 'below'
        self.fig.title.text_font_size = "15pt"
        self.fig.title.align = "center"
        # only give x ticks at bars
        self.fig.xaxis[0].ticker = FixedTicker(ticks=label_places)
        # save vals in ColumnDataSource so ticker_func can use it as default val
        index_obj = ColumnDataSource(data=index)

        # define function which assigns values to tick labels
        def ticker_func(labels=index_obj):
            return labels.data[str(tick * 100)]

        # call ticker_func
        self.fig.xaxis[0].formatter = FuncTickFormatter.from_py_func(
            ticker_func)
コード例 #18
0
ファイル: plots.py プロジェクト: suryabahubalendruni/cruz
def make_violin_plot(x,
                     y,
                     hue,
                     data,
                     plot_type="factor",
                     palette="GnBu",
                     width=750,
                     height=500):
    data = data[[x, y, hue]]
    sns_palette = sns.color_palette(palette, 2)
    sns.set_style("whitegrid")
    if plot_type == "factor":
        violin_plot_sns = sns.factorplot(x=x,
                                         y=y,
                                         hue=hue,
                                         data=data,
                                         kind="violin",
                                         palette=sns_palette)
    else:
        violin_plot_sns = sns.violinplot(x=x,
                                         y=y,
                                         hue=hue,
                                         data=data,
                                         palette=sns_palette,
                                         split=True,
                                         scale="area",
                                         inner="box",
                                         orient="v",
                                         bw=.15,
                                         responsive=True)
    violin_plot = mpl.to_bokeh()
    violin_plot.toolbar_location = "above"
    violin_plot.toolbar_sticky = False
    violin_plot.grid.grid_line_color = "SlateGray"
    violin_plot.grid.grid_line_alpha = .5
    violin_plot.grid.minor_grid_line_color = "SlateGray"
    violin_plot.grid.minor_grid_line_alpha = .2
    violin_plot.plot_height = height
    violin_plot.plot_width = width
    if "amount" in y:
        violin_plot.title.text = "Fare Violin Plot"
        violin_plot.yaxis[0].formatter = NumeralTickFormatter(format="$ 0.00")
    if "distance" in y:
        violin_plot.title.text = "Distance Violin Plot"
        violin_plot.yaxis[0].formatter = PrintfTickFormatter(
            format="%5.2f miles")

    def day_ticker():
        days = [
            "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
            "Sunday"
        ]
        if abs(int(round(tick)) - tick) < .05:
            return days[int(round(tick))]
        else:
            return ""

    def month_ticker():
        months = [
            "January", "February", "March", "April", "May", "June", "July"
        ]
        if abs(int(round(tick)) - tick) < .05:
            return months[int(round(tick))]
        else:
            return ""

    if "day" in x:
        violin_plot.xaxis[0].formatter = FuncTickFormatter.from_py_func(
            day_ticker)
    if "month" in x:
        violin_plot.xaxis[0].formatter = FuncTickFormatter.from_py_func(
            month_ticker)
    return violin_plot
コード例 #19
0
ファイル: plots.py プロジェクト: suryabahubalendruni/cruz
def make_stacked_bar_chart(buckets,
                           stack,
                           data,
                           palette,
                           width=500,
                           height=500):
    cp = data
    if buckets == "day":
        cp[buckets] = cp.apply(lambda row: row['pickup_datetime'].weekday(),
                               axis=1)
    elif buckets == "month":
        cp[buckets] = cp.apply(lambda row: row['pickup_datetime'].month,
                               axis=1)
    TOOLS = "pan,reset,hover,save"
    stacked_bar = Bar(cp,
                      label=buckets,
                      values=buckets,
                      agg='count',
                      stack=cat(stack, sort=True),
                      tools=TOOLS,
                      title="{0} Stacked Bar for {1}".format(
                          ("Daily" if buckets == "day" else "Monthly"),
                          stack.replace("_", " ").title()),
                      palette=palette,
                      plot_width=width,
                      plot_height=height,
                      toolbar_location="above",
                      toolbar_sticky=False,
                      legend_sort_field='color',
                      legend_sort_direction='ascending',
                      responsive=True)
    hover = stacked_bar.select_one(HoverTool)
    hover.point_policy = "follow_mouse"
    hover.tooltips = [("Frequency", "@height"),
                      ("{0}".format(stack.replace("_", " ").title()),
                       "@{0}".format(stack))]

    def day_ticker():
        days = [
            "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
            "Sunday"
        ]
        if abs(int(round(tick)) - tick) < .05:
            return days[int(round(tick))]
        else:
            return ""

    def month_ticker():
        months = [
            "January", "February", "March", "April", "May", "June", "July"
        ]
        if abs(int(round(tick)) - tick) < .05:
            return months[int(round(tick))]
        else:
            return ""

    if buckets == "day":
        stacked_bar.xaxis.formatter = FuncTickFormatter.from_py_func(
            day_ticker)
    else:
        stacked_bar.xaxis.formatter = FuncTickFormatter.from_py_func(
            month_ticker)
    stacked_bar.grid.grid_line_color = "SlateGray"
    stacked_bar.grid.grid_line_alpha = .5
    stacked_bar.grid.minor_grid_line_color = "SlateGray"
    stacked_bar.grid.minor_grid_line_alpha = .2

    return stacked_bar
コード例 #20
0
    df['Gun_Seconds'] = map(lambda i: time_to_seconds(i),df['Gun Tim'])
    df['Pace'] = map(lambda i: time_to_seconds(i),df['Pace'])

    #df['Net Tim']= map(lambda i: if (str(i).split(':')),df['Div/Tot'])
together = pd.concat(dfs)
together['Rank'] = together['Net_Seconds'].rank()
gun_color_women ="#ff3399"
gun_color_men ='#0000ff'
net_color_women ="#9900cc"
net_color_men = "#006666"


####PLOT ONE#### DATA DISTRIBUTIONS - GUN TIME

plot_one = figure(plot_width=900,plot_height=500)
plot_one.xaxis.formatter = FuncTickFormatter.from_py_func(seconds_formatted)
#hover_one =HoverTool(
#        tooltips=[
#            ("index", "$index"),
#            ("(x,y)", "($x, $y)"),
#            ("desc", "@desc"),
#        ]
#    )


plot_one.add_tools(HoverTool())
#WOMEN
density = stats.kde.gaussian_kde(females['Gun_Seconds'].dropna())
x = np.arange(0.,max(females['Gun_Seconds'].dropna()), 1)
y = [density(y) for y in x]
コード例 #21
0
ファイル: plots.py プロジェクト: ADEQUATeDQ/portalmonitor
def portalDynamicity(df):

    def getWeekString(yearweek):
        if yearweek is None or len(str(yearweek)) == 0:
            return ''
        year = "'" + str(yearweek)[:2]
        week = int(str(yearweek)[2:])
        # d = d - timedelta(d.weekday())
        # dd=(week)*7
        # dlt = timedelta(days = dd)
        # first= d + dlt

        # dlt = timedelta(days = (week)*7)
        # last= d + dlt + timedelta(days=6)

        return 'W' + str(week) + '-' + str(year)
    bp = figure(plot_width=600, plot_height=300, y_axis_type="datetime", responsive=True,
                tools='')  # ,toolbar_location=None
    bp.toolbar.logo = None
    bp.toolbar_location = None
    label_dict={}
    for i, s in enumerate(df['snapshot']):
        label_dict[i] = getWeekString1(s)

    bp.yaxis[0].formatter = NumeralTickFormatter(format="0.0%")
    bp.xaxis[0].axis_label = 'Snapshots'
    bp.yaxis[0].axis_label = '% of portals'

    li = bp.line(df.index.values.tolist(), df['dyratio'], line_width=2, line_color='red', legend="dyratio")
    c = bp.circle(df.index.values.tolist(), df['dyratio'], line_width=2, line_color='red', legend="dyratio")
    li1 = bp.line(df.index.values.tolist(), df['adddelratio'], line_width=2, line_color='blue', legend="adddelratio")
    c = bp.circle(df.index.values.tolist(), df['adddelratio'], line_width=2, line_color='blue', legend="adddelratio")
    legend = bp.legend[0].legends
    bp.legend[0].legends = []
    l = Legend(location=(0, -30))
    l.items = legend
    bp.add_layout(l, 'right')



    labels=["staticRatio","updatedRatio","addRatio","delRatio"]
    #for l in labels:
    #    df[l]= df[l]*100
    print brewer.keys()
    colors = brewer["Pastel2"][len(labels)]
    bar = Bar(df,
              values=blend("staticRatio","updatedRatio","addRatio","delRatio", name='medals', labels_name='medal'),
              label=cat(columns='snapshot', sort=False),
              stack=cat(columns='medal', sort=False),
              color=color(columns='medal', palette=colors,
                          sort=False),
              legend='top_right',
              bar_width=0.5, responsive=True,
              tooltips=[('ratio', '@medal'), ('snapshot', '@snapshot'),('Value of Total',' @height{0.00%}')])
    legend = bar.legend[0].legends
    bar.legend[0].legends = []
    l = Legend(location=(0, -30))
    l.items = legend
    bar.add_layout(l, 'right')
    bar.xaxis[0].axis_label = 'Snapshots'
    bar.yaxis[0].axis_label = '% of datasets'
    bar.width=600
    bar.height=300
    bar.xaxis[0].formatter = FuncTickFormatter.from_py_func(getWeekStringTick)
    bar.toolbar.logo = None
    bar.toolbar_location = None

    bar.yaxis[0].formatter = NumeralTickFormatter(format="0.0%")
    return {'bar':bar,'lines':bp}
コード例 #22
0
ファイル: main.py プロジェクト: lperozzi/channel
def create_figure(result, var, test, position, number):
    color_mapper1 = LinearColorMapper(palette="Viridis256",
                                      low=np.amin(result),
                                      high=np.amax(result))
    color_mapper2 = LinearColorMapper(palette="Greys256",
                                      low=np.amin(var),
                                      high=np.amax(var))
    color_mapper3 = LinearColorMapper(palette="Greys256",
                                      low=np.amin(test),
                                      high=np.amax(test))
    p = figure(title="Channel Probability",
               x_range=(0, 5),
               y_range=(0, 5),
               toolbar_location=None)
    q = figure(title="Seismic Amplitude",
               x_range=(0, 5),
               y_range=(0, 5),
               toolbar_location=None)
    r = figure(title="Model Uncertainty",
               x_range=(0, 5),
               y_range=(0, 5),
               toolbar_location=None)
    #s = figure(title="Model Uncertainty Max Vote", x_range=(0,10), y_range=(0,10), toolbar_location=None)
    i = number
    color_bar1 = ColorBar(color_mapper=color_mapper1,
                          ticker=BasicTicker(),
                          label_standoff=12,
                          border_line_color=None,
                          location=(0, 0),
                          formatter=FuncTickFormatter.from_py_func(ticker))
    p.add_layout(color_bar1, 'right')
    color_bar2 = ColorBar(color_mapper=color_mapper2,
                          ticker=BasicTicker(),
                          label_standoff=12,
                          border_line_color=None,
                          location=(0, 0),
                          formatter=FuncTickFormatter.from_py_func(ticker))
    color_bar3 = ColorBar(color_mapper=color_mapper3,
                          ticker=BasicTicker(),
                          label_standoff=20,
                          border_line_color=None,
                          location=(0, 0),
                          formatter=FuncTickFormatter.from_py_func(ticker1))
    q.add_layout(color_bar3, 'right')
    r.add_layout(color_bar2, 'right')
    #s.add_layout(color_bar2, 'right')

    if position == 1:
        # must give a vector of image data for image parameter
        p.image(image=[np.transpose(result[i, :, :])],
                x=0,
                y=0,
                dw=5,
                dh=5,
                color_mapper=color_mapper1)
        # must give a vector of image data for image parameter
        q.image(image=[np.transpose(test[i, :, :])],
                x=0,
                y=0,
                dw=5,
                dh=5,
                color_mapper=color_mapper3)
        r.image(image=[np.transpose(var[i, :, :])],
                x=0,
                y=0,
                dw=5,
                dh=5,
                color_mapper=color_mapper2)
        #s.image(image=[np.transpose(var2[i,:,:])], x=0, y=0, dw=10, dh=10, color_mapper=color_mapper2)
    elif position == 2:
        # must give a vector of image data for image parameter
        p.image(image=[np.transpose(result[:, i, :])],
                x=0,
                y=0,
                dw=5,
                dh=5,
                color_mapper=color_mapper1)
        # must give a vector of image data for image parameter
        q.image(image=[np.transpose(test[:, i, :])],
                x=0,
                y=0,
                dw=5,
                dh=5,
                color_mapper=color_mapper3)
        r.image(image=[np.transpose(var[:, i, :])],
                x=0,
                y=0,
                dw=5,
                dh=5,
                color_mapper=color_mapper2)
        #s.image(image=[np.transpose(var2[:,i,:])], x=0, y=0, dw=10, dh=10,color_mapper=color_mapper2)
    else:
        # must give a vector of image data for image parameter
        p.image(image=[np.transpose(result[:, :, i])],
                x=0,
                y=0,
                dw=5,
                dh=5,
                color_mapper=color_mapper1)
        # must give a vector of image data for image parameter
        q.image(image=[np.transpose(test[:, :, i])],
                x=0,
                y=0,
                dw=5,
                dh=5,
                color_mapper=color_mapper3)
        r.image(image=[np.transpose(var[:, :, i])],
                x=0,
                y=0,
                dw=5,
                dh=5,
                color_mapper=color_mapper2)
        #s.image(image=[np.transpose(var2[:,:,i])], x=0, y=0, dw=10, dh=10,color_mapper=color_mapper2)

    t = column(row(p, r), q)
    return t
コード例 #23
0
def _create_time_series(dfincident, agg_by, pattern, group_by,
                        types, width=500, height=350):
    """ Create a time series plot of the incident rate. 

    params
    ------
    agg_field: the column name to aggregate by.
    pattern_field: the column name that represents the pattern length to
                 be investigated / plotted.
    incident_types: array, the incident types to be included in the plot.

    return
    ------
    tuple of (Bokeh figure, glyph) showing the incident rate over time.
    """

    def xticker():
        """ Custom function for positioning ticks """
        if (int(tick)%10 == 0) | (len(tick)>2):
            return tick
        else:
            return ""

    x, y, labels = aggregate_data_for_time_series(dfincident, agg_by, 
                                                  pattern, group_by,
                                                  types, None)

    if group_by != "None":
        colors, ngroups = get_colors(len(labels))
        source = ColumnDataSource({"xs": x[0:ngroups],
                                   "ys": y[0:ngroups],
                                   "cs": colors,
                                   "label": labels[0:ngroups]})
    else:
        source = ColumnDataSource({"xs": [x],
                                   "ys": [y],
                                   "cs": ["green"],
                                   "label": ["avg incidents count"]})

    # create plot
    timeseries_tools = "pan,wheel_zoom,reset,xbox_select,hover,save"
    p = figure(tools=timeseries_tools, width=width, height=height,
               x_range=FactorRange(*x))

    glyph = p.multi_line(xs="xs", ys="ys", legend="label", line_color="cs", 
                 source=source, line_width=3)

    # format legend
    p.legend.label_text_font_size = "7pt"
    p.legend.background_fill_alpha = 0.5
    p.legend.location = 'top_left'
    # format ticks
    p.xaxis.formatter = FuncTickFormatter.from_py_func(xticker)
    p.xaxis.major_tick_line_width = 0.1
    p.xaxis.major_label_text_font_size = "5pt"
    p.xaxis.group_text_font_size = "6pt"
    p.xaxis.major_tick_line_color = None
    p.x_range.group_padding = 0.0
    p.x_range.range_padding = 0.0
    p.x_range.subgroup_padding = 0.0

    #p.yaxis.major_tick_line_color = "Red"
    #p.yaxis.major_label_text_font_size = "6pt"
    #p.y_range = Range1d(np.min(y)*0.9, np.max(y)*1.1)
    return p, glyph
コード例 #24
0
def plot_tweet_distributions(frame,
                             terms: list,
                             title='tweet frequencies',
                             **kwargs):
    """
    Uses bokeh to make a jittered plot of tweet timestamps
    :param frame: Dataframe with columns tweetTime (datetime), tweet (int), term (str)
    :param terms: List of terms appearing in the frame
    :param title: Title to disply in plot
    :param kwargs: Possibly contains color_generator, ticker
    If a ticker is included, it should be a function which returns labels for integer
    inputs like this:
        def ticker():
            # Replaces the numeric y axis label with the correct term
            # The dict seems to need to be hardcoded since bokeh
            # messes with any args or values which seem like they should be
            # in scope
            dd = {
                1: 'crps',
                2: 'migraine',
                3: 'fibromyalgia'
            }
            term = dd.get( tick )
            return "{}".format( term )
    """
    try:
        # If was passed a custom color generator, initialize it
        colorgen = kwargs['color_generator'](len(terms))
    except:
        # Otherwise use the default color generator
        colorgen = color_generator(len(terms))

    # initialize the notebook output
    output_notebook()

    # create a new plot with a title and axis labels
    p = figure(title=title,
               x_axis_type="datetime",
               plot_width=800,
               plot_height=500,
               x_axis_label='timestamp',
               y_axis_label='term')

    for term in terms:
        color = next(colorgen)
        source = ColumnDataSource(frame[frame.term == term])
        p.circle(x='tweetTime',
                 y=jitter('tweet', width=0.5, range=p.y_range),
                 fill_color=color,
                 source=source,
                 alpha=0.6)

    p.x_range.range_padding = 0
    p.ygrid.grid_line_color = None
    # p.legend.orientation = "horizontal"

    try:
        # If we were passed a ticker function for labeling the y axis
        # we use it here
        ticker = kwargs['ticker']
        # limit the displayed tick locations to those corresponding to the
        # terms in the dataframe
        tick_locations = [x for x in range(1, len(terms) + 1)]
        p.yaxis.ticker = FixedTicker(ticks=tick_locations)

        # Now add the labels instead of the numbers to the y axis
        p.yaxis.formatter = FuncTickFormatter.from_py_func(ticker)
    except:
        # If we didn't get one, as will likely be true if we are only plotting
        # a single term, no worries.
        pass

    # show the results
    show(p)