コード例 #1
0
def create_circle_legend(circle_var, color_var, legend_min, legend_med, legend_max,
                         x_axis = 'x_axis', y_axis = 'y_axis', 
                         plot_height = 200, plot_width = 140):
    # Get customized df
    circle_df = create_circle_legend_df(color_var, legend_min, legend_med, legend_max)
    
    maxval = circle_df[color_var].max()
    minval = circle_df[color_var].min()
    if maxval > abs(minval):
        minval = maxval * -1 
    if maxval < abs(minval):
        maxval = minval * -1
    colors = list((RdBu[9]))
    exp_cmap = LinearColorMapper(palette=colors, low = minval, high = maxval)
    
    circle = figure(x_range = FactorRange(), y_range = FactorRange(), plot_width= plot_width, 
               plot_height=plot_height, toolbar_location=None, tools="hover")

    circle.scatter(x_axis, y_axis, source = circle_df, fill_alpha=1,  line_width=0, size="size", 
              fill_color={"field":color_var, "transform":exp_cmap})
    
    circle.x_range.factors = sorted(circle_df[x_axis].unique().tolist())
    circle.y_range.factors = circle_df[y_axis].unique().tolist() # plots in reverse order of circle_df (max to min)
    circle.xaxis.major_label_orientation = math.pi/2
    
    circle.xaxis.axis_label = 'FDR p-value'
    
    return circle
コード例 #2
0
ファイル: test_helpers.py プロジェクト: zz412000428/bokeh
 def test_axis_type_auto(self):
     assert(bph._get_axis_class("auto", FactorRange(), 0)) == (CategoricalAxis, {})
     assert(bph._get_axis_class("auto", FactorRange(), 1)) == (CategoricalAxis, {})
     assert(bph._get_axis_class("auto", DataRange1d(), 0)) == (LinearAxis, {})
     assert(bph._get_axis_class("auto", DataRange1d(), 1)) == (LinearAxis, {})
     assert(bph._get_axis_class("auto", Range1d(), 0)) == (LinearAxis, {})
     assert(bph._get_axis_class("auto", Range1d(), 1)) == (LinearAxis, {})
     assert(bph._get_axis_class("auto", Range1d(start=datetime.datetime(2018, 3, 21)), 0)) == (DatetimeAxis, {})
     assert(bph._get_axis_class("auto", Range1d(start=datetime.datetime(2018, 3, 21)), 1)) == (DatetimeAxis, {})
コード例 #3
0
def plotCircleHeatMap ( df, circle_var, color_var, x_axis, y_axis, plot_width= 1000, plot_height = 650, font_size = 12,    x_axis_lab = "no_label", y_axis_lab = "no_label", show_plot = True, save_png = "plot.png", legend_min = 1e-6, legend_med = .0001, legend_max = 0.01, show_legend = True):
  
    # circle_var designed for pvalues. Normalized by taking log 10 of values and multiplying by 5 
    #added a new column to make the plot size
    
    df["size2"] = df[circle_var].apply(lambda x: -1*(np.log(x)))
    df['size'] = (df["size2"])*3
    #find values to set color bar min/ max as 
    maxval = df[color_var].max()
    minval = df[color_var].min()
    if maxval > abs(minval):
        minval = maxval * -1 
    if maxval < abs(minval):
        maxval = minval * -1
    colors = list((RdBu[9]))
    exp_cmap = LinearColorMapper(palette=colors, low = minval, high = maxval)
    p = figure(x_range = FactorRange(), y_range = FactorRange(), plot_width= plot_width, 
               plot_height=plot_height, 
               toolbar_location=None, tools="hover")

    p.scatter(x_axis,y_axis,source=df, fill_alpha=1,  line_width=0, size="size", 
              fill_color={"field":color_var, "transform":exp_cmap})

    #p.x_range.factors = sorted(df[x_axis].unique().tolist())
    p.x_range.factors = df[x_axis].unique().tolist()
    p.y_range.factors = sorted(df[y_axis].unique().tolist(), reverse = True)
    p.xaxis.major_label_orientation = math.pi/2
    
    # font size
    p.axis.major_label_text_font_size = str(font_size)+"pt"
    
    if (x_axis_lab != "no_label" ):
        p.xaxis.axis_label = x_axis_lab
    if (y_axis_lab != "no_label" ):   
        p.yaxis.axis_label = y_axis_lab

    bar = ColorBar(color_mapper=exp_cmap, location=(0,0))
    p.add_layout(bar, "right")
    
    if show_plot:  
        if show_legend:
            # Create Circle Legend
            circle_legend = create_circle_legend(circle_var, color_var, legend_min, legend_med, legend_max)
            circle_legend.axis.major_label_text_font_size = str(font_size - 1)+"pt" # font size
            output_notebook()
            show(row(p, circle_legend))
        else:
            output_notebook()
            show(p)
      
    if save_png != "plot.png":
        export_png(row(p, circle_legend), filename= save_png)
        
    return p
コード例 #4
0
def plotCircleHeatMap(df,
                      circle_var,
                      color_var,
                      x_axis,
                      y_axis,
                      plot_width=1000,
                      plot_height=650,
                      x_axis_lab="no_label",
                      y_axis_lab="no_label"):

    # circle_var designed for pvalues. Normalized by taking log 10 of values and multiplying by 5
    #added a new column to make the plot size

    df["size"] = (np.log10(df[circle_var]))
    df["size"] = np.abs(df["size"])
    df['size'] = np.where(df["size"] < 0, np.abs(df["size"]), (df["size"])) * 5
    maxval = df[color_var].max()
    minval = df[color_var].min()
    colors = list((RdBu[9]))
    exp_cmap = LinearColorMapper(palette=colors, low=minval, high=maxval)
    p = figure(x_range=FactorRange(),
               y_range=FactorRange(),
               plot_width=plot_width,
               plot_height=plot_height,
               toolbar_location=None,
               tools="hover")

    p.scatter(x_axis,
              y_axis,
              source=df,
              fill_alpha=1,
              line_width=0,
              size="size",
              fill_color={
                  "field": color_var,
                  "transform": exp_cmap
              })

    p.x_range.factors = sorted(df[x_axis].unique().tolist())
    p.y_range.factors = sorted(df[y_axis].unique().tolist(), reverse=True)
    p.xaxis.major_label_orientation = math.pi / 2

    if (x_axis_lab != "no_label"):
        p.xaxis.axis_label = x_axis_lab
    if (x_axis_lab != "no_label"):
        p.yaxis.axis_label = y_axis_lab

    bar = ColorBar(color_mapper=exp_cmap, location=(0, 0))
    p.add_layout(bar, "right")
    output_notebook()
    show(p)
コード例 #5
0
def sort_axis(data, key, reverse=False, continous=True):
    '''
    returns list of strings to be used as axis label ticks
    data - list of dicts with all the data rows
    key - str(): 'key' to take out the values from each item of list to use as axis range
    reverse - True/False if to sort in reverse order
    continous - True/False - for 'number like' values - if only use the values in rows or to create mid-values in range of min/max value
    '''
    values = [value[key] for value in data]
    values = list(set(values))
    if 'date' in key and continous:
        from itertools import product
        temp = [[] for item in values[0].split('-')]
        for i in values:
            temp[0].append(int(i.split('-')[0]))
        if len(temp) >= 2:
            temp[1].extend([1, 12])
        if len(temp) >= 3:
            temp[2].extend([1, 31])
        for no, grp in enumerate(temp):
            temp[no] = ['%02d' % i for i in range(min(grp), max(grp) + 1)]
        temp = list(product(*temp))
        for no, item in enumerate(temp):
            temp[no] = '-'.join(item)
        values = temp
    elif continous:
        try:
            temp = []
            for item in values:
                temp.append(int(item))
            values = ['%02d' % i for i in range(min(temp), max(temp) + 1)]
        except:
            pass
    values.sort(reverse=reverse)
    return FactorRange(factors=values)
コード例 #6
0
def create_figure():

    dfDemo = dfD[dfD["Pronoun"].isin([genders[i] for i in pronoun.active])]

    dfPracts = dfDemo[dfDemo["Primary Role"]=="Data Science Industry Practitioner"]["Position in Firm"].value_counts()
    dfProfs = dfDemo[dfDemo["Primary Role"]=="Data Science Faculty Member/Instructor at Higher Ed Institution"]["Academic position"].value_counts()

    dfBothAcad = dfDemo[dfDemo["Primary Role"]=="Both Practitioner and Faculty Member/Instructor"]["Academic position"].value_counts()
    dfBothFirm = dfDemo[dfDemo["Primary Role"]=="Both Practitioner and Faculty Member/Instructor"]["Position in Firm"].value_counts()
    dfBoth = pd.concat([dfBothAcad,dfBothFirm])
    dfBoth = dfBoth.groupby(dfBoth.index).sum().sort_values(ascending=False)

    dfTotal = pd.DataFrame([dfPracts,dfProfs,dfBothAcad,dfBothFirm],
                          index=["Practitioners","Professors","Both-Academic Position","Both-Industry Position"])

    dfTotal = dfTotal.reindex(['Vice-President', 'Senior','Junior', 'Other (please specify)','Adjunct/Part-Time','Assistant Professor',
          'Associate Professor',  'Full Professor'],
                             axis=1).rename({"Other (please specify)":"Other"},axis=1)

    pt = dfTotal.cumsum(axis=1)
    p = figure(title="Count of Positions of Data Science Professionals",
              x_axis_label='Primary Role', y_axis_label='Total',
              x_range = FactorRange(factors=list(pt.index)),
              plot_height=600, plot_width=900,tools=[])
    for column,color in zip(pt.columns,all_palettes['PiYG'][len(pt.columns)]):
       p.vbar(x=pt.index,bottom=pt[column]-dfTotal[column],top=pt[column],width=.2,color=color, legend = column)
    p.ygrid.minor_grid_line_color = 'black'
    p.ygrid.minor_grid_line_alpha = 0.1



    p.legend.location = "top_left"

    p.toolbar.logo = None
    return p
コード例 #7
0
    def test_chart_tools_linear(self, mock_warn):
        base_args = dict(
            title="title", xlabel="xlabel", ylabel="ylabel",
            legend="top_left", xscale="linear", yscale="linear", xgrid=True, ygrid=True,
            width=800, height=600,
        )
        expected = [
            [PanTool,  WheelZoomTool, BoxZoomTool, PreviewSaveTool, ResizeTool, ResetTool, HelpTool],
            [],
            [ResizeTool, PanTool,  BoxZoomTool, ResetTool, LassoSelectTool],
        ]
        scenarios = zip(
            [True, False, "resize,pan,box_zoom,reset,lasso_select"], expected
        )

        self.check_tools_scenario(base_args, scenarios)

        self.check_tools_scenario(base_args, scenarios, categorical=True)

        msg_repeat = "LassoSelectTool are being repeated"
        expected_tools = [ResizeTool, PanTool, BoxZoomTool, ResetTool, LassoSelectTool, LassoSelectTool]
        mock_warn.reset_mock()

        # Finally check removing tools
        base_args['tools'] = "resize,pan,box_zoom,reset,lasso_select,lasso_select"

        chart = Chart(**base_args)
        chart.x_range = FactorRange()

        self.compare_tools(chart.tools, expected_tools)
        mock_warn.assert_any_call(msg_repeat)
コード例 #8
0
ファイル: test_chart.py プロジェクト: ogrisel/bokeh
    def test_chart_tools_linear(self, mock_warn):
        base_args = dict(title="title",
                         xlabel="xlabel",
                         ylabel="ylabel",
                         legend="top_left",
                         xscale="linear",
                         yscale="linear",
                         xgrid=True,
                         ygrid=True,
                         width=800,
                         height=600,
                         filename=False,
                         server=False,
                         notebook=False)
        expected = [
            [
                PanTool, WheelZoomTool, BoxZoomTool, PreviewSaveTool,
                ResizeTool, ResetTool
            ],
            [],
            [ResizeTool, PanTool, BoxZoomTool, ResetTool, LassoSelectTool],
        ]
        scenarios = zip(
            [True, False, "resize,pan,box_zoom,reset,lasso_select"], expected)

        self.check_tools_scenario(base_args, scenarios)

        # need to change the expected tools because categorical scales
        # automatically removes pan and zoom tools
        expected = [
            [PreviewSaveTool, ResizeTool, ResetTool],
            [],
            [ResizeTool, ResetTool, LassoSelectTool],
        ]
        scenarios = zip(
            [True, False, "resize,pan,box_zoom,reset,lasso_select"], expected)
        self.check_tools_scenario(base_args, scenarios, categorical=True)

        msg_repeat = "LassoSelectTool are being repeated"
        msg_removed = "categorical plots do not support pan and zoom operations.\n" \
                      "Removing tool(s): pan, box_zoom"
        expected_tools = [
            ResizeTool, ResetTool, LassoSelectTool, LassoSelectTool
        ]
        mock_warn.reset_mock()

        # Finally check repeated tools
        base_args[
            'tools'] = "resize,pan,box_zoom,reset,lasso_select,lasso_select"

        chart = Chart(**base_args)
        chart.x_range = FactorRange()
        chart.tools = []
        chart.create_tools(chart._options.tools)

        self.compare_tools(chart.tools, expected_tools)
        mock_warn.assert_any_call(msg_repeat)
        mock_warn.assert_any_call(msg_removed)
コード例 #9
0
ファイル: test_chart.py プロジェクト: ogrisel/bokeh
    def check_tools_scenario(self, base_args, scenarios, categorical=False):
        for tools, expected_tools in scenarios:
            base_args['tools'] = tools
            chart = Chart(**base_args)

            if categorical:
                chart.x_range = FactorRange()
                chart.tools = []
                chart.create_tools(chart._options.tools)
                self.compare_tools(chart.tools, expected_tools)

                chart = Chart(**base_args)
                chart.y_range = FactorRange()
                chart.tools = []
                chart.create_tools(chart._options.tools)
                self.compare_tools(chart.tools, expected_tools)

            else:
                self.compare_tools(chart.tools, expected_tools)
コード例 #10
0
    def _get_range(self, dim, start, end):
        """Create a :class:`Range` for the :class:`Chart`.

        Args:
            dim (str): the name of the dimension, which is an attribute of the builder
            start: the starting value of the range
            end: the ending value of the range

        Returns:
            :class:`Range`
        """
        dim_ref = getattr(self, dim)
        values = dim_ref.data
        dtype = dim_ref.dtype

        sort = self.sort_dim.get(dim)

        # object data or single value
        if dtype.name == 'object':
            factors = values.drop_duplicates()
            if sort:
                # TODO (fpliger):   this handles pandas API change so users do not experience
                #                   the related annoying deprecation warning. This is probably worth
                #                   removing when pandas deprecated version (0.16) is "old" enough
                try:
                    factors.sort_values(inplace=True)
                except AttributeError:
                    factors.sort(inplace=True)

            setattr(self, dim + 'scale', 'categorical')
            return FactorRange(factors=factors.tolist())
        elif np.issubdtype(dtype, np.datetime64):
            setattr(self, dim + 'scale', 'datetime')
            return Range1d(start=start, end=end)
        else:

            if end == 'None' or (end - start) == 0:
                setattr(self, dim + 'scale', 'categorical')
                return FactorRange(factors=['None'])
            else:
                diff = end - start
                setattr(self, dim + 'scale', 'linear')
                return Range1d(start=start - 0.1 * diff, end=end + 0.1 * diff)
コード例 #11
0
    def _plot_bokeh(self, current_plot, show_legend=True):
        from bokeh.models.tools import HoverTool
        from collections import OrderedDict
        from bokeh.models.ranges import FactorRange
        import bokeh.plotting as bkh

        value_lst = self.matrix.flatten()
        min_el = min(value_lst)
        vmax = float(max(value_lst) - min_el)
        color_lst = [BOKEH_CMAP[int((v - min_el) / vmax * (len(BOKEH_CMAP) - 1))] \
                     for v in value_lst]

        source = bkh.ColumnDataSource(
            data=dict(
                x=self.labels * self.matrix.shape[0],
                y=numpy.array([[i] * self.matrix.shape[1] for i in self.labels]).flatten(),
                color=color_lst,
                value=value_lst,
            )
        )
        # current_plot._below = []
        current_plot.x_range = FactorRange(factors=self.labels)
        current_plot.y_range = FactorRange(factors=self.labels)
        # current_plot._left = []

        # current_plot.extra_y_ranges = {"foo": bkh.FactorRange(factors=self.labels)}
        # current_plot.add_layout(CategoricalAxis(y_range_name="foo"), place='left')
        # current_plot.extra_x_ranges = {"foo": bkh.FactorRange(factors=self.labels)}
        # current_plot.add_layout(CategoricalAxis(x_range_name="foo"), place='top')

        current_plot.rect('x', 'y', 0.98, 0.98, source=source, color='color', line_color=None)
        current_plot.grid.grid_line_color = None
        current_plot.axis.axis_line_color = None
        current_plot.axis.major_tick_line_color = None
        hover = current_plot.select(dict(type=HoverTool))
        if not hover:
            hover = HoverTool(plot=current_plot, always_active=True)
        hover.tooltips = OrderedDict([
            ('labels', '@x @y'),
            ('value', '@value')
        ])
        current_plot.tools.append(hover)
        return current_plot
コード例 #12
0
def plot_amp_qa(data, name, lower=None, upper=None, amp_keys=None, title=None, plot_height=80, plot_width=700, ymin=None, ymax=None):
    '''Creates gridplot of 3 camera separated amp plots
    Args:
        data: table of per_amp qadata
        name: metric being plotted (str)
    Options:
        lower: list of lower thresholds per camera from get_thresholds()
            format: [[lower_errB, lowerB], [lower_errR, lowerR], [lower_errZ, lowerZ]]
        upper: list of upper thresholds per camera from get_thresholds()
            format : [[upperB, upper_errB], [upperR, upper_errR], [upperZ, upper_errZ]]
        amp_keys: list of amps that have data
        title: title for plot, if different than name (str)
        plot_height, plot_width: height, width of graph in pixels
        ymin/ymax: lists of y axis ranges for B, R, Z plots, unless data exceeds these
    Output:
        Bokeh gridplot object'''
    
    if title == None:
        title = name
        
    labels = [(spec, amp) for spec in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] for amp in ['A', 'B', 'C', 'D']]
    
    figs = []
    for cam in ['B', 'R', 'Z']:
        if cam == 'B':
            fig = plot_amp_cam_qa(data, name, cam, labels, title, lower=lower, upper=upper, amp_keys=amp_keys, plot_height=plot_height+25, plot_width=plot_width, ymin=ymin[0], ymax=ymax[0])
        if cam == 'R':
            fig = plot_amp_cam_qa(data, name, cam, labels, title, lower=lower, upper=upper, amp_keys=amp_keys, plot_height=plot_height, plot_width=plot_width, ymin=ymin[1], ymax=ymax[1])
        if cam == 'Z':
            fig = plot_amp_cam_qa(data, name, cam, labels, title, lower=lower, upper=upper, amp_keys=amp_keys, plot_height=plot_height, plot_width=plot_width, ymin=ymin[2], ymax=ymax[2])
            
        
        if name == "BIAS":
            fig.yaxis.ticker = AdaptiveTicker(base=10, desired_num_ticks=5, 
                                              mantissas=np.arange(1, 5.5, 0.5), 
                                              min_interval=1)
            fig.yaxis.formatter = NumeralTickFormatter(format='e')
        else:
            fig.yaxis.ticker = AdaptiveTicker(base=10, desired_num_ticks=5, 
                                              mantissas=np.arange(1, 5.5, 0.5), 
                                              min_interval=1)
            fig.yaxis.formatter = NumeralTickFormatter(format='a')
        figs.append(fig)
    
    # x-axis labels for spectrograph 0-9 and amplifier A-D
    axis = bk.figure(x_range=FactorRange(*labels), toolbar_location=None,
                     plot_height=50, plot_width=plot_width,
                     y_axis_location=None)
    axis.line(x=labels, y=0, line_color=None)
    axis.grid.grid_line_color=None
    axis.outline_line_color=None

    fig = gridplot([[figs[0]], [figs[1]], [figs[2]], [axis]], toolbar_location='right')

    return fig
コード例 #13
0
def plot_total_time(stats: pd.DataFrame,
                    palette: Palette = Spectral5) -> Figure:
    """Plots a summary bar graph giving total run time for each configuration
        and run.

    Args:
        stats (pd.DataFrame): Data frame containing the statistics output
        palette (Palette, optional): Colour palette. Defaults to Spectral5.

    Returns:
        figure.Figure: The plotting figure
    """

    if stats.configuration.nunique() == 1:
        # Group by run only
        y = stats.run.unique()
        by = ["run"]
    elif stats.run.nunique() == 1:
        # Group by configuration only
        y = stats.configuration.unique()
        by = ["configuration"]
    else:
        # Group by both
        y = [(c, r) for c in stats.configuration.unique()
             for r in stats.run.unique()]
        by = ["configuration", "run"]
    df = stats.groupby(by=by).sum()
    tooltips = [
        ("configuration", "@" + "_".join(by)),
        ("time", "@time"),
    ]
    p = figure(
        y_range=FactorRange(*y),
        title="Total run time for all instances",
        tooltips=tooltips,
    )
    p.hbar(
        y="_".join(by),
        right="time",
        height=0.5,
        fill_color=factor_cmap(
            "_".join(by),
            palette=palette,
            factors=stats.run.unique() if len(by) > 1 else y,
            start=len(by) - 1,
        ),
        line_color=None,
        source=ColumnDataSource(df),
    )
    p.x_range.start = 0
    p.xaxis.axis_label = "Time (s)"
    p.yaxis.axis_label = "Configuration"
    return p
コード例 #14
0
    def _update_histogram(self, figure, source, hist, edges, name=""):
        if isinstance(edges[0], str):
            figure.x_range = FactorRange(factors=edges)
        else:
            figure.x_range = DataRange1d()

        source.data = self._hist_source_dict(hist, edges)

        if name:
            figure.title.text = name

        figure.y_range.start = -0.1 * np.max(hist)
        figure.y_range.end = 1.1 * np.max(hist)
コード例 #15
0
ファイル: nb9utils.py プロジェクト: xyzh43/CSE6040x
def make_stacked_barchart(df,
                          x_var,
                          cat_var,
                          y_var,
                          fillna=True,
                          x_labels=None,
                          bar_labels=None,
                          kwargs_figure={}):
    from bokeh.models import ColumnDataSource
    from bokeh.plotting import figure
    from bokeh.core.properties import value
    from bokeh.models.ranges import FactorRange
    from bokeh.io import show
    from bokeh.plotting import figure

    assert type(x_var) is str, "x-variable should be a string but isn't."
    assert type(
        cat_var) is str, "category variable should be a string but isn't."
    assert type(y_var) is str, "y-variable should be a string but isn't."

    pt = df.pivot(x_var, cat_var, y_var)
    if fillna:
        pt.fillna(0, inplace=True)
    pt = pt.cumsum(axis=1)
    bar_vars = pt.columns

    from bokeh.palettes import brewer
    assert len(bar_vars) in brewer['Dark2'], "Not enough colors."

    x = x_labels if x_labels is not None else FactorRange(
        factors=list(pt.index))
    legend = bar_labels if bar_labels is not None else list(bar_vars)
    colors = brewer['Dark2'][len(bar_vars)]
    source = ColumnDataSource(data=df)

    p = figure(x_range=x, **kwargs_figure)
    bot = 0
    for k, var in enumerate(bar_vars):
        p.vbar(x=pt.index,
               bottom=bot,
               top=pt[var],
               color=colors[k],
               legend=var,
               width=0.25)
        bot = pt[var]
    return p
コード例 #16
0
ファイル: competition_geography.py プロジェクト: kktse/fsaem
def generate_chart(year):
    data = get_data(year)

    plot_data = {
        'country': data.index.tolist(),
        'count': [float(i) for i in data.values.tolist()]
    }

    barchart = Bar(plot_data,
                   label='country',
                   values='count',
                   color="red",
                   xgrid=False,
                   ygrid=False,
                   plot_width=800,
                   plot_height=500,
                   tools="pan,wheel_zoom,box_zoom,reset,resize")

    barchart.title = "Formula SAE Michigan " + year + " Countries"

    barchart.x_range = FactorRange(factors=data.index.tolist())

    barchart._xaxis.axis_label = "Country"
    barchart._xaxis.axis_line_color = None
    barchart._xaxis.major_tick_line_color = None
    barchart._xaxis.minor_tick_line_color = None

    barchart._yaxis.axis_label = "Number of Teams"
    barchart._yaxis.axis_line_color = None
    barchart._yaxis.major_tick_line_color = None
    barchart._yaxis.minor_tick_line_color = None

    barchart.outline_line_color = None

    barchart.toolbar_location = 'right'

    barchart.logo = None

    hover = HoverTool(tooltips=[("Country", '@x'), ("# Teams", '@height')])

    barchart.add_tools(hover)

    return barchart
コード例 #17
0
    def bar(self,
            data_frame: pd.DataFrame,
            category: str = None,
            value: float = None,
            text: str = None,
            color: str = None,
            title: str = None):
        source = construct_categorical_data(data_frame,
                                            c_col=category,
                                            v_col=value,
                                            text_col=text)

        p = self._chart.figure
        if title is not None:
            self._chart.set_title(title)

        p.x_range = FactorRange(factors=data_frame[category].values)
        p.y_range = Range1d(0, data_frame[value].max() * 1.1)
        p.yaxis.formatter = self.tick_formater('integer')
        if data_frame[category].nunique() > 5:
            p.xaxis.major_label_orientation = math.pi / 2

        p.vbar(x='category',
               top='value',
               width=0.5,
               color=self.next_color(),
               source=source)
        y_offset = 20
        #        y_offset = data_frame[value].max() * 0.1
        if text is not None:
            text_glyph = Text(x="category",
                              y="value",
                              y_offset=y_offset,
                              text="text",
                              text_align='center',
                              text_font_size='10pt',
                              text_color="white")
            p.add_glyph(source, text_glyph)

        return self
コード例 #18
0
def barplot(x=None,
            y=None,
            data=None,
            stacked=False,
            width=500,
            height=500,
            hue_order=None,
            p=None,
            **plot_kw):

    grouped = data.groupby(x, sort=False)
    x_values = list(grouped.groups.keys())
    metadata = grouped.pipe(filter_groups, approx=True)

    if p is None:
        p = figure(x_range=FactorRange(*x_values),
                   width=width,
                   height=height,
                   x_axis_label=x[0],
                   y_axis_label=y)

    data = dict(x=x_values, y=grouped[y].agg('mean'))
    data.update({col: metadata[col] for col in metadata.columns})

    if len(x) > 1:
        data['color'] = grouped['color'].nth(0, dropna='all')
        data[x[1]] = grouped[x[1]].nth(0, dropna='all')

    p.vbar(x='x',
           top='y',
           width=0.9,
           line_color='black',
           source=data,
           **plot_kw)
    p.xaxis.major_label_orientation = "vertical"

    return p
コード例 #19
0
def update(json_data):
    sql_data = json_to_sql(json_data)
    data = get_dataframe(sql_data)

    columns = data.columns.tolist()
    columns.remove('x')

    x_axis_data = [(x, z) for x in data['x'] for z in columns]

    to_zip = [data[c].tolist() for c in columns]

    y_axis_data = sum(zip(*to_zip), ())

    source = ColumnDataSource(
        data=dict(x_axis_data=x_axis_data, y_axis_data=y_axis_data))

    p = figure(x_range=FactorRange(*x_axis_data),
               plot_width=1200,
               plot_height=600,
               title="Chart with Zip implementation")

    p.vbar(x='x_axis_data',
           top='y_axis_data',
           width=1,
           source=source,
           line_color="white",
           fill_color=factor_cmap('x_axis_data',
                                  palette=viridis(len(columns)),
                                  factors=columns,
                                  start=1,
                                  end=len(columns)))

    p.y_range.start = 0
    p.x_range.range_padding = 0.1
    p.xaxis.major_label_orientation = 1
    p.xgrid.grid_line_color = None
    return p
コード例 #20
0
def create_weight_plot(df):
	"""Crea gráfico de importancia de variables sobre calidad del agua
	
	Parameters:
		df (Dataframe): Dataframe con los datos a mostrar en la visualización

	Returns:
		DataTable: Gráfico de importancia de variables sobre calidad del agua
	"""

	source = ColumnDataSource(df)

	TOOLTIPS = [
		('Atributo', '@Attribute'),
		('Peso', '@Weight'),
	]

	weight_plot = figure(max_width=650, height=400, toolbar_location=None, sizing_mode='stretch_width',y_range=FactorRange(factors=source.data['Attribute']), x_range=(0,1), tooltips=TOOLTIPS)
	weight_plot.hbar(y='Attribute', left='Weight', right=0, source=source, height=0.6, fill_color=bokeh_utils.BAR_COLORS_PALETTE[0], line_color=bokeh_utils.BAR_COLORS_PALETTE[0])

	weight_plot.title.text = 'Peso de indicadores influentes'
	weight_plot.title.text_color = bokeh_utils.TITLE_FONT_COLOR
	weight_plot.title.align = 'left'
	weight_plot.title.text_font_size = '16px'
	weight_plot.title.offset = -100
	weight_plot.min_border_right = 15
	weight_plot.xaxis.major_label_text_color = bokeh_utils.LABEL_FONT_COLOR
	weight_plot.yaxis.major_label_text_color = bokeh_utils.LABEL_FONT_COLOR
	weight_plot.border_fill_color = bokeh_utils.BACKGROUND_COLOR

	return weight_plot
コード例 #21
0
ファイル: insert_book.py プロジェクト: treekhshai/Bookstore
                   columns=['category', 'amount'])

source = ColumnDataSource(dict(x=[], y=[]))

x_label = "Category"
y_label = "Amount"
title = "BAR PLOT"
import itertools
from bokeh.models.ranges import FactorRange
import math
plot = figure(plot_width=600,
              plot_height=600,
              x_axis_label=x_label,
              y_axis_label=y_label,
              title=title,
              x_range=FactorRange(factors=list(dat.category)))
source = ColumnDataSource(dict(x=[], y=[], color=[]))
plot.vbar(source=source, x='x', top='y', color='color', bottom=0, width=0.3)
plot.xaxis.major_label_orientation = math.pi / 2


def authorview():
    global plot
    global db
    global source
    tempdf = pd.read_sql('SELECT * FROM sales_by_author', db)
    colors = colors = itertools.cycle(Spectral6)
    c = []
    for i, x in enumerate(colors):
        c.append(x)
        print(i)
コード例 #22
0
ファイル: test_plots.py プロジェクト: sherry-tan/bokeh
def test__check_compatible_scale_and_ranges_incompat_numeric_scale_and_factor_range(
):
    plot = Plot(x_scale=LinearScale(), x_range=FactorRange())
    check = plot._check_compatible_scale_and_ranges()
    assert check != []
コード例 #23
0
ファイル: test_plots.py プロジェクト: sherry-tan/bokeh
 def test_get_set_multi_mismatch(self):
     obj = bmp._list_attr_splat([LinearAxis(), FactorRange()])
     with pytest.raises(AttributeError) as e:
         obj.formatter.power_limit_low == 10
     assert str(e.value).endswith("list items have no %r attribute" %
                                  "formatter")
コード例 #24
0
ファイル: test_plots.py プロジェクト: sherry-tan/bokeh
 def get_range_instance():
     return FactorRange('foo', 'bar')
コード例 #25
0
ファイル: test_plots.py プロジェクト: sherry-tan/bokeh
def test__check_compatible_scale_and_ranges_compat_factor():
    plot = Plot(x_scale=CategoricalScale(), x_range=FactorRange())
    check = plot._check_compatible_scale_and_ranges()
    assert check == []
コード例 #26
0
    def plot_team_stat(comparison_stat, agg_func):
        """Creates figures with bars plots of teams stats.

        :param comparison_stat: str. Statistic to plot.
        :param agg_func: str. 'mean' or 'sum'.
        :return: bokeh figures.
        """

        map_agg_func = ('mean', 'sum')
        data = create_data_source(comparison_stat, map_agg_func[agg_func])
        source = ColumnDataSource(data=data)
        teams = list(source.data['team'])

        # Plot avg stat per game

        p_1 = figure(x_range=FactorRange(factors=teams),
                     plot_height=400,
                     plot_width=700)

        hover = HoverTool(tooltips=[('', '@{Total}')])
        hover.point_policy = 'follow_mouse'
        p_1.add_tools(hover)

        p_1.vbar(x='team',
                 top='Total',
                 source=source,
                 width=0.4,
                 color=Spectral4[0])

        p_1.x_range.range_padding = 0.05
        p_1.xaxis.major_label_orientation = 1
        p_1.xaxis.major_label_text_font_size = "10pt"
        p_1.toolbar_location = None

        # Plot breakdown by match result

        p_2 = figure(x_range=FactorRange(factors=teams),
                     plot_height=400,
                     plot_width=700,
                     tools='hover',
                     tooltips='@$name',
                     title='Breakdown by Match Result')

        w = p_2.vbar(x=dodge('team', -0.25, range=p_2.x_range),
                     top='w',
                     width=0.2,
                     source=source,
                     color=Spectral4[1],
                     name='w')
        d = p_2.vbar(x=dodge('team', 0.0, range=p_2.x_range),
                     top='d',
                     width=0.2,
                     source=source,
                     color=Spectral4[2],
                     name='d')
        l = p_2.vbar(x=dodge('team', 0.25, range=p_2.x_range),
                     top='l',
                     width=0.2,
                     source=source,
                     color=Spectral4[3],
                     name='l')

        legend_it = [('Won', [w]), ('Drew', [d]), ('Lost', [l])]
        legend = Legend(items=legend_it, location=(0, 155))

        p_2.add_layout(legend, 'right')
        p_2.title.text_font_size = '12pt'
        p_2.x_range.range_padding = 0.05
        p_2.xgrid.grid_line_color = None
        p_2.xaxis.major_label_text_font_size = "10pt"
        p_2.xaxis.major_label_orientation = 1
        p_2.toolbar_location = None

        return p_1, p_2
コード例 #27
0
def boxplot_series(groups,
                   values,
                   xlim=(None, None),
                   ylim=(None, None),
                   **kwargs):
    """Create a (e.g. time-) series of boxplots for a variable.

    :param groups: the grouping variable (the x-axis values). The function
        will handle also non-numeric, categorical grouping variables (though
        the sort order is not controllable).
    :param values: the data for boxplots are drawn (the y-axis values).
    :param xlim: tuple for plotting limits (start, end). A value None will
        trigger calculation from the data.
    :param ylim: tuple for plotting limits (start, end). A value None will
        trigger calculation from the data.
    :param kwargs: kwargs for bokeh figure.

    :returns: a bokeh plot.

    After creating this plot, you may wish to change the following:

        * p.xaxis.axis_label = 'Read Length / bases'
        * p.yaxis.axis_label = 'Number of reads'
    """
    df = pd.DataFrame(dict(group=groups, value=values))
    uniq = df.group.unique()
    # numeric or categorical
    if not np.issubdtype(uniq.dtype, np.number):
        x_range = FactorRange(factors=uniq)
    else:
        xlim = util.Limiter(util.pad(uniq)).fix(*xlim)
        x_range = Range1d(start=xlim.min,
                          end=xlim.max,
                          bounds=(xlim.min, xlim.max))

    # find the quartiles and IQR for each category
    groups = df.groupby('group')
    quantiles = groups.quantile([0.25, 0.5, 0.75])
    quantiles.index.names = ['group', 'quantile']
    uniq = groups.apply(lambda x: x.name).tolist()
    q1 = quantiles.xs(0.25, level='quantile')
    q2 = quantiles.xs(0.50, level='quantile')
    q3 = quantiles.xs(0.75, level='quantile')
    iqr = q3 - q1
    upper = q3 + 1.5 * iqr
    lower = q1 - 1.5 * iqr

    defaults = {"output_backend": "webgl", "height": 300, "width": 600}
    defaults.update(kwargs)

    ylim = util.Limiter().accumulate(df['value']).fix(*ylim)
    y_range = Range1d(start=ylim.min,
                      end=ylim.max,
                      bounds=(ylim.min, ylim.max))

    p = figure(**defaults, x_range=x_range, y_range=y_range)

    # stems
    p.segment(uniq, upper.value, uniq, q3.value, line_color="black")
    p.segment(uniq, lower.value, uniq, q1.value, line_color="black")

    # boxes
    for low, high in ((q2.value, q3.value), (q1.value, q2.value)):
        p.vbar(uniq, 0.8, low, high, line_color='black')

    return p
コード例 #28
0
def test__get_scale_factor_range():
    s = bph._get_scale(FactorRange(), "auto")
    assert isinstance(s, CategoricalScale)
コード例 #29
0
    r = kw['edge_renderer']
    assert r.glyph.line_color == "purple"
    assert r.selection_glyph.line_color == "blue"
    assert r.nonselection_glyph.line_color == "yellow"
    assert r.hover_glyph.line_color == "red"
    assert r.muted_glyph.line_color == "orange"

    assert r.glyph.line_width == 23
    assert r.selection_glyph.line_width == 23
    assert r.nonselection_glyph.line_width == 23
    assert r.hover_glyph.line_width == 23
    assert r.muted_glyph.line_width == 23


_RANGES = [Range1d(), DataRange1d(), FactorRange()]


class Test__get_axis_class(object):
    @pytest.mark.parametrize('range', _RANGES)
    @pytest.mark.unit
    def test_axis_type_None(self, range):
        assert (bph._get_axis_class(None, range, 0)) == (None, {})
        assert (bph._get_axis_class(None, range, 1)) == (None, {})

    @pytest.mark.parametrize('range', _RANGES)
    @pytest.mark.unit
    def test_axis_type_linear(self, range):
        assert (bph._get_axis_class("linear", range, 0)) == (LinearAxis, {})
        assert (bph._get_axis_class("linear", range, 1)) == (LinearAxis, {})
コード例 #30
0
def make_graf(p, pav, count, factor):
    p = figure(x_range=[-5, 5],
               y_range=FactorRange(factors=factor),
               height=heigth_count(count),
               tools="save",
               toolbar_location="above")
    p.title.text = "<-Katabolizmas|Anabolizmas->"
    p.title.align = "center"
    # p.output_backend = "svg"
    p.text(x=[-4.7],
           y=[(count - (count - 3) / 3 - 1)],
           text=["Rytas"],
           text_font_size='10pt',
           text_font_style="bold",
           angle=1.56)
    p.text(x=[-4.7],
           y=[(count - (count - 3) / 3 * 2 - 2)],
           text=["Pietūs"],
           text_font_size='10pt',
           text_font_style="bold",
           angle=1.56)
    p.text(x=[-4.7],
           y=[(count - count)],
           text=["Vakaras"],
           text_font_size='10pt',
           text_font_style="bold",
           angle=1.56)
    p.x_range.bounds = 'auto'
    p.y_range.bounds = 'auto'
    p.xaxis.axis_label = pav
    p.yaxis.visible = False
    p.xaxis.ticker = FixedTicker(
        ticks=[-3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5])
    p.xaxis.major_label_overrides = {
        -3.5: "Didelis",
        -2.5: "Vidutinis",
        -1.5: "Mažas",
        -0.5: "Norma",
        0.5: "Norma",
        1.5: "Mažas",
        2.5: "Vidutinis",
        3.5: "Didelis"
    }
    p.xaxis.major_tick_line_color = None
    # p.output_backend = "svg"

    p.add_layout(
        Span(location=0,
             dimension='height',
             line_color='black',
             line_dash='solid',
             line_width=4))
    p.add_layout(
        Span(location=1,
             dimension='height',
             line_color='green',
             line_dash='dashed',
             line_width=4))
    p.add_layout(
        Span(location=-1,
             dimension='height',
             line_color='green',
             line_dash='dashed',
             line_width=4))
    p.add_layout(
        Span(location=2,
             dimension='height',
             line_color='orange',
             line_dash='dashed',
             line_width=4))
    p.add_layout(
        Span(location=-2,
             dimension='height',
             line_color='orange',
             line_dash='dashed',
             line_width=4))
    p.add_layout(
        Span(location=3,
             dimension='height',
             line_color='red',
             line_dash='dashed',
             line_width=4))
    p.add_layout(
        Span(location=-3,
             dimension='height',
             line_color='red',
             line_dash='dashed',
             line_width=4))
    p.add_layout(
        Span(location=4,
             dimension='height',
             line_color='darkred',
             line_dash='dashed',
             line_width=4))
    p.add_layout(
        Span(location=-4,
             dimension='height',
             line_color='darkred',
             line_dash='dashed',
             line_width=4))
    p.add_layout(
        BoxAnnotation(top=(count - 3) / 3 + 1,
                      fill_alpha=0.1,
                      fill_color='black'))
    p.add_layout(
        BoxAnnotation(bottom=(count - 3) / 3 + 1,
                      top=(count - 3) / 3 * 2 + 2,
                      fill_alpha=0.1,
                      fill_color='cyan'))
    p.add_layout(BoxAnnotation(top=count, fill_alpha=0.1, fill_color='yellow'))
    return p