예제 #1
0
def get_bokeh_fig():
    from bokeh.plotting import Figure  # , gridplot
    from bokeh.models import ColumnDataSource, HoverTool
    results, varied_keys, varied_vals = read()
    include_keys = varied_keys + [
        'nfev', 'njev',  'nprec_setup', 'nprec_solve', 'njacvec_dot',
        'nprec_solve_ilu', 'nprec_solve_lu', "n_steps", "n_rhs_evals",
        "n_lin_solv_setups", "n_err_test_fails", "n_nonlin_solv_iters",
        "n_nonlin_solv_conv_fails", "krylov_n_lin_iters",
        "krylov_n_prec_evals", "krylov_n_prec_solves", "krylov_n_conv_fails",
        "krylov_n_jac_times_evals", "krylov_n_iter_rhs"
    ]
    cols = [xkey, ykey, 'color'] + include_keys
    sources = {}
    varied3 = varied_vals[2]
    keys = list(results.keys())
    vals = list(results.values())
    for val in varied3:
        sources[val] = ColumnDataSource(data={k: [] for k in cols})
        for k in cols:
            sources[val].data[k] = [vals[idx].get(k, None) for idx in
                                    range(len(vals)) if keys[idx][2] == val]
    hover = HoverTool(tooltips=[(k, '@'+k) for k in include_keys])
    top = Figure(
        plot_height=600, plot_width=800, title="%s vs. %s" % (ykey, xkey),
        x_axis_type="linear", y_axis_type="log", tools=[
            hover, 'pan', 'reset', 'box_zoom', 'wheel_zoom', 'save'])
    top.xaxis.axis_label = xkey
    top.yaxis.axis_label = ykey
    for source, marker in zip(sources.values(), ['circle', 'diamond']):
        top.scatter(x=xkey, y=ykey, source=source, size=9, color="color",
                    line_color=None, marker=marker)
    return top
예제 #2
0
def make_tab(title, marker, webgl):
    p = Figure(title=title, webgl=webgl)
    p.scatter(flowers["petal_length"],
              flowers["petal_width"],
              color='blue',
              fill_alpha=0.2,
              size=12,
              marker=marker)
    return Panel(child=p, title=title)
예제 #3
0
 def makeplot():
     p = Figure(plot_width=800, plot_height=200,tools="hover,pan",title=None)
     p.scatter(x, y, radius=radii,
            fill_color=colors, fill_alpha=0.6,
            line_color='gray', source=source)
     hover = p.select(dict(type=HoverTool))
     hover.tooltips = OrderedDict([
         ("radius", "@radius")])
     p.xgrid.grid_line_color = None
     p.ygrid.grid_line_color = None
     return p
예제 #4
0
파일: plot.py 프로젝트: Ritbit1111/ee770
def plot_iv():
    print("inside")
    source = ColumnDataSource(data=iv_data(35, 6, 0.34, 20000, 100))

    plot = Figure(plot_width=600,
                  plot_height=600,
                  y_range=(-1, 10),
                  x_range=(0, 60))
    plot.xaxis.axis_label = 'Voltage (V)'
    plot.yaxis.axis_label = 'Current (I)'
    plot.scatter('x', 'y', source=source, line_width=3, line_alpha=0.6)

    isc_slider = Slider(start=4, end=10, value=6, step=0.1, title='I_sc')
    voc_slider = Slider(start=10, end=50, value=35, step=1, title='V_oc')
    rs_slider = Slider(start=0.01, end=5, value=0.34, step=0.5, title='R_s')
    rsh_slider = Slider(start=10, end=1000, value=100, step=10, title='R_sh')
    n_slider = Slider(start=25,
                      end=5000,
                      value=100,
                      step=5,
                      title='Data Points')
    download_button = Button(label='Download data as csv', width=100)

    def get_slider_val():
        return (voc_slider.value, isc_slider.value, rs_slider.value,
                rsh_slider.value, n_slider.value)

    def update_plot(attrname, old, new):
        V, I, Rs, Rsh, N = get_slider_val()
        source.data = iv_data(V, I, Rs, Rsh, N)

    def download():
        print("Not working for now")

    isc_slider.on_change('value', update_plot)
    voc_slider.on_change('value', update_plot)
    rs_slider.on_change('value', update_plot)
    rsh_slider.on_change('value', update_plot)
    n_slider.on_change('value', update_plot)
    download_button.on_click(download)
    #

    layout = row(
        plot,
        column(isc_slider, voc_slider, rs_slider, rsh_slider, n_slider,
               download_button),
    )
    return (layout)
예제 #5
0
def render_scatter(
    itmdt: Intermediate, plot_width: int, plot_height: int, palette: Sequence[str]
) -> Figure:
    """
    Render scatter plot with a regression line and possible most influencial points
    """

    # pylint: disable=too-many-locals

    df = itmdt["data"]
    xcol, ycol, *maybe_label = df.columns

    tooltips = [(xcol, f"@{{{xcol}}}"), (ycol, f"@{{{ycol}}}")]

    fig = Figure(
        plot_width=plot_width,
        plot_height=plot_height,
        toolbar_location=None,
        title=Title(text="Scatter Plot & Regression Line", align="center"),
        tools=[],
        x_axis_label=xcol,
        y_axis_label=ycol,
    )

    # Scatter
    scatter = fig.scatter(x=df.columns[0], y=df.columns[1], source=df)
    if maybe_label:
        assert len(maybe_label) == 1
        mapper = CategoricalColorMapper(factors=["=", "+", "-"], palette=palette)
        scatter.glyph.fill_color = {"field": maybe_label[0], "transform": mapper}
        scatter.glyph.line_color = {"field": maybe_label[0], "transform": mapper}

    # Regression line
    coeff_a, coeff_b = itmdt["coeffs"]
    line_x = np.asarray([df.iloc[:, 0].min(), df.iloc[:, 0].max()])
    line_y = coeff_a * line_x + coeff_b
    fig.line(x=line_x, y=line_y, line_width=3)
    # Not adding the tooltips before because we only want to apply tooltip to the scatter
    hover = HoverTool(tooltips=tooltips, renderers=[scatter])
    fig.add_tools(hover)

    # Add legends
    if maybe_label:
        nidx = df.index[df[maybe_label[0]] == "-"][0]
        pidx = df.index[df[maybe_label[0]] == "+"][0]

        legend = Legend(
            items=[
                LegendItem(label="Most Influential (-)", renderers=[scatter], index=nidx),
                LegendItem(label="Most Influential (+)", renderers=[scatter], index=pidx),
            ],
            margin=0,
            padding=0,
        )

        fig.add_layout(legend, place="right")
    return fig
예제 #6
0
    def make_plot(source, title):
        plot = Figure(plot_width=800,
                      plot_height=600,
                      tools="",
                      toolbar_location=None)
        plot.title.text = title
        colors = Blues4[0:3]

        plot.scatter(x=x, y=y, source=source)
        plot.multi_line('ci_x', 'ci', source=source)

        # fixed attributes
        plot.xaxis.axis_label = xlabel
        plot.yaxis.axis_label = ylabel
        plot.axis.major_label_text_font_size = "8pt"
        plot.axis.axis_label_text_font_size = "8pt"
        plot.axis.axis_label_text_font_style = "bold"

        return plot
예제 #7
0
def setup_chosen(fpath):
    try:
        df = pd.DataFrame.from_csv(fpath)
    except Exception as exc:
        msg = str(exc)
        MessageBox.text = msg
    dfcols = list(df.columns)

    ChosenSource = ColumnDataSource()
    ChosenSource.data = bu.column_data_source_data_from_df(df)
    ChosenSource.name = "ChosenSource"
    ChosenTable = bu.data_table(source=ChosenSource,
                                               columns=dfcols,
                                               width=800)
    ChosenTable.name = "ChosenTable"

    metadf = bu.df_summary(df)
    MetaSource = ColumnDataSource()
    MetaSource.name = "MetaSource"
    MetaSource.data = bu.column_data_source_data_from_df(metadf)
    MetaTable = bu.data_table(source=MetaSource,
                               columns=list(metadf.columns),
                                       width=600)
    MetaTable.name = "MetaTable"

    RowFilter.value = ("# enter row filter conditions here")
    ScatterPlotX = Select(options = dfcols,
                          value=dfcols[0])
    ScatterPlotX.name = 'ScatterPlotX'
    ScatterPlotY = Select(options = dfcols,
                          value=dfcols[-1])
    ScatterPlotY.name = 'ScatterPlotY'
    ScatterSource = ColumnDataSource()
    ScatterSource.name = 'ScatterSource'
    ScatterSource.data = dict(X=ChosenSource.data[ScatterPlotX.value],
                              Y=ChosenSource.data[ScatterPlotY.value])
    ScatterPlot = Figure(height=500, width=600)
    res = ScatterPlot.scatter(x='X',
                         y='Y',
                         source=ScatterSource)
    res.name = "srender"
    ScatterPlot.name = 'ScatterPlot'

    layout= column(MessageBox, CloseButton,
                RowFilter,
                ColumnChooser,
                column(bu.child_in_widgetbox(MetaTable),
                    bu.child_in_widgetbox(ChosenTable)),
                row(ScatterPlotX, ScatterPlotY, MakeScatterPlot),
                ScatterPlot,)
    MakeScatterPlot.on_click(functools.partial(make_scatter, dom=layout))
    currentstate = bio.curstate()

    return layout
예제 #8
0
def add_to_arima_plot(
        figure: Figure,
        order,
        values,
        legend: str,
        color: str
):
    year = 0.01 * order.values
    delta = len(order) - len(values)
    figure.line(year[delta:], values, legend=legend, color=color)
    return figure.scatter(year[delta:], values, legend=legend, color=color)
def make_correlation_figure(correlation_values, title):
    """
    Creates a correlation function plot with confidence intervals for
    determining the ARIMA ordering

    :param correlation_values:
        The computed correlation function values
    :param title:
        Tile for the plot
    :return:
        A Bokeh figure populated with traces for the correlation function
        display
    """

    count = len(correlation_values)

    figure = Figure(title=title)
    figure.line(x=[0, count], y=-1.96/np.sqrt(len(temperatures)), color='black')
    figure.line(x=[0, count], y=1.96/np.sqrt(len(temperatures)), color='black')
    figure.line(x=list(range(count)), y=correlation_values)
    figure.scatter(x=list(range(count)), y=correlation_values, size=6)

    return figure
예제 #10
0
파일: clustering.py 프로젝트: 0-T-0/bokeh
affinity = cluster.AffinityPropagation(damping=.9, preference=-200)

# change here, to select clustering algorithm (note: spectral is slow)
algorithm = dbscan  # <- SELECT ALG

plots =[]
for dataset in (noisy_circles, noisy_moons, blobs1, blobs2):
    X, y = dataset
    X = StandardScaler().fit_transform(X)

    # predict cluster memberships
    algorithm.fit(X)
    if hasattr(algorithm, 'labels_'):
        y_pred = algorithm.labels_.astype(np.int)
    else:
        y_pred = algorithm.predict(X)

    p = Figure(webgl=True, title=algorithm.__class__.__name__,
               plot_width=PLOT_SIZE, plot_height=PLOT_SIZE)

    p.scatter(X[:, 0], X[:, 1], color=colors[y_pred].tolist(), alpha=0.1,)

    plots.append(p)

# generate layout for the plots
layout = vplot(hplot(*plots[:2]), hplot(*plots[2:]))

output_file("clustering.html", title="clustering with sklearn")

show(layout)
예제 #11
0

# create the scatter plot
TOOLS="pan,wheel_zoom,reset"

p = Figure(tools=TOOLS, plot_width=500, plot_height=500, min_border=10, min_border_left=50,
           title="Inputted Data",
           toolbar_location="above",
           active_scroll='wheel_zoom', 
           active_drag = "pan",
           x_axis_label = "x",
           y_axis_label = "y"
           )
p.background_fill_color = "#fafafa"

r = p.scatter(source = srcData, x='x', y='y', size=10, color="blue", alpha=0.6)

#y error bars:
p.add_layout(
        Whisker(source = srcData, base="x", upper="err_y_up", lower="err_y_down")
    )

#x error bars:
p.add_layout(
        Whisker(source = srcData, base="y", upper="err_x_up", lower="err_x_down", dimension="width")
    )

#JS callbacks

callbackPlot = CustomJS(args=dict(srcData=srcData, p=p, xaxis=p.xaxis[0], yaxis=p.yaxis[0]), code="""
    p.reset.emit();
예제 #12
0
class ScatterBokeh(Plot):
    def __init__(self,
                 plot_title: str,
                 number_of_objectives: int,
                 ws_url: str = 'localhost:5006'):
        super(ScatterBokeh, self).__init__(plot_title, number_of_objectives)

        if self.number_of_objectives == 2:
            self.source = ColumnDataSource(data=dict(x=[], y=[], str=[]))
        elif self.number_of_objectives == 3:
            self.source = ColumnDataSource(data=dict(x=[], y=[], z=[], str=[]))
        else:
            raise Exception(
                'Wrong number of objectives: {0}'.format(number_of_objectives))

        self.client = ClientSession(websocket_url='ws://{0}/ws'.format(ws_url))
        self.doc = curdoc()
        self.doc.title = plot_title
        self.figure_xy = None
        self.figure_xz = None
        self.figure_yz = None

        self.__initialize()

    def __initialize(self) -> None:
        """ Set-up tools for plot. """
        code = '''
            selected = source.selected['1d']['indices'][0]
            var str = source.front.str[selected]
            alert(str)
        '''

        callback = CustomJS(args=dict(source=self.source), code=code)
        self.plot_tools = [
            TapTool(callback=callback),
            WheelZoomTool(), 'save', 'pan',
            HoverTool(tooltips=[('index', '$index'), ('(x,y)', '($x, $y)')])
        ]

    def plot(self,
             front: List[S],
             reference: List[S] = None,
             output: str = '',
             show: bool = True) -> None:
        # This is important to purge front (if any) between calls
        reset_output()

        # Set up figure
        self.figure_xy = Figure(output_backend='webgl',
                                sizing_mode='scale_width',
                                title=self.plot_title,
                                tools=self.plot_tools)
        self.figure_xy.scatter(x='x',
                               y='y',
                               legend='solution',
                               fill_alpha=0.7,
                               source=self.source)
        self.figure_xy.xaxis.axis_label = self.xaxis_label
        self.figure_xy.yaxis.axis_label = self.yaxis_label

        x_values, y_values, z_values = self.get_objectives(front)

        if self.number_of_objectives == 2:
            # Plot reference solution list (if any)
            if reference:
                ref_x_values, ref_y_values, _ = self.get_objectives(reference)
                self.figure_xy.line(x=ref_x_values,
                                    y=ref_y_values,
                                    legend='reference',
                                    color='green')

            # Push front to server
            self.source.stream({
                'x': x_values,
                'y': y_values,
                'str': [s.__str__() for s in front]
            })
            self.doc.add_root(column(self.figure_xy))
        else:
            # Add new figures for each axis
            self.figure_xz = Figure(title='xz',
                                    output_backend='webgl',
                                    sizing_mode='scale_width',
                                    tools=self.plot_tools)
            self.figure_xz.scatter(x='x',
                                   y='z',
                                   legend='solution',
                                   fill_alpha=0.7,
                                   source=self.source)
            self.figure_xz.xaxis.axis_label = self.xaxis_label
            self.figure_xz.yaxis.axis_label = self.zaxis_label

            self.figure_yz = Figure(title='yz',
                                    output_backend='webgl',
                                    sizing_mode='scale_width',
                                    tools=self.plot_tools)
            self.figure_yz.scatter(x='y',
                                   y='z',
                                   legend='solution',
                                   fill_alpha=0.7,
                                   source=self.source)
            self.figure_yz.xaxis.axis_label = self.yaxis_label
            self.figure_yz.yaxis.axis_label = self.zaxis_label

            # Plot reference solution list (if any)
            if reference:
                ref_x_values, ref_y_values, ref_z_values = self.get_objectives(
                    reference)
                self.figure_xy.line(x=ref_x_values,
                                    y=ref_y_values,
                                    legend='reference',
                                    color='green')
                self.figure_xz.line(x=ref_x_values,
                                    y=ref_z_values,
                                    legend='reference',
                                    color='green')
                self.figure_yz.line(x=ref_y_values,
                                    y=ref_z_values,
                                    legend='reference',
                                    color='green')

            # Push front to server
            self.source.stream({
                'x': x_values,
                'y': y_values,
                'z': z_values,
                'str': [s.__str__() for s in front]
            })
            self.doc.add_root(
                row(self.figure_xy, self.figure_xz, self.figure_yz))

        self.client.push(self.doc)

        if output:
            self.__save(output)
        if show:
            self.client.show()

    def update(self,
               front: List[S],
               reference: List[S],
               new_title: str = '',
               persistence: bool = False) -> None:
        # Check if plot has not been initialized first
        if self.figure_xy is None:
            self.plot(front, reference)

        if not persistence:
            rollover = len(front)
        else:
            rollover = None

        self.figure_xy.title.text = new_title
        x_values, y_values, z_values = self.get_objectives(front)

        if self.number_of_objectives == 2:
            self.source.stream(
                {
                    'x': x_values,
                    'y': y_values,
                    'str': [s.__str__() for s in front]
                },
                rollover=rollover)
        else:
            self.source.stream(
                {
                    'x': x_values,
                    'y': y_values,
                    'z': z_values,
                    'str': [s.__str__() for s in front]
                },
                rollover=rollover)

    def __save(self, file_name: str):
        # env = Environment(loader=FileSystemLoader(BASE_PATH + '/util/'))
        # env.filters['json'] = lambda obj: Markup(json.dumps(obj))

        html = file_html(models=self.doc, resources=CDN)
        with open(file_name + '.html', 'w') as of:
            of.write(html)

    def disconnect(self):
        if self.is_connected():
            self.client.close()

    def is_connected(self) -> bool:
        return self.client.connected
import numpy as np

from bokeh.io import show
from bokeh.layouts import column, row
from bokeh.models import ColumnDataSource, CustomJS, Spinner
from bokeh.plotting import Figure

data = np.random.rand(10, 2)
cds = ColumnDataSource(data=dict(x=data[:, 0], y=data[:, 1]))

p = Figure(x_range=(0, 1), y_range=(0, 1))
points = p.scatter(x='x', y='y', source=cds)

w = Spinner(title="Glyph size", low=1, high=20, step=0.1, value=4, width=100)
cb = CustomJS(args={'points': points},
              code="""
points.glyph.size = cb_obj.value
""")
points.glyph.size = w.value

w.js_on_change('value', cb)

show(row(column(w, width=100), p))
예제 #14
0
    def get_graph(self):

        data = self.get_data()

        slider = Slider(start=0.8,
                        end=1.2,
                        value=1,
                        step=.001,
                        title="Power",
                        bar_color='red')

        if self.type[:3] == 'GEN':
            x = [datetime.date(data.index[k]) for k in range(data.shape[0])]
            y1 = data.iloc[:, 0]
            y2 = data.iloc[:, 1]
            source = ColumnDataSource(data=dict(x=x, y1=y1, y2=y2))
            graph = figure(tools=TOOLS,
                           title=self.type,
                           x_axis_type='datetime',
                           x_axis_label='date',
                           y_axis_label="el. usage ",
                           plot_height=200,
                           y_range=(
                               0,
                               4000,
                           ))
            graph.line('x',
                       'y1',
                       source=source,
                       legend="Outdoor temperature",
                       color='orange',
                       alpha=0.5,
                       y_range_name="temperature",
                       line_width=1)
            graph.line('x',
                       'y2',
                       source=source,
                       legend="Electricity usage",
                       hover_line_color="red",
                       alpha=0.5,
                       line_width=1).hover_glyph.line_width = 2

            graph.extra_y_ranges = {"temperature": Range1d(start=0, end=100)}
            graph.add_layout(
                LinearAxis(y_range_name="temperature",
                           axis_label='temperature'), 'right')

            graph.add_tools(
                HoverTool(tooltips=[
                    ("y", "$y{0}"),
                    ("date", '@x{%F}'),
                ],
                          formatters={'x': 'datetime'}))
            callback = CustomJS(args=dict(source=source,
                                          y1_base=y1,
                                          y2_base=y2,
                                          slider=slider),
                                code=CALLBACK_2)

        if self.type[:13] == 'C_EL_U/O_TEMP':
            x = data.iloc[:, 0]
            y = data.iloc[:, 1]
            source = ColumnDataSource(data=dict(x=x, y=y))
            graph = Figure(tools=TOOLS,
                           title=self.type,
                           y_axis_label='Electricity usage',
                           x_axis_label="Outside temperature",
                           plot_height=200,
                           y_range=(0, 4000))

            graph.add_tools(
                HoverTool(tooltips=[
                    ("El. usage", "$y{0}"),
                    ("Out. temp.", "$x"),
                ]))
            graph.scatter(
                'x',
                'y',
                source=source,
                legend="Graph electricity usage vs. outdoor temperature",
                alpha=0.5,
                size=10)
            callback = CustomJS(args=dict(source=source,
                                          y_base=y,
                                          slider=slider),
                                code=CALLBACK_1)

        if self.type[:6] == 'O_TEMP':
            x = [datetime.date(data.index[k]) for k in range(data.shape[0])]
            y = data
            source = ColumnDataSource(data=dict(x=x, y=y))
            graph = Figure(tools=TOOLS,
                           title=self.type,
                           x_axis_type='datetime',
                           x_axis_label='date',
                           y_axis_label="Outside temperature",
                           plot_height=200,
                           y_range=(0, 100))
            graph.line('x',
                       'y',
                       source=source,
                       legend="Graph of outdoor temperature vs. time",
                       line_width=1,
                       alpha=0.5,
                       hover_line_color="red").hover_glyph.line_width = 2

            graph.add_tools(
                HoverTool(tooltips=[
                    ("Out. temp", "$y{0}"),
                    ("date", '@x{%F}'),
                ],
                          formatters={'x': 'datetime'}))
            callback = CustomJS(args=dict(source=source,
                                          y_base=y,
                                          slider=slider),
                                code=CALLBACK_1)

        if self.type[:4] == 'EL_U':
            x = [datetime.date(data.index[k]) for k in range(data.shape[0])]
            y = data
            source = ColumnDataSource(data=dict(x=x, y=y))
            graph = Figure(tools=TOOLS,
                           title=self.type,
                           x_axis_type='datetime',
                           x_axis_label='date',
                           y_axis_label="Electricity usage",
                           plot_height=200,
                           y_range=(0, 4000))
            graph.line(
                'x',
                'y',
                source=source,
                legend="Graph electricity usage vs. time",
                line_width=1,
                hover_line_color="red",
                alpha=0.5,
            ).hover_glyph.line_width = 2
            graph.add_tools(
                HoverTool(tooltips=[
                    ("El. usage", "$y{0}"),
                    ("date", '@x{%F}'),
                ],
                          formatters={'x': 'datetime'}))
            callback = CustomJS(args=dict(source=source,
                                          y_base=y,
                                          slider=slider),
                                code=CALLBACK_1)
        else:
            pass

        slider.js_on_change('value', callback)
        layout = column(slider, graph, sizing_mode="scale_width")
        script, div = components(layout)

        return script, div
df = pd.DataFrame([to_width_length(r) for _, r in df_tracks.iterrows()])

for key in create().keys():
    df_out = df_out.drop([key], axis=1, errors='ignore')

df_out = pd.merge(left=df_out, right=df, how='inner', on='uid')
figure = Figure(
    title='Track Lengths and Widths',
    x_axis_label='Track Length (m)',
    y_axis_label='Track Width (m)'
)

figure.scatter(
    df_out[csv_columns[23].name].fillna(df_out[csv_columns[24].name]),
    df_out[csv_columns[25].name].fillna(df_out[csv_columns[26].name]),
    color='blue',
    legend='Pes'
)

figure.scatter(
    df_out[csv_columns[33].name].fillna(df_out[csv_columns[34].name]),
    df_out[csv_columns[35].name].fillna(df_out[csv_columns[36].name]),
    color='red',
    legend='Manus'
)


cd.display.markdown(
    """
    # Track Width and Length
예제 #16
0
# dropdown menu for selecting one of the sample curves
sample_curve_input = Dropdown(label="choose a sample function pair or enter one below",
                              menu=leibnitz_settings.sample_curve_names)
sample_curve_input.on_click(sample_curve_change)

# initialize plot
toolset = "crosshair,pan,reset,resize,save,wheel_zoom"
# Generate a figure container
plot = Figure(plot_height=400, plot_width=400, tools=toolset,
              title="Leibnitz sector formula",
              x_range=[leibnitz_settings.x_min_view, leibnitz_settings.x_max_view],
              y_range=[leibnitz_settings.y_min_view, leibnitz_settings.y_max_view])

# Plot the line by the x,y values in the source property
plot.line('x', 'y', source=source_curve, line_width=3, line_alpha=1, color='black', legend='curve')
plot.scatter('x', 'y', source=source_point, color='blue', legend='point at t')
plot.scatter([0], [0], color='black', marker='x')
pat = plot.patch('x', 'y', source=source_sector, fill_color='blue', fill_alpha=.2, legend='area')
plot.line('x_start', 'y_start', source=source_lines, line_width=1, line_alpha=1, color='blue')
plot.line('x_end', 'y_end', source=source_lines, line_width=1, line_alpha=1, color='blue')
plot.text('x', 'y', text='text', text_color='text_color', source=source_text)

# calculate data
update_curve()
update_point()

# lists all the controls in our app
controls = widgetbox(t_value_input, sample_curve_input, x_component_input, y_component_input)

# make layout
curdoc().add_root(row(plot, controls))
예제 #17
0
# Extract column names
column_names = red_wine.columns
features = column_names[0:-1].tolist()
print(features)

# Select a column for x-axis and y-axis
x_feature = Select(title='Select feature for x-axis', value=features[0], options=features)
y_feature = Select(title='Select feature for y-axis', value=features[0], options=features)
threshold = Select(title='Threshold (stdev from mean):', value='10',
                   options=['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'])

# Set up plot
source = ColumnDataSource(data=dict(x=[], y=[]))

plot = Figure(plot_width=400, plot_height=400, title='Outliers')
plot.scatter(x='x', y='y', source=source)


# Define outlier function
def outliers(df, threshold):

    column_names = df.columns

    mean_list = df.mean(axis=0).tolist()

    i = 0
    for col in column_names:
        mask = abs(df.loc[:,col] - df.loc[:,col].mean()) > \
               threshold*df.loc[:,col].std()
        # print(mask.index)
        df.loc[mask, col] = mean_list[i]
예제 #18
0
파일: trial3.py 프로젝트: BrownDwarf/kinder
source = ColumnDataSource(data=dict(x=x0, y=y0))
source2 = ColumnDataSource(data=dict(x=xlc, y=ylc))


# Set up plot
plot = Figure(tools="crosshair,pan,reset,resize,save,wheel_zoom",
              plot_width=400, plot_height=400, title=None,
              x_range=[-4, 0], y_range=[-4, 0])

plot2 = Figure(tools="crosshair,pan,reset,resize,save,wheel_zoom",
               plot_width=400, plot_height=400, title=None,
              x_range=[2063, 2102], y_range=[0.90, 1.10])


plot.scatter(xx, yy, size=3, color="#3A5785", alpha=0.1)
plot.scatter('x', 'y', source=source, size=15, color="#FF0000", alpha=1.0)

plot2.line('x', 'y', source=source2, line_width=3, line_alpha=0.6)

# Set up widgets
offset = Slider(title="offset", value=0, start=0, end=1677, step=1)

#layout = hplot(plot, plot2, width=800, height=500)


def update_data(attrname, old, new):

    # Get the current slider values
    b = offset.value
예제 #19
0
from astropy.table import Table
abund=Table.read('/Users/kschles/Documents/GALAH/wg4output/wg4_04292016/sobject_iraf_k2.fits', format='fits')
abund=Table.to_pandas(abund)

source = ColumnDataSource(data=dict(x=abund.loc[0:100,'feh_cannon'], y=abund.loc[0:100,'alpha_fe_cannon'], sobject_id=abund.loc[0:100,'sobject_id']))
data=dict(x=abund.loc[0:100,'feh_cannon'], y=abund.loc[0:100,'alpha_fe_cannon'], sobject_id=abund.loc[0:100,'sobject_id'])

# Set up plot
#plot = Figure(plot_height=400, plot_width=400, title="My Abundance Plot",
#              tools="crosshair,pan,reset,resize,save,box_zoom")
TOOLS= [BoxZoomTool(), ResetTool(), ResizeTool(), PreviewSaveTool(), PanTool(), HoverTool(tooltips=[("sobject_id","@sobject_id")])]
plot = Figure(plot_height=400, plot_width=400, title="My Abundance Plot",tools=TOOLS)
plot.xaxis.axis_label = "[Fe/H]"
plot.yaxis.axis_label = "[a/Fe]"

plot.scatter('x', 'y', source=source, color='black')

# create the horizontal histogram
x1 = np.random.normal(loc=5.0, size=400) * 100
hhist, hedges = np.histogram(np.array(data['x']).astype(float), bins=20)
hzeros = np.zeros(len(hedges)-1)
hmax = max(hhist)*1.1

LINE_ARGS = dict(color="#3A5785", line_color=None)

ph = Figure(toolbar_location=None, plot_width=plot.plot_width, plot_height=200, x_range=plot.x_range,
            y_range=(-hmax, hmax), title=None, min_border=10, min_border_left=50)
ph.xgrid.grid_line_color = None

ph.quad(bottom=0, left=hedges[:-1], right=hedges[1:], top=hhist, color="white", line_color="#3A5785")
hh1 = ph.quad(bottom=0, left=hedges[:-1], right=hedges[1:], top=hzeros, alpha=0.5, **LINE_ARGS)
예제 #20
0
"""
Created on Mon May  2 10:43:23 2016

@author: rpjai
"""

from bokeh.io import curdoc
from bokeh.plotting import Figure, output_file, show, ColumnDataSource
# from bokeh.models import HBox
from bokeh.models.widgets import Slider, Select
from bokeh.sampledata.autompg import autompg as am

auto_src = ColumnDataSource(data=dict(xs=am.mpg, ys=am.hp))

p1 = Figure(plot_width=400, plot_height=400)
p1.scatter('xs', 'ys', source=auto_src)

x_select = Select(title="", options=['mpg', 'weight', 'accel'], value="accel")
y_select = Select(title="", options=['mpg', 'weight', 'accel'], value="mpg")

def update_plot(attrname, old, new):
    new_x, new_y = x_select.value, y_select.value
    pass

# 1. ColumnDataSource(x, y)
# 2. Create scatter ()
# 3. x, y Select widgets.
# 4. Update function.

#
# my_slider = Slider(start=0, end=100, step=1, value=50, title="Circle Radius")
예제 #21
0
                             y_axis_label='Current (A)')

#Define data you wanna plot
source_data = ColumnDataSource(
    data=dict(x=IV_data['Voltage'], y=IV_data['Current']))
source_data_log = ColumnDataSource(
    data=dict(x=IV_data['Voltage'], y=IV_data['Abs_Current']))
source_fit_by_eye = ColumnDataSource(
    data=dict(x=IV_data['Voltage'], y=IV_data['Current_fit']))
source_fit_by_eye_log = ColumnDataSource(
    data=dict(x=IV_data['Voltage'], y=IV_data['Abs_Current_fit']))

#Perform actual plotting
plot_fit_by_eye.scatter('x',
                        'y',
                        source=source_data,
                        legend='Measured Data',
                        color='blue')
plot_fit_by_eye_log.scatter('x',
                            'y',
                            source=source_data_log,
                            legend='Measured Data',
                            color='blue')
plot_fit_by_eye.line('x',
                     'y',
                     source=source_fit_by_eye,
                     line_width=3,
                     legend='Fit',
                     color='black')
plot_fit_by_eye_log.line('x',
                         'y',
예제 #22
0
function1_input.on_change('value', input_change)
# text input for the second function to be convolved
function2_input = TextInput(value=convolution_settings.function1_input_init, title="my second function:")
function2_input.on_change('value', input_change)

# initialize plot
toolset = "crosshair,pan,reset,resize,save,wheel_zoom"
# Generate a figure container
plot = Figure(plot_height=400, plot_width=400, tools=toolset,
              title="Convolution of two functions",
              x_range=[convolution_settings.x_min_view, convolution_settings.x_max_view],
              y_range=[convolution_settings.y_min_view, convolution_settings.y_max_view])

# Plot the line by the x,y values in the source property
plot.line('x', 'y', source=source_function1, line_width=3, line_alpha=0.6, color='red', legend='function 1')
plot.line('x', 'y', source=source_function2, color='green', line_width=3, line_alpha=0.6, legend='function 2')
plot.line('x', 'y', source=source_result, color='blue', line_width=3, line_alpha=0.6, legend='convolution')
plot.scatter('x', 'y', source=source_xmarker, color='black')
plot.line('x', 'y', source=source_xmarker, color='black', line_width=3)
plot.patch('x', 'y_pos', source=source_overlay, fill_color='blue', fill_alpha=.2)
plot.patch('x', 'y_neg', source=source_overlay, fill_color='red', fill_alpha=.2)

# calculate data
update_data()

# lists all the controls in our app
controls = widgetbox(x_value_input, function_type, function1_input, function2_input, width=400)

# make layout
curdoc().add_root(row(plot, controls, width=800))
          legend_label='function 1')
plot.line('x',
          'y',
          source=source_function2,
          color='green',
          line_width=3,
          line_alpha=0.6,
          legend_label='function 2')
plot.line('x',
          'y',
          source=source_result,
          color='blue',
          line_width=3,
          line_alpha=0.6,
          legend_label='convolution')
plot.scatter('x', 'y', source=source_xmarker, color='black')
plot.line('x', 'y', source=source_xmarker, color='black', line_width=3)
plot.patch('x',
           'y_pos',
           source=source_overlay,
           fill_color='blue',
           fill_alpha=.2)
plot.patch('x',
           'y_neg',
           source=source_overlay,
           fill_color='red',
           fill_alpha=.2)

# calculate data
update_data()
예제 #24
0
TOOLS = "pan,wheel_zoom,reset"

p = Figure(tools=TOOLS,
           plot_width=600,
           plot_height=600,
           min_border=10,
           min_border_left=50,
           title="Fitted Model",
           toolbar_location="above",
           active_scroll='wheel_zoom',
           active_drag="pan",
           x_axis_label="x",
           y_axis_label="y")
p.background_fill_color = "#fafafa"

r = p.scatter(source=srcData, x='x', y='y', size=10, color="red", alpha=1.0)

#y error bars:
p.add_layout(
    Whisker(source=srcData, base="x", upper="err_y_up", lower="err_y_down"))

#x error bars:
p.add_layout(
    Whisker(source=srcData,
            base="y",
            upper="err_x_up",
            lower="err_x_down",
            dimension="width"))

#model plot
예제 #25
0

# initialize the plot data
update_source_data(True)

# make the plot responsive to slider changes
standard_deviation_slider.on_change(
    'value', lambda attr, old_value, new_value: update_source_data(True))
cutoff_slider.on_change(
    'value', lambda attr, old_value, new_value: update_source_data(False))

# create the figure

p = Figure(title='Normal Distribution')

p.scatter(source=source,
          x='x',
          y='y',
          color='green',
          alpha='alpha',
          radius=0.1)

p.x_range = Range1d(start=-8, end=8)
p.y_range = Range1d(start=-8, end=8)

content = column(standard_deviation_slider, cutoff_slider, p)

# register the figure

curdoc().add_root(content)
curdoc().title = 'Normal Distribution'
예제 #26
0
파일: plot.py 프로젝트: Ritbit1111/app_770
def plot_iv(doc):

    init_calc = iv.iv_data(72, 800, 25, 45.9, 9.25, 37.2, 8.76, 7.47, 100)
    source = ColumnDataSource(data=init_calc[0])
    source_translated = ColumnDataSource(data=init_calc[1])
    res_source = ColumnDataSource(data=init_calc[2])
    status_param = init_calc[3]
    print(status_param)

    plot = Figure(plot_width=600,
                  plot_height=600,
                  y_range=(-1, 10),
                  x_range=(0, 60))
    plot.xaxis.axis_label = 'Voltage (V)'
    plot.yaxis.axis_label = 'Current (I)'
    plot.scatter(
        'x',
        'y',
        source=source,
        line_width=3,
        line_alpha=0.6,
    )
    plot.scatter(
        'x',
        'y',
        source=source_translated,
        line_width=3,
        line_alpha=0.6,
        line_color='red',
    )

    sig_plot = Figure(plot_width=300,
                      plot_height=300,
                      x_axis_label='Series Resistance (Rs)',
                      y_axis_label='Shunt Resistance (Rsh)',
                      title='Calculated Resistances')
    sig_plot.scatter('x', 'y', source=res_source, line_width=10)
    vline = Span(location=0,
                 dimension='height',
                 line_color='red',
                 line_width=3)
    # Horizontal line
    hline = Span(location=0,
                 dimension='width',
                 line_color='green',
                 line_width=3)
    sig_plot.renderers.extend([vline, hline])

    error_plt = Figure(
        plot_width=100,
        plot_height=50,
        toolbar_location=None,
    )

    if (status_param.success == True):
        print('Successful Entry to the landing page')
        cite = Label(text='Success',
                     render_mode='css',
                     text_color='white',
                     border_line_color='green',
                     background_fill_color='green')
    else:
        print('Inside fail')
        cite = Label(text='False',
                     render_mode='css',
                     text_color='white',
                     border_line_color='red',
                     background_fill_color='red')
    error_plt.add_layout(cite)
    error_plt.add_layout(
        Label(text='Success',
              render_mode='css',
              text_color='white',
              border_line_color='green',
              background_fill_color='green'))

    Ncell_input = TextInput(value='72', title='No. of cells')
    Irrad_input = TextInput(value='800', title='Irradiance')
    Temp_input = TextInput(value='25', title='Temperature (Celcius)')
    Isc_input = TextInput(value='9.25', title='I_sc at STC')
    Im_input = TextInput(value='8.76', title='I_m')
    Voc_input = TextInput(value='45.9', title='V_oc')
    Vm_input = TextInput(value='37.2', title='V_m')
    Isc_N_input = TextInput(value='7.47', title='I_sc at NOTC(G=800, T=45C)')
    Data_input = TextInput(value='100', title='Data Size')
    submit = Button(label='Submit', button_type='success')
    download_button_STC = Button(label='Download data (STC)')
    download_button_GT = Button(label='Download data (Translated)')

    def get_inputs():
        return (float(Ncell_input.value), float(Irrad_input.value),
                float(Temp_input.value), float(Voc_input.value),
                float(Isc_input.value), float(Vm_input.value),
                float(Im_input.value), float(Isc_N_input.value),
                float(Data_input.value))

    def update_plot(event):
        N, G, T, V, I, Vm, Im, I_N, datapoints = get_inputs()
        print('#' * 30)
        print('Updating the plot')
        print('#' * 30)
        updated_data = iv.iv_data(N, G, T, V, I, Vm, Im, I_N, datapoints)
        source.data = updated_data[0]
        source_translated.data = updated_data[1]
        res_source.data = updated_data[2]
        global status_param
        status_param = updated_data[3]
        print(status_param)
        if (status_param.success == True):
            print('Inside success')
            cite = Label(text='Successful Parameter Extraction',
                         render_mode='css',
                         text_color='white',
                         border_line_color='green',
                         background_fill_color='green')
        else:
            print('Inside fail')
            cite = Label(text='Parameter extraction not converging',
                         render_mode='css',
                         text_color='white',
                         border_line_color='red',
                         background_fill_color='red')
        error_plt = Figure(
            plot_width=100,
            plot_height=50,
            toolbar_location=None,
        )

        error_plt.add_layout(cite)
        layout.children[2].children[1] = error_plt

    def update_success():
        if (status_param.success == True):
            print('Inside success')
            cite = Label(text='Success',
                         render_mode='css',
                         text_color='white',
                         border_line_color='green',
                         background_fill_color='green')
        else:
            print('Inside fail')
            cite = Label(text='False',
                         render_mode='css',
                         text_color='white',
                         border_line_color='red',
                         background_fill_color='red')
        error_plt = Figure(
            plot_width=100,
            plot_height=50,
            toolbar_location=None,
        )

        error_plt.add_layout(cite)
        layout.children[2].children[1] = error_plt

    submit.on_click(update_plot)
    download_button_STC.js_on_click(
        CustomJS(args=dict(source=source),
                 code=open(join(dirname(__file__), "download.js")).read()))
    download_button_GT.js_on_click(
        CustomJS(args=dict(source=source_translated),
                 code=open(join(dirname(__file__), "download.js")).read()))

    #doc.add_periodic_callback(update_success, 1000)

    layout = row(
        plot,
        column(Ncell_input, Irrad_input, Temp_input, Isc_input, Im_input,
               Voc_input, Vm_input, Isc_N_input, Data_input, submit,
               download_button_STC, download_button_GT),
        column(sig_plot, error_plt))
    return (layout)
예제 #27
0
    def plot_carto_single(self, data, frente, palette, path=FILE_OUT,
                          name_file="", low=0, high=100, show_plot=True):
        """

        :param data: df loaded by data_load
        :param frente: string, name of "partido" lowercase: diff, mas, cc, creemos, fpv, pan_bol
        :param palette: ej: P_GRAD_CC
        :param name_file: default:test
        :param low: cmap low limit: default: -80
        :param high: cmap high limit: defauilt: +80.
        :param path: file out
        :return: df
        """
        da_col = ['HAB','PAIS','MUN','REC','X','Y','LAT','LON','x','y',
                  'r','r2','GX','GY'
                  ]

        cart_init_val = self.CART_SLIDER_INIT  # add slider
        self.process_data(cart_init_val, data)


        if frente == "diff":
            low = self.C_BAR_LOW
            high = self.C_BAR_HIGH
            frente = "d_mas_cc"
            f1 = 'mas_o_cc'
            f2 = 'ad_mas_cc'
            _p = 'mas'
            _p1 = 'cc'
            da_col.append(frente)
            da_col.append(f1)
            da_col.append(f2)
            da_col.append(_p)
            da_col.append(_p1)
        if frente == "d_mas_creemos":
            low = self.C_BAR_LOW
            high = self.C_BAR_HIGH
            f1 = 'mas_o_creemos'
            f2 = 'ad_mas_creemos'
            da_col.append(frente)
            da_col.append(f1)
            da_col.append(f2)
            da_col.append('mas')
            da_col.append('creemos')

        da_col.append(frente)



        cm = linear_cmap(frente, palette=palette, low=low, high=high)



        data = data[da_col]
        source_master = ColumnDataSource(data)
        source_red_map = ColumnDataSource({'gx': [], 'gy': []})
        # la, lo = ebu.get_la_lo_bolivia()
        # source_bol = ColumnDataSource({'la': la, 'lo': lo})
        # source_red_car = ColumnDataSource({'lo': [], 'la': []})

        # JS CODE
        code_draw_red_map = """
        const data = {'gx': [], 'gy': []}
        const indices = cb_data.index.indices
        for (var i = 0; i < indices.length; i++ ) {
                data['gx'].push(source_master.data.GX[indices[i]])
                data['gy'].push(source_master.data.GY[indices[i]])
        }
        source_red_map.data = data
        """

        code_slider = """
            var data = source.data;
            var f = cb_obj.value
            var x = data['x']
            var y = data['y']
            var Y = data['Y']
            var X = data['X']
            var lat = data['LAT']
            var lon = data['LON']
            for (var i = 0; i < x.length; i++) {
                y[i] = (1-f)*lat[i] + f*Y[i]
                x[i] = (1-f)*lon[i] + f*X[i]
            }
            source.change.emit();
        """

        # FIGURES
        curr_time = ebu.get_bolivian_time(-3)

        pw = self.FIG_WIDTH

        callback_red_map = CustomJS(
            args={'source_master': source_master,
                  'source_red_map': source_red_map, },
            code=code_draw_red_map)

        hover_cart = bokeh.models.HoverTool(
            tooltips=self.TOOL_TIP_DIC[frente],
            callback=callback_red_map,
            # renderers = [red_scat_car]

        )

        cart_fig = Figure(plot_width=pw, plot_height=pw,
                          output_backend="webgl", )
        cart_fig.background_fill_color = "grey"
        cart_fig.background_fill_alpha = .5
        cart_fig.scatter('x', 'y', source=source_master, radius='r', color=cm)
        cart_fig.add_tools(hover_cart, )

        title = "Última actualización: " + curr_time["datetime_val"].strftime(
            "%Y-%m-%d %H:%M") + "BOT"


        map_fig = Figure(plot_width=pw, plot_height=pw,
                         x_axis_type='mercator',
                         y_axis_type='mercator',
                         output_backend="webgl",
                         title=title,
                         )

        # cb_fig = bokeh.plotting.Figure(plot_height=pw,plot_width=)
        # cb_fig.toolbar.logo = None
        # cb_fig.toolbar_location = None

        # SCATTER
        # noinspection PyUnresolvedReferences
        # add tiles
        tile_provider = bokeh.tile_providers.get_provider(
            bokeh.tile_providers.Vendors.CARTODBPOSITRON)
        map_fig.add_tile(tile_provider)

        # scatter in map
        map_fig.scatter(
            'GX', 'GY', source=source_master, size='r2',
            color=cm
        )

        # todo if we wont use map then we nee to delete the source
        # cart_fig.line('lo', 'la', source=source_bol, color='black')

        # noinspection PyUnusedLocal
        red_scat_map = map_fig.circle_cross('gx', 'gy',
                                            source=source_red_map,
                                            fill_color=None,
                                            size=20,
                                            line_color="white",
                                            line_width=4
                                            )

        # noinspection PyUnusedLocal
        red_scat_map = map_fig.circle_cross('gx', 'gy',
                                            source=source_red_map,
                                            fill_color=None,
                                            size=20,
                                            line_color="red",
                                            line_width=1
                                            )
        # red_scat_car = cart_fig.scatter('lo', 'la',
        # source=source_red_car, color='green')

        # add a hover tool that sets the link data for a hovered circle

        # callbacks

        # code = code_merged)

        # callback_red_car = CustomJS(
        # args={'source_master': source_master, 'source_red_car': source_red_car},
        # code=code_draw_red_car)

        # tools

        hover_map = bokeh.models.HoverTool(
            tooltips=self.TOOL_TIP_DIC[frente],
            # callback=callback_red_car,
            # renderers = [red_scat_map]
        )
        map_fig.add_tools(hover_map, )

        # slider
        callback_slider = CustomJS(args=dict(source=source_master),
                                   code=code_slider)

        slider = Slider(start=0, end=1, value=cart_init_val, step=.02,
                        title="carto")
        slider.js_on_change('value', callback_slider)

        # COLOR BAR
        ml = {int(i): str(np.abs(i)) for i in np.arange(-80, 81, 20)}
        cb = bokeh.models.ColorBar(
            color_mapper=cm['transform'],
            # width=int(.9 * 450),
            width='auto',
            location=(0, 0),
            #     title="DEN (N/km^2)",
            # title=(BAR_TITLE),
            # margin=0,padding=0,
            title_standoff=10,
            # ticker=bokeh.models.LogTicker(),
            orientation='horizontal',
            major_label_overrides=ml

        )

        cart_fig.add_layout(cb, 'above')
        # cb.title_text_align = 'left'
        cart_fig.title.text = self.BAR_TITLE_DIC[frente]
        cart_fig.title.align = 'center'

        # layout = row(column(slider, cart_f),map_f)
        layout = bokeh.layouts.gridplot(
            [[slider, None], [cart_fig, map_fig]], sizing_mode='scale_width',
            merge_tools=False)
        layout.max_width = 1400
        # layout = bokeh.layouts.column([slider, cart_fig])

        cart_fig.x_range.start = self.CXS
        cart_fig.x_range.end = self.CXE
        cart_fig.y_range.start = self.CYS
        cart_fig.y_range.end = self.CYE

        _ll = ebu.lola_to_cart(lo=[self.MXS, self.MXE], la=[self.MYS, self.MYE])
        map_fig.x_range.start = _ll[0][0]
        map_fig.x_range.end = _ll[0][1]
        map_fig.y_range.start = _ll[1][0]
        map_fig.y_range.end = _ll[1][1]

        cart_fig.xaxis.major_tick_line_color = None
        # turn off x-axis major ticks
        cart_fig.xaxis.minor_tick_line_color = None
        # turn off x-axis minor ticks
        cart_fig.yaxis.major_tick_line_color = None
        # turn off y-axis major ticks
        cart_fig.yaxis.minor_tick_line_color = None
        cart_fig.xaxis.major_label_text_font_size = '0pt'
        # turn off x-axis tick labels
        cart_fig.yaxis.major_label_text_font_size = '0pt'
        # turn off y-axis tick labels
        nam = 'z037_' + frente + '_' + name_file + '.html'
        nam_lat = 'z037_' + frente + '_' + 'latest' + '.html'
        nam1 = os.path.join(path, nam)

        nam2 = os.path.join(os.path.dirname(ebu.DIR), 'docs',
                            'graficas_htmls',
                            nam_lat)
        # bokeh.plotting.output_file(nam2)
        if show_plot:

            bokeh.plotting.show(layout)

        bokeh.plotting.save(layout, nam1)
        bokeh.plotting.save(layout, nam2)

        return data
예제 #28
0
    ''' The 'true' function we use to generate data'''
    return x+5*np.sin(x)

x_points = 200
x = np.linspace(0,20,x_points)
err = np.random.normal(size=x_points)

p = Figure(title="bagging demo", plot_height=400, plot_width=800, y_range=(-5,30))

slider_degrees = Slider(start=1, end=10, step=1, value=5, title="Degrees")
slider_lines = Slider(start=1, end=50, step=1, value=10, title="Lines")
slider_points = Slider(start=1, end=100, step=1, value=20, title="Points")

# The datapoints
source_points = ColumnDataSource(data=dict(x=x, y=func(x)+err))
p.scatter(x='x', y='y', source=source_points, color="blue", line_width=3)

# The function where the datapoints come from
source_function = ColumnDataSource(data=dict(x=x, y=func(x)))
p.line(x='x', y='y', source=source_function, color="blue", line_width=1)

# The bootstrap lines
source_lines = ColumnDataSource(data=dict(xs=[ [], [] ], ys=[ [], [] ]))
p.multi_line(xs='xs', ys='ys', source=source_lines, color="pink", line_width=0)

# Their average
source_avg = ColumnDataSource(data=dict(x=[], y=[]))
p.line(x='x', y='y', source=source_avg, color="red", line_width=2)

# Basic instructions
div_instr = Div(text="<font color=black>\
예제 #29
0
def do_a_plot(table):
	#print table.columns
	table.columns = [c.strip() for c in table.columns]
	#df.columns = ['a', 'b']
	column_list = list(table)
	#print column_list
	#print table[column_list[0]]
	table['blank_x'] = '' # add fake columns for plotting
	table['blank_y'] = ''
	#table['blank_x_err'] = ''
	#table['blank_y_err'] = ''
	source = ColumnDataSource(data=dict(table))

	plot = Figure(plot_width=650, plot_height=650)
	scatter = plot.scatter('blank_x', 'blank_y', source=source, _changing=True)
	# line = plot.line('blank_x', 'blank_y', source=source, visible=False, _changing=True)

	main_callback = CustomJS(args=dict(source=source,
		xaxis=plot.xaxis[0],
		yaxis=plot.yaxis[0]), code="""
	        var data = source.get('data');
	        var f = cb_obj.get('value').trim();
	        console.log(f);
	        for(var propertyName in data) {
				console.log('name ' + propertyName + ', name_stripped ' + propertyName.trim());
			}
	        var axis = cb_obj.get('title')[0].toLowerCase();
	        console.log(axis);
	        if (axis == 'x') {
	        	xaxis.set({"axis_label": f});
	        } else if (axis == 'y') {
	        	yaxis.set({"axis_label": f});
	        } else {
	        	return false;
	        }
	        blank_data = data['blank_' + axis];
	        for (i = 0; i < blank_data.length; i++) {
	            blank_data[i] = data[f][i];
	        }
	        source.trigger('change');
	    """)

	reverse_js = """
			var start = range.get("start");
			var end = range.get("end");
			range.set({"start": end, "end": start});
			return false;
		"""
	reverse_x_callback = CustomJS(args=dict(range=plot.x_range), code=reverse_js)
	reverse_y_callback = CustomJS(args=dict(range=plot.y_range), code=reverse_js)

	select_x = Select(title="X Options:", value=column_list[0], options=column_list, callback=main_callback)
	select_y = Select(title="Y Options:", value=column_list[0], options=column_list, callback=main_callback)
	select_c = Select(title="Color Weight:", value=column_list[0], options=column_list, callback=main_callback)	
	select_r = Select(title="Size Weight:", value=column_list[0], options=column_list, callback=main_callback)	
	reverse_x_button = Button(label="Reverse X range", type="success", callback=reverse_x_callback)
	reverse_y_button = Button(label="Reverse Y range", type="success", callback=reverse_y_callback)

	# layout = vform(select_x, select_y, reverse_x_button, reverse_y_button, plot)
	
	controls = [select_x, select_y, select_c, select_r, reverse_x_button, reverse_y_button]
	inputs = HBox(VBoxForm(*controls))
	curdoc().add_root(HBox(inputs, plot))

	output_file('bokeh_plot.html') # currently writes to a file
	save(curdoc())
	shutil.copy('bokeh_plot.html', 'templates/')
예제 #30
0
# SCATTER

# noinspection PyUnresolvedReferences
# add tiles
tile_provider = bokeh.tile_providers.get_provider(
    bokeh.tile_providers.Vendors.CARTODBPOSITRON)
# map_fig.add_tile(tile_provider)

# scatter in map
# map_fig.scatter(
#     'GX', 'GY', source=source_master, size='r',
#     color=cm
# )

# cart_fig.line('lo', 'la', source=source_bol, color='black')
cart_fig.scatter('x', 'y', source=source_master, size='r', color=cm)

# red_scat_map = map_fig.scatter('gx', 'gy',
#                                source=source_red_map, color='red',
#                                line_color='green',
#                                size=10
#                                )
# red_scat_car = cart_fig.scatter('lo', 'la',
# source=source_red_car, color='green')

# add a hover tool that sets the link data for a hovered circle

# callbacks
callback_red_map = CustomJS(
    args={
        'source_master': source_master,
예제 #31
0
def densidad_carto(width=500):
    bokeh.plotting.reset_output()

    WIDTH = width
    CB_VALS = [0, 1, 2, 3]
    CB_LIMS = ebu.DEN_LIMS
    CB_LABS = {s: str(l) for s, l in enumerate(CB_LIMS[:])}
    FILE_OUT = os.path.join(ebu.DIR,
                            'htlml_1_intermedios/2020/z040_densidad2020.html')
    # bokeh.plotting.output_file(FILE_OUT)
    df0 = pd.read_csv(
        os.path.join(ebu.DATA_PATH1_2020,
                     'z020_geopadron_recintos_2020_ALL_DEN.csv'),
        # encoding='ISO-8859-1'
    ).set_index('ID_RECI')
    df1 = pd.read_csv(os.path.join(ebu.DATA_PATH1_2020,
                                   'z030_carto_xy.csv')).set_index('ID_RECI')
    rec_df = pd.merge(df0,
                      df1,
                      left_index=True,
                      right_index=True,
                      validate='1:1')
    # %%
    len(rec_df)
    # %%
    rec_df['r'] = np.sqrt(rec_df['HAB']) / 10
    res = ebu.lola_to_cart(rec_df['LON'].values, rec_df['LAT'].values)
    rec_df['GX'] = res[0]
    rec_df['GY'] = res[1]
    needed_cols = [
        'X', 'Y', 'd_mas_cc', 'r', 'LAT', 'LON', 'PAIS', 'REC', 'MUN', 'DEN'
        'GX', 'GY'
    ]
    # %%
    len(rec_df)
    # %%
    # order by density
    rec_df = rec_df.sort_values('DEN', axis=0, ascending=True)
    # %%
    # remove nans
    # rec_df = rec_df.dropna(axis=0)
    # assert rec_df.isna().sum().sum() == 0
    # %%
    len(rec_df)
    # %%
    # cut = pd.IntervalIndex.from_tuples([(0, 50), (50, 500), (500, 1500),(1500,3000),(3000,4000),(4000,7000)])
    # %%
    # lab = ['B','M','X','A']
    lab = CB_VALS
    lims = CB_LIMS
    NL = len(lims)
    c = pd.cut(
        rec_df['DEN'],
        lims,
        labels=lab,
        #              retbins=True
    )
    # %%
    rec_df['DEN_CUT'] = c.astype(int)
    # %%
    # %% [markdown]
    # ## Carto Densidad
    # %% [markdown]
    # ###### código
    # %%
    # output_file(os.path.join(ebu.DATA_FIG_OUT, "carto_map_mas_cc.html"))
    # %%
    # rec_df_spl = rec_df.sample(200).copy()
    rec_df_spl = rec_df.copy()
    # %%
    # DATA
    bokeh.plotting.output_notebook()
    cart_init_val = .0
    data = rec_df_spl.copy()
    data['x'] = data['LON'] * (1 - cart_init_val) + data['X'] * cart_init_val
    data['y'] = data['LAT'] * (1 - cart_init_val) + data['Y'] * cart_init_val
    # %%
    # COLOR
    from bokeh.transform import linear_cmap
    from bokeh.transform import log_cmap
    # cm = linear_cmap('d_mas_cc', palette=ebu.P_DIF[::-1], low=-80, high=80)
    # cm = log_cmap('DEN', palette=bokeh.palettes.Viridis11, low=1, high=10000)
    cm = linear_cmap('DEN_CUT',
                     palette=bokeh.palettes.Viridis[NL - 1],
                     low=0,
                     high=NL - 1)
    # %%
    # SOURCES
    source_master = ColumnDataSource(data)
    source_red_map = ColumnDataSource({'gx': [], 'gy': []})
    la, lo = ebu.get_la_lo_bolivia()
    source_bol = ColumnDataSource({'la': la, 'lo': lo})
    # source_red_car = ColumnDataSource({'lo': [], 'la': []})
    # %%
    # JS CODE
    code_draw_red_map = """
const data = {'gx': [], 'gy': []}
const indices = cb_data.index.indices
for (var i = 0; i < indices.length; i++) {
        data['gx'].push(source_master.data.GX[indices[i]])
        data['gy'].push(source_master.data.GY[indices[i]])
}
source_red_map.data = data
"""
    code_draw_red_car = """
const data = {'lo': [], 'la': []}
const indices = cb_data.index.indices
for (var i = 0; i < indices.length; i++) {
        data['lo'].push(source_master.data.x[indices[i]])
        data['la'].push(source_master.data.y[indices[i]])
}
source_red_car.data = data
"""
    code_merged = """
const data_map = {'lo': [], 'la': []}
const data_car = {'gx': [], 'gy': []}
const indices = cb_data.index.indices
for (var i = 0; i < indices.length; i++) {
        data_map['lo'].push(source_master.data.x[indices[i]])
        data_map['la'].push(source_master.data.y[indices[i]])
        data_car['gx'].push(source_master.data.GX[indices[i]])
        data_car['gy'].push(source_master.data.GY[indices[i]])
}
source_red_car.data = data_car
source_red_map.data = data_map
"""
    code_slider = """
    var data = source.data;
    var f = cb_obj.value
    var x = data['x']
    var y = data['y']
    var Y = data['Y']
    var X = data['X']
    var lat = data['LAT']
    var lon = data['LON']
    for (var i = 0; i < x.length; i++) {
        y[i] = (1-f)*lat[i] + f*Y[i]
        x[i] = (1-f)*lon[i] + f*X[i]
    }
    source.change.emit();
"""
    # %%
    # FIGURES
    pw = WIDTH
    cart_fig = Figure(plot_width=pw + int(.2 * pw),
                      plot_height=pw,
                      output_backend="webgl")
    # map_fig = Figure(plot_width=pw, plot_height=pw,
    #                  x_axis_type='mercator',
    #                  y_axis_type='mercator',
    #                  output_backend="webgl",
    #                  )
    # cb_fig = bokeh.plotting.Figure(plot_height=pw,plot_width=)
    # cb_fig.toolbar.logo = None
    # cb_fig.toolbar_location = None
    # %%
    # SCATTER
    # noinspection PyUnresolvedReferences
    # add tiles
    tile_provider = bokeh.tile_providers.get_provider(
        bokeh.tile_providers.Vendors.CARTODBPOSITRON)
    # map_fig.add_tile(tile_provider)
    # scatter in map
    # map_fig.scatter(
    #     'GX', 'GY', source=source_master, size='r',
    #     color=cm
    # )
    # cart_fig.line('lo', 'la', source=source_bol, color='black')
    cart_fig.scatter('x', 'y', source=source_master, size='r', color=cm)
    # red_scat_map = map_fig.scatter('gx', 'gy',
    #                                source=source_red_map, color='red',
    #                                line_color='green',
    #                                size=10
    #                                )
    # red_scat_car = cart_fig.scatter('lo', 'la',
    # source=source_red_car, color='green')
    # add a hover tool that sets the link data for a hovered circle
    # callbacks
    callback_red_map = CustomJS(
        args={
            'source_master': source_master,
            'source_red_map': source_red_map,
            # 'source_red_car':source_red_car
        },
        code=code_draw_red_map)
    # code = code_merged)
    # callback_red_car = CustomJS(
    #     args={'source_master': source_master, 'source_red_car': source_red_car},
    #     code=code_draw_red_car)
    # tools
    ebu.TOOL_TIPS1 = [('Inscritos', '@HAB'), ('País', '@PAIS'),
                      ('Municipio', '@MUN'), ('Recinto', '@REC'),
                      ('Votantes/km^2', '@DEN{0}'), ('--------', '------')
                      # ('PAIS', '@PAIS'),
                      ]
    hover_cart = bokeh.models.HoverTool(
        tooltips=ebu.TOOL_TIPS1,
        callback=callback_red_map,
        # renderers = [red_scat_car]
    )
    cart_fig.add_tools(hover_cart, )
    hover_map = bokeh.models.HoverTool(
        tooltips=ebu.TOOL_TIPS1,
        # callback=callback_red_car,
        # renderers = [red_scat_map]
    )
    # map_fig.add_tools(hover_map, )
    # slider
    callback_slider = CustomJS(args=dict(source=source_master),
                               code=code_slider)
    slider = Slider(start=0,
                    end=1,
                    value=cart_init_val,
                    step=.01,
                    title="carto")
    slider.js_on_change('value', callback_slider)
    # %%
    # COLOR BAR
    cb = bokeh.models.ColorBar(
        color_mapper=cm['transform'],
        width=30,
        location=(0, 0),
        title="Den. (V./km^2)",
        # margin=0,padding=0,
        title_standoff=10,
        #     ticker=bokeh.models.LogTicker(),
        major_label_overrides=CB_LABS,
        ticker=bokeh.models.FixedTicker(ticks=list(CB_LABS.keys())))
    cart_fig.add_layout(cb, 'left')
    # layout = row(column(slider, cart_f),map_f)
    # layout = bokeh.layouts.gridplot(
    #     [[slider, None], [cart_fig, map_fig]]
    #     , merge_tools=False
    # )
    layout = bokeh.layouts.column([slider, cart_fig],
                                  # sizing_mode='scale_width'
                                  )
    layout.width = width
    cart_fig.x_range.start = -80
    cart_fig.x_range.end = -45
    cart_fig.y_range.start = -30
    cart_fig.y_range.end = 0
    _ll = ebu.lola_to_cart(lo=[-80, -45], la=[-30, 0])
    # map_fig.x_range.start = _ll[0][0]
    # map_fig.x_range.end = _ll[0][1]
    # map_fig.y_range.start = _ll[1][0]
    # map_fig.y_range.end = _ll[1][1]
    # %% [markdown]
    # ###### gráfica
    # %% [markdown]
    # En el mapa de abajo, cada punto corresponde un recinto electoral, su color está relacionado con la densidad de votantes, y su tamaño con la cantidad de votos.
    # Mueve el slider (carto) para ver la deformación.
    # %%
    # %%
    bokeh.plotting.show(layout)
                    x_range=[curveintegral_settings.x_min, curveintegral_settings.x_max],
                    y_range=[curveintegral_settings.y_min, curveintegral_settings.y_max]
                    )

# remove grid from plot
plot_field.grid[0].grid_line_alpha = 0.0
plot_field.grid[1].grid_line_alpha = 0.0

# Plot the direction field
plot_field.segment('x0', 'y0', 'x1', 'y1', source=source_segments)
plot_field.patches('xs', 'ys', source=source_patches)
plot_field.circle('x', 'y', source=source_basept, color='blue', size=1.5)
# Plot curve
plot_field.line('x', 'y', source=source_curve, color='black', legend='curve')
# Plot parameter point
plot_field.scatter('x', 'y', source=source_param, color='black', legend='c(t)')
# Plot corresponding tangent vector
plot_field.segment('x0', 'y0', 'x1', 'y1', source=source_param, color='black')
plot_field.patches('xs', 'ys', source=source_param, color='black')

# Generate a figure container for the integral value
plot_integral = Figure(title_text_font_size="12pt",
                       plot_height=200,
                       plot_width=400,
                       title="Integral along curve",
                       x_range=[curveintegral_settings.parameter_min, curveintegral_settings.parameter_max],
                       y_range=[-10,10]
                       )
plot_integral.logo = None

plot_integral.scatter('t',0, source=source_param, color='black')
예제 #33
0
import numpy as np

from bokeh.io import show
from bokeh.plotting import Figure
from bokeh.models import ColumnDataSource, CustomJS, Spinner
from bokeh.layouts import row, widgetbox

data = np.random.rand(10, 2)
cds = ColumnDataSource(data=dict(x=data[:, 0], y=data[:, 1]))

p = Figure(x_range=(0, 1), y_range=(0, 1))
points = p.scatter(x='x', y='y', source=cds)

w = Spinner(title="Glyph size", low=1, high=20, step=0.1, value=4, width=100)
cb = CustomJS(args={'points': points}, code="""
points.glyph.size = cb_obj.value
""")
points.glyph.size = w.value

w.js_on_change('value', cb)

show(row([widgetbox(w, width=100), p]))
)
# cb_fig = bokeh.plotting.Figure(plot_height=pw,plot_width=)
# cb_fig.toolbar.logo = None
# cb_fig.toolbar_location = None

# %%
# SCATTER

# noinspection PyUnresolvedReferences
# add tiles
tile_provider = bokeh.tile_providers.get_provider(
    bokeh.tile_providers.Vendors.CARTODBPOSITRON)
map_fig.add_tile(tile_provider)

# scatter in map
map_fig.scatter('GX', 'GY', source=source_master, size='r', color=cm)

cart_fig.line('lo', 'la', source=source_bol, color='black')
cart_fig.scatter('x', 'y', source=source_master, size='r', color=cm)

red_scat_map = map_fig.scatter('gx',
                               'gy',
                               source=source_red_map,
                               color='red',
                               line_color='green',
                               size=10)
# red_scat_car = cart_fig.scatter('lo', 'la',
# source=source_red_car, color='green')

# add a hover tool that sets the link data for a hovered circle
예제 #35
0
# dropdown menu for selecting one of the sample curves
sample_curve_input = Dropdown(label="choose a sample function pair or enter one below",
                              menu=leibnitz_settings.sample_curve_names)
sample_curve_input.on_change('value', sample_curve_change)

# initialize plot
toolset = "crosshair,pan,reset,save,wheel_zoom"
# Generate a figure container
plot = Figure(plot_height=400, plot_width=400, tools=toolset,
              title="Leibnitz sector formula",
              x_range=[leibnitz_settings.x_min_view, leibnitz_settings.x_max_view],
              y_range=[leibnitz_settings.y_min_view, leibnitz_settings.y_max_view])

# Plot the line by the x,y values in the source property
plot.line('x', 'y', source=source_curve, line_width=3, line_alpha=1, color='black', legend_label='curve')
plot.scatter('x', 'y', source=source_point, color='blue', legend_label='point at t')
plot.scatter([0], [0], color='black', marker='x')
pat = plot.patch('x', 'y', source=source_sector, fill_color='blue', fill_alpha=.2, legend_label='area')
plot.line('x_start', 'y_start', source=source_lines, line_width=1, line_alpha=1, color='blue')
plot.line('x_end', 'y_end', source=source_lines, line_width=1, line_alpha=1, color='blue')
plot.text('x', 'y', text='text', text_color='text_color', source=source_text)

# calculate data
update_curve()
update_point()

# lists all the controls in our app
controls = widgetbox(t_value_input, sample_curve_input, x_component_input, y_component_input)

# make layout
curdoc().add_root(row(plot, controls))
cart_fig.background_fill_alpha = .5
# cb_fig = bokeh.plotting.Figure(plot_height=pw,plot_width=)
# cb_fig.toolbar.logo = None
# cb_fig.toolbar_location = None

# %%
# SCATTER

# noinspection PyUnresolvedReferences
# add tiles
tile_provider = bokeh.tile_providers.get_provider(
    bokeh.tile_providers.Vendors.CARTODBPOSITRON)
map_fig.add_tile(tile_provider)

# scatter in map
map_fig.scatter('GX', 'GY', source=source_master, size='r2', color=cm)

cart_fig.line('lo', 'la', source=source_bol, color='black')
cart_fig.scatter('x', 'y', source=source_master, radius='r', color=cm)

red_scat_map = map_fig.circle_cross(
    'gx',
    'gy',
    source=source_red_map,
    #                                color='red',
    fill_color=None,
    #                                line_color='green',
    size=20,
    line_color="#dd1c77",
    line_width=3)
# red_scat_car = cart_fig.scatter('lo', 'la',
예제 #37
0
# create plots
#REMARK: color might not be used from internal vis.js and has no effect - colormap always according to z! see https://github.com/bokeh/bokeh/issues/7814
surface = diffraction_Surface3d(x="x", y="y", z="z", color="color", data_source=source_surf, width=500,height=100)  # wave surface
# contour plots of wave
contour_zero = diffraction_Contour(plot, line_width=2,line_color='black', path_filter = 10)  # zero level
contour_pos  = diffraction_Contour(plot, line_width=1, line_color='red', path_filter = 10)  # some other levels
contour_neg  = diffraction_Contour(plot, line_width=1, line_color='blue', path_filter = 10)  # some other levels

kvector = diffraction_Quiver(plot, fix_at_middle=False) # visualization of wave k vector
plot.line(x=[x_min,0], y=[0,0], line_dash='dashed')
plot.line(x=[x_max,0], y=[0,0], line_width=10)  # the wall
plot.line(x='x', y='y', source=source_wavefront)  # wavefront visualization
plot.patch(x='x', y='y', color='yellow', source=source_light, alpha=.1)  # light area
plot.patch(x='x', y='y', color='red',source=source_reflection, alpha=.1)  # reflection area
plot.patch(x='x', y='y', color='blue', source=source_shadow, alpha=.1)  # shadow area
plot.scatter(x='x',y='y', source=source_value_plotter, size=10)  # value probing
plot.toolbar.logo = None

initialize()

# add app description
description_filename = join(dirname(__file__), "description.html")

description = LatexDiv(text=open(description_filename).read(), render_as_text=False, width=1130)

# add area image
area_image = Div(text="""
<p>
<img src=/Diffraction/static/images/Diffraction_areas.jpg width=300>
</p>
<p>
예제 #38
0
plots = []
for i_dataset, dataset in enumerate(
    [noisy_circles, noisy_moons, blobs1, blobs2]):
    X, y = dataset
    X = StandardScaler().fit_transform(X)

    # Predict cluster memberships
    algorithm.fit(X)
    if hasattr(algorithm, 'labels_'):
        y_pred = algorithm.labels_.astype(np.int)
    else:
        y_pred = algorithm.predict(X)

    # Plot
    p = Figure(webgl=True,
               title=name,
               plot_width=PLOT_SIZE,
               plot_height=PLOT_SIZE)
    p.scatter(
        X[:, 0],
        X[:, 1],
        color=colors[y_pred].tolist(),
        alpha=0.1,
    )
    plots.append(p)

# Genearate and show the plot
box = VBox(HBox(plots[0], plots[1]), HBox(plots[2], plots[3]))
output_file("clustering.html", title="clustering with sklearn")
show(box)
예제 #39
0
# Generate a figure container
plot = Figure(plot_height=400,
              plot_width=400,
              tools=toolset,
              title="2D ODE System",
              x_range=[odesystem_settings.x_min, odesystem_settings.x_max],
              y_range=[odesystem_settings.y_min, odesystem_settings.y_max]
              )
# remove grid from plot
plot.grid[0].grid_line_alpha = 0.0
plot.grid[1].grid_line_alpha = 0.0

# Plot the direction field
quiver = my_bokeh_utils.Quiver(plot)
# Plot initial values
plot.scatter('x0', 'y0', source=source_initialvalue, color='black', legend='(x0,y0)')
# Plot streamline
plot.line('x', 'y', source=source_streamline, color='black', legend='streamline')
# Plot critical points and lines
plot.scatter('x', 'y', source=source_critical_pts, color='red', legend='critical pts')
plot.multi_line('x_ls', 'y_ls', source=source_critical_lines, color='red', legend='critical lines')

# initialize controls
# text input for input of the ode system [u,v] = [x',y']
u_input = TextInput(value=odesystem_settings.sample_system_functions[odesystem_settings.init_fun_key][0], title="u(x,y):")
v_input = TextInput(value=odesystem_settings.sample_system_functions[odesystem_settings.init_fun_key][1], title="v(x,y):")

# dropdown menu for selecting one of the sample functions
sample_fun_input = Dropdown(label="choose a sample function pair or enter one below",
                            menu=odesystem_settings.sample_system_names)
예제 #40
0
import pandas as pd
from bokeh.models.widgets import Slider, HBox

data_path = './main.csv'

data = pd.read_csv(data_path, dtype={'x': np.float, 'y': np.float, 'label': np.int})

hover = HoverTool(tooltips=[("value", "@text"), ], active=False)
plot = Figure(tools=[hover,  WheelZoomTool(), BoxZoomTool(), PanTool(), ResetTool()],
    webgl=True,
    plot_width=800,
    plot_height=800,
    y_axis_type="log")

source = ColumnDataSource(data)
scatter = plot.scatter(source=source, line_width=0, line_alpha=0, size=10, x="x", y="y", alpha=0.5)

p_value = Slider(title='p value', value=0.5, start=1, end=10, step=0.5, orientation='horizontal')
p_mult = Slider(title='x', value=1, start=1, end=70, step=1)

def get_p():
    return p_value.value * 10**-p_mult.value


left_limit = Slider(title='left_limit', value=-0.5, start=-1, end=0, step=0.001, orientation='horizontal')
right_limit = Slider(title='right_limit', value=0.5, start=0, end=1, step=0.001, orientation='horizontal')

left = Span(location=left_limit.value, dimension='height', line_color='maroon', render_mode='css')
plot.renderers.append(left)
right = Span(location=right_limit.value, dimension='height', line_color='maroon', render_mode='css')
plot.renderers.append(right)
예제 #41
0
                              menu=arc_settings.sample_curve_names)
sample_curve_input.on_click(sample_curve_change)


# initialize plot
toolset = "crosshair,pan,reset,resize,save,wheel_zoom"
# Generate a figure container
plot = Figure(plot_height=400, plot_width=400, tools=toolset,
              title="Arc length parametrization",
              x_range=[arc_settings.x_min_view, arc_settings.x_max_view],
              y_range=[arc_settings.y_min_view, arc_settings.y_max_view])

# Plot the line by the x,y values in the source property
plot.line('x', 'y', source=source_curve, line_width=3, line_alpha=1, color='black', legend='curve')
# quiver related to normal length parametrization
quiver = 2*[None]
quiver[0] = my_bokeh_utils.Quiver(plot, fix_at_middle=False, line_width=2, color='blue')
plot.scatter('x', 'y', source=source_point_normal, color='blue', legend='original parametrization')
# quiver related to arc length parametrization
quiver[1] = my_bokeh_utils.Quiver(plot, fix_at_middle=False, line_width=2, color='red')
plot.scatter('x', 'y', source=source_point_arc, color='red', legend='arc length parametrization')

# calculate data
update_curve()
update_points()
update_tangents()

# make layout
curdoc().add_root(row(plot, widgetbox(parametrization_input, t_value_input, sample_curve_input, x_component_input,
                                      y_component_input, width=400)))
예제 #42
0
파일: render.py 프로젝트: pplonski/dataprep
def render_crossfilter(itmdt: Intermediate, plot_width: int,
                       plot_height: int) -> column:
    """
    Render crossfilter scatter plot with a regression line.
    """

    # pylint: disable=too-many-locals, too-many-function-args
    df = itmdt["data"]
    df["__x__"] = df[df.columns[0]]
    df["__y__"] = df[df.columns[0]]
    source_scatter = ColumnDataSource(df)
    source_xy_value = ColumnDataSource({
        "x": [df.columns[0]],
        "y": [df.columns[0]]
    })
    var_list = list(df.columns[:-2])

    xcol = source_xy_value.data["x"][0]
    ycol = source_xy_value.data["y"][0]

    tooltips = [("X-Axis: ", "@__x__"), ("Y-Axis: ", "@__y__")]

    fig = Figure(
        plot_width=plot_width,
        plot_height=plot_height,
        toolbar_location=None,
        title=Title(text="Scatter Plot", align="center"),
        tools=[],
        x_axis_label=xcol,
        y_axis_label=ycol,
    )
    scatter = fig.scatter("__x__", "__y__", source=source_scatter)

    hover = HoverTool(tooltips=tooltips, renderers=[scatter])
    fig.add_tools(hover)

    x_select = Select(title="X-Axis", value=xcol, options=var_list, width=150)
    y_select = Select(title="Y-Axis", value=ycol, options=var_list, width=150)

    x_select.js_on_change(
        "value",
        CustomJS(
            args=dict(
                scatter=source_scatter,
                xy_value=source_xy_value,
                x_axis=fig.xaxis[0],
            ),
            code="""
        let currentSelect = this.value;
        let xyValueData = xy_value.data;
        let scatterData = scatter.data;

        xyValueData['x'][0] = currentSelect;
        scatterData['__x__'] = scatterData[currentSelect];

        x_axis.axis_label = currentSelect;
        scatter.change.emit();
        xy_value.change.emit();
        """,
        ),
    )
    y_select.js_on_change(
        "value",
        CustomJS(
            args=dict(
                scatter=source_scatter,
                xy_value=source_xy_value,
                y_axis=fig.yaxis[0],
            ),
            code="""
        let currentSelect = this.value;
        let xyValueData = xy_value.data;
        let scatterData = scatter.data;

        xyValueData['y'][0] = currentSelect;
        scatterData['__y__'] = scatterData[currentSelect];

        y_axis.axis_label = currentSelect;
        scatter.change.emit();
        xy_value.change.emit();
        """,
        ),
    )

    fig = column(row(x_select, y_select, align="center"),
                 fig,
                 sizing_mode="stretch_width")
    return fig
예제 #43
0
    title="Vector valued function",
    x_range=[curveintegral_settings.x_min, curveintegral_settings.x_max],
    y_range=[curveintegral_settings.y_min, curveintegral_settings.y_max])

# remove grid from plot
plot_field.grid[0].grid_line_alpha = 0.0
plot_field.grid[1].grid_line_alpha = 0.0

# Plot the direction field
plot_field.segment('x0', 'y0', 'x1', 'y1', source=source_segments)
plot_field.patches('xs', 'ys', source=source_patches)
plot_field.circle('x', 'y', source=source_basept, color='blue', size=1.5)
# Plot curve
plot_field.line('x', 'y', source=source_curve, color='black', legend='curve')
# Plot parameter point
plot_field.scatter('x', 'y', source=source_param, color='black', legend='c(t)')
# Plot corresponding tangent vector
plot_field.segment('x0', 'y0', 'x1', 'y1', source=source_param, color='black')
plot_field.patches('xs', 'ys', source=source_param, color='black')

# Generate a figure container for the integral value
plot_integral = Figure(title_text_font_size="12pt",
                       plot_height=200,
                       plot_width=400,
                       title="Integral along curve",
                       x_range=[
                           curveintegral_settings.parameter_min,
                           curveintegral_settings.parameter_max
                       ],
                       y_range=[-10, 10])
plot_integral.logo = None
예제 #44
0
def scatter(
    figure: Figure,
    x: List[DataType],
    y: List[DataType],
    smiles: Dict[str, tuple],
    legend_label: Optional[str] = None,
    marker: Optional[str] = None,
    marker_size: Optional[int] = None,
    marker_color: Optional[str] = None,
    **kwargs: Dict[str, Any],
):
    """Adds a scatter series to a bokeh figure which will show the molecular
    structure associated with a data point when the user hovers over it.

    Args:
        figure: The bokeh figure to plot the scatter data on.
        x: An array of the x values to plot.
        y: An array of the y values to plot.
        smiles: An array of the SMILES patterns associated with each (x, y) pair.
        legend_label: The label to show in the legend for this data series.
        marker: The marker style.
        marker_size: The size of the marker to draw.
        marker_color: The marker color.
        kwargs: Extra keyword arguments to pass to the underlying bokeh ``scatter``
            function.
    """
    
    # Validate the sizes of the input arrays.
    data_sizes = {"x": len(x), "y": len(y), "smiles": len(smiles)}

    if len({*data_sizes.values()}) != 1:
        raise InputSizeError(data_sizes)

    makevalid = lambda x: x if x.find('_') < 0 else x[:x.find('_')]

    # Generate an image for each SMILES pattern.
    raw_images = []
    xvalid = []
    yvalid = []
    smivalid = []
    for (smiles_pattern, torsion_indices), x_, y_ in zip(smiles.items(), x, y):
        try:
            img = base64.b64encode(smiles_to_svg(makevalid(smiles_pattern), torsion_indices).encode()).decode()
            raw_images.append(img)
            xvalid.append(x_)
            yvalid.append(y_)
            smivalid.append(smiles_pattern)
        except rdkit.Chem.rdchem.AtomValenceException:
            print(f"AtomicValenceException for smiles {makevalid(smiles_pattern)} with torsions {torsion_indices}")
            continue

    images = [f"data:image/svg+xml;base64,{raw_image}" for raw_image in raw_images]

    # Create a custom data source.
    source = ColumnDataSource(data={"x": xvalid, "y": yvalid, "smiles": smivalid, "image": images})

    # Add the scatter data.
    scatter_kwargs = {**kwargs}

    if marker is not None:
        scatter_kwargs["marker"] = marker
    if marker_size is not None:
        scatter_kwargs["size"] = marker_size
    if marker_color is not None:
        scatter_kwargs["color"] = marker_color
    if legend_label is not None:
        scatter_kwargs["legend_label"] = legend_label

    figure.scatter(x="x", y="y", source=source, **scatter_kwargs)
예제 #45
0
from bokeh.plotting import Figure
from bokeh.models import BoxSelectTool, ColumnDataSource, HBox
from bokeh.io import curdoc
import numpy

#x0,y0=numpy.meshgrid(1,1,indexing='xy')
#circleSource=ColumnDataSource(data={'x':[numpy.ravel(x0)*10.0],'y':[numpy.ravel(y0)*10.0]})

x0=numpy.random.rand(10)
y0=numpy.random.rand(10)
circleSource=ColumnDataSource(data=dict(x=x0*10.0,y=y0*10.0))

p=Figure(x_range=[-10,10], y_range=[0,10], plot_width=400, plot_height=400,tools="crosshair, box_select, wheel_zoom")
#p.circle('x','y',source=circleSource,size=10,color="navy")
p.scatter(x0,y0,size=10,color="navy")
p.select(BoxSelectTool).select_every_mousemove = False


p2=Figure(x_range=[-10,10], y_range=[0,10], plot_width=400, plot_height=400,tools="crosshair, box_select, wheel_zoom")
p2.scatter('x','y',source=circleSource,size=10,color="navy",name="scatter")
p2.select(BoxSelectTool).select_every_mousemove = False
renderer = p2.select(dict(name="scatter"))
scatter_ds = renderer[0].data_source

figs=HBox(children=[p,p2])
curdoc().add_root(HBox(children=[figs],width=800))

def updateSelection(attrname, old, new):
    inds=numpy.array(new['1d']['indices'])
    #print(inds)
    numpy.savetxt('selInds.txt',inds,fmt='%d')
예제 #46
0
plot = Figure(plot_height=400,
              plot_width=400,
              tools=toolset,
              title="2D ODE System",
              x_range=[odesystem_settings.x_min, odesystem_settings.x_max],
              y_range=[odesystem_settings.y_min, odesystem_settings.y_max])
# remove grid from plot
plot.grid[0].grid_line_alpha = 0.0
plot.grid[1].grid_line_alpha = 0.0

# Plot the direction field
quiver = my_bokeh_utils.Quiver(plot)
# Plot initial values
plot.scatter('x0',
             'y0',
             source=source_initialvalue,
             color='black',
             legend='(x0,y0)')
# Plot streamline
plot.line('x',
          'y',
          source=source_streamline,
          color='black',
          legend='streamline')
# Plot critical points and lines
plot.scatter('x',
             'y',
             source=source_critical_pts,
             color='red',
             legend='critical pts')
plot.multi_line('x_ls',
예제 #47
0
def render_crossfilter(itmdt: Intermediate, plot_width: int,
                       plot_height: int) -> column:
    """
    Render crossfilter scatter plot with a regression line.
    """

    # pylint: disable=too-many-locals, too-many-function-args
    source_scatter = ColumnDataSource(itmdt["data"])
    source_coeffs = ColumnDataSource(itmdt["coeffs"])
    source_xy_value = ColumnDataSource({
        "x": [itmdt["data"].columns[0]],
        "y": [itmdt["data"].columns[0]]
    })
    var_list = list(itmdt["data"].columns)[0:-2]

    xcol = source_xy_value.data["x"][0]
    ycol = source_xy_value.data["y"][0]

    tooltips = [("X-Axis: ", "@__x__"), ("Y-Axis: ", "@__y__")]

    fig = Figure(
        plot_width=plot_width,
        plot_height=plot_height,
        toolbar_location=None,
        title=Title(text="Scatter Plot & Regression Line", align="center"),
        tools=[],
        x_axis_label=xcol,
        y_axis_label=ycol,
    )
    scatter = fig.scatter("__x__", "__y__", source=source_scatter)
    fig.line("__x__", "__y__", source=source_coeffs, line_width=3)

    # Not adding the tooltips before because we only want to apply tooltip to the scatter
    hover = HoverTool(tooltips=tooltips, renderers=[scatter])
    fig.add_tools(hover)

    x_select = Select(title="X-Axis", value=xcol, options=var_list, width=150)
    y_select = Select(title="Y-Axis", value=ycol, options=var_list, width=150)

    x_select.js_on_change(
        "value",
        CustomJS(
            args=dict(
                scatter=source_scatter,
                coeffs=source_coeffs,
                xy_value=source_xy_value,
                x_axis=fig.xaxis[0],
            ),
            code="""
        let currentSelect = this.value;
        let xyValueData = xy_value.data;
        let scatterData = scatter.data;
        let coeffsData = coeffs.data;

        xyValueData['x'][0] = currentSelect;
        scatterData['__x__'] = scatterData[currentSelect];
        coeffsData['__x__'] = coeffsData[`${currentSelect}${xyValueData['y'][0]}x`];
        coeffsData['__y__'] = coeffsData[`${currentSelect}${xyValueData['y'][0]}y`];

        x_axis.axis_label = currentSelect;
        scatter.change.emit();
        coeffs.change.emit();
        xy_value.change.emit();
        """,
        ),
    )
    y_select.js_on_change(
        "value",
        CustomJS(
            args=dict(
                scatter=source_scatter,
                coeffs=source_coeffs,
                xy_value=source_xy_value,
                y_axis=fig.yaxis[0],
            ),
            code="""
        let currentSelect = this.value;
        let xyValueData = xy_value.data;
        let scatterData = scatter.data;
        let coeffsData = coeffs.data;

        xyValueData['y'][0] = currentSelect;
        scatterData['__y__'] = scatterData[currentSelect];
        coeffsData['__x__'] = coeffsData[`${xyValueData['x'][0]}${currentSelect}x`];
        coeffsData['__y__'] = coeffsData[`${xyValueData['x'][0]}${currentSelect}y`];

        y_axis.axis_label = currentSelect;
        scatter.change.emit();
        coeffs.change.emit();
        xy_value.change.emit();
        """,
        ),
    )

    fig = column(row(x_select, y_select, align="center"),
                 fig,
                 sizing_mode="stretch_width")
    return fig