예제 #1
0
def make_plot(yname, line_color, below_axis=True, left_axis=True, right_axis=False, border_fill_color="white"):
    """ Returns a tuple (plot, [obj1...objN]); the former can be added
    to a GridPlot, and the latter is added to the plotcontext.
    """
    plot = Plot(
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        min_border=15,
        border_fill_color=border_fill_color,
        border_fill_alpha=0.1,
        toolbar_location='above',
        plot_width=300,
        plot_height=300,
        responsive='box'
    )
    if below_axis:
        plot.add_layout(LinearAxis(), 'below')
    else:
        plot.add_layout(LinearAxis(), 'above')
    if left_axis:
        plot.add_layout(LinearAxis(), 'left')
    if right_axis:
        plot.add_layout(LinearAxis(), 'right')
    plot.add_glyph(source, Line(x="x", y=yname, line_color=line_color))
    plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())
    return plot
예제 #2
0
def plot_states_bokeh(model, title=''):
    data_table = get_column_data(model)
    data_table = data_table.reset_index()
    source = ColumnDataSource(data_table)
    i = 0
    colors = Category10[4]
    items = []
    plot = figure(plot_width=600,
                  plot_height=400,
                  tools=[],
                  title=title,
                  x_range=(0, 100))
    for c in data_table.columns[1:]:
        line = Line(x='Step',
                    y=c,
                    line_color=colors[i],
                    line_width=3,
                    line_alpha=.8,
                    name=c)
        glyph = plot.add_glyph(source, line)
        i += 1
        items.append((c, [glyph]))
    plot.xaxis.axis_label = 'Step'
    plot.add_layout(Legend(location='center_right', items=items))
    plot.background_fill_color = "#e1e1ea"
    plot.background_fill_alpha = 0.5
    plot.legend.label_text_font_size = "10pt"
    plot.title.text_font_size = "15pt"
    plot.toolbar.logo = None
    plot.sizing_mode = 'scale_height'
    return plot
예제 #3
0
def set_glyphs(colors, column_names, column_time, plot, pos, source):
    for i, name in enumerate(column_names):
        color = colors[i]
        glyph_line = Line(x=column_time,
                          y=name,
                          line_width=1,
                          line_alpha=.7,
                          line_color=color)

        glyph = Circle(x=column_time,
                       y=name,
                       fill_color=color,
                       line_alpha=0,
                       fill_alpha=.7)

        plot.add_layout(
            LinearAxis(y_range_name=name,
                       major_label_text_color=color,
                       axis_line_color=color,
                       major_tick_line_color=color,
                       minor_tick_line_color=color,
                       name=name), pos[i])

        # plot.line(x=column_time,
        #           y=name,
        #           line_width=1,
        #           line_alpha=.7,
        #           line_color=color,
        #           legend=name,
        #           y_range_name=name,
        #           source=source)

        plot.add_glyph(source, glyph, y_range_name=name, name=name)

        plot.add_glyph(source, glyph_line, y_range_name=name, name=name)
예제 #4
0
def make_plot():
    xdr = DataRange1d()
    ydr = DataRange1d()

    plot = Plot(x_range=xdr, y_range=ydr, plot_width=400, plot_height=400)
    plot.title.text = "Product downloads"

    line = Line(x="dates", y="downloads", line_color="blue")
    plot.add_glyph(source, line)

    circle = Circle(x="dates", y="downloads", fill_color="red")
    plot.add_glyph(source, circle)

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

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

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

    plot.add_tools(HoverTool(tooltips=dict(downloads="@downloads")))

    return plot, source
예제 #5
0
def trail_map(data):
    lon = (min(data.lon) + max(data.lon)) / 2
    lat = (min(data.lat) + max(data.lat)) / 2

    map_options = GMapOptions(lng=lon, lat=lat, zoom=13)
    plot = GMapPlot(plot_width=800,
                    plot_height=800,
                    map_options=map_options,
                    api_key=API_KEY)
    plot.title.text = "%s - Trail Map" % name
    plot.x_range = Range1d()
    plot.y_range = Range1d()
    plot.add_tools(PanTool(), WheelZoomTool(), ResetTool())

    line_source = ColumnDataSource(dict(x=data.lon, y=data.lat,
                                        dist=data.dist))
    line = Line(x="x", y="y", line_color="blue", line_width=2)
    plot.add_glyph(line_source, line)

    if plot.api_key == "GOOGLE_API_KEY":
        plot.add_layout(
            Label(x=240,
                  y=700,
                  x_units='screen',
                  y_units='screen',
                  text='Replace GOOGLE_API_KEY with your own key',
                  text_color='red'))

    return plot
예제 #6
0
    def create(cls):
        """One-time creation of app's objects.

        This function is called once, and is responsible for
        creating all objects (plots, datasources, etc)
        """
        obj = cls()

        obj.word_source = ColumnDataSource(dict(x=[], y=[], text=[]))
        obj.target_source = ColumnDataSource(dict(tx=[], ty=[], ttext=[]))
        obj.line_source = ColumnDataSource(dict(word_path_x=[],
                                                word_path_y=[]))

        obj.text = TextInput(title="Word", name='word', value='gay')

        obj.year = Slider(title="Year",
                          name='year',
                          value=1900,
                          start=1900,
                          end=2000,
                          step=5)

        obj.basis = Slider(title="Basis Year",
                           name='basis',
                           value=2000,
                           start=1900,
                           end=2000,
                           step=5)

        toolset = "crosshair,pan,reset,resize,save,wheel_zoom"
        # Generate a figure container
        plot = figure(title_text_font_size="12pt",
                      plot_height=400,
                      plot_width=400,
                      tools=toolset,
                      title="Word Path",
                      x_range=[-1, 1],
                      y_range=[-1, 1])

        #      plot.line("x", "y", source=obj.source)
        glyph = Text(x="x", y="y", text="text", text_color="#96deb3")
        plot.add_glyph(obj.word_source, glyph)
        glypht = Text(x="tx", y="ty", text="ttext")
        plot.add_glyph(obj.target_source, glypht)
        glyphline = Line(x="word_path_x",
                         y="word_path_y",
                         line_width=4,
                         line_alpha=0.3,
                         line_color='red')
        plot.add_glyph(obj.line_source, glyphline)

        obj.plot = plot
        obj.update_data(True, True)

        obj.inputs = VBoxForm(children=[obj.text, obj.year, obj.basis])

        obj.children.append(obj.inputs)
        obj.children.append(obj.plot)

        return obj
예제 #7
0
파일: dotLine.py 프로젝트: cilegann/InCore
    def doBokehViz(self):
        try:
            # self.bokeh_fig.xaxis.axis_label = self.dataCol['x']
            # self.bokeh_fig.yaxis.axis_label = self.dataCol['y']
            [x, y_dot, y_line] = missingFiltering().filtCols(
                [self.data['x'], self.data['y_dot'], self.data['y_line']],
                ['float', 'float', 'float'], [True, True, True])
            x, y_dot, y_line = zip(*sorted(zip(x, y_dot, y_line)))
            x = list(x)
            y_dot = list(y_dot)
            y_line = list(y_line)
            data = ColumnDataSource(data={
                'x': x,
                'y_dot': y_dot,
                'y_line': y_line
            })
            l1 = Line(x='x', y='y_line', line_color='red', line_width=2)
            l2 = Circle(x='x',
                        y='y_dot',
                        fill_color='blue',
                        fill_alpha=0.4,
                        size=7)
            r1 = self.bokeh_fig.add_glyph(data, l1, name='line')
            r2 = self.bokeh_fig.add_glyph(data, l2, name='dot')

            self.bokeh_fig.add_tools(
                HoverTool(tooltips=[('X,Y', '@x,@y_dot')], names=['dot']))
            self.bokeh_fig.add_tools(
                HoverTool(tooltips=[('X,Y', '@x,@y_line')], names=['line']))
        except Exception as e:
            raise Exception(f'[{self.algoInfo["algoname"]}][do_bokeh_viz]{e}')
예제 #8
0
def make_plot(title, xname, yname):
    plot = Plot(x_range=xdr,
                y_range=ydr,
                title=title,
                plot_width=400,
                plot_height=400,
                border_fill='white',
                background_fill='#e9e0db')

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

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

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

    line = Line(x='x', y='y', line_color="#666699", line_width=2)
    plot.add_glyph(lines_source, line)

    circle = Circle(x=xname,
                    y=yname,
                    size=12,
                    fill_color="#cc6633",
                    line_color="#cc6633",
                    fill_alpha=0.5)
    plot.add_glyph(circles_source, circle)

    return plot
예제 #9
0
def altitude_profile(data):
    plot = Plot(plot_width=800, plot_height=400)
    plot.title.text = "%s - Altitude Profile" % name
    plot.y_range.range_padding = 0

    xaxis = LinearAxis(axis_label="Distance (km)")
    plot.add_layout(xaxis, 'below')

    yaxis = LinearAxis(axis_label="Altitude (m)")
    plot.add_layout(yaxis, 'left')

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))  # x grid
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))  # y grid

    plot.add_tools(PanTool(), WheelZoomTool(), ResetTool())

    X, Y = data.dist, data.alt
    y0 = min(Y)

    patches_source = ColumnDataSource(
        dict(xs=[[X[i], X[i + 1], X[i + 1], X[i]] for i in range(len(X[:-1]))],
             ys=[[y0, y0, Y[i + 1], Y[i]] for i in range(len(Y[:-1]))],
             color=data.colors[:-1]))
    patches = Patches(xs="xs", ys="ys", fill_color="color", line_color="color")
    plot.add_glyph(patches_source, patches)

    line_source = ColumnDataSource(dict(x=data.dist, y=data.alt))
    line = Line(x='x', y='y', line_color="black", line_width=1)
    plot.add_glyph(line_source, line)

    return plot
예제 #10
0
def plot_extent(event):

    years = range(year_select.value[0], year_select.value[1])
    df = pd.read_csv('seaice_extent_cleaned.csv', index_col=0)
    df['day_of_year'] = pd.to_datetime(df.date).dt.dayofyear
    df = df[df.year.isin(years)]
    df['year'] = df.year.astype(str)
    data = pd.pivot_table(df,
                          index='day_of_year',
                          columns='year',
                          values='Extent').reset_index()
    source = ColumnDataSource(data)
    p = figure(plot_width=700, plot_height=300)
    years = [str(i) for i in years]
    colors = Category10[10]
    i = 0
    for y in years:
        glyph = Line(x="day_of_year",
                     y=y,
                     line_color=colors[i],
                     line_width=2,
                     line_alpha=0.6)
        p.add_glyph(source, glyph)
        i += 1
    p.y_range.start = 0
    p.y_range.end = 21
    plot.object = p
    return
예제 #11
0
 def build_renderers(self):
     glyph = Line(x='x_values',
                  y='y_values',
                  line_color=self.line_color,
                  line_alpha=self.line_alpha,
                  line_width=self.width,
                  line_dash=self.dash)
     yield GlyphRenderer(glyph=glyph)
예제 #12
0
    def __init__(self, head_selection):
        self.head_selection = head_selection
        self.color_names = ['1 Blue', '2 Orange', '3 Green', '4 Red', '5 Purple', '6 Brown', '7 Pink', '8 Gray', '9 Olive', '10 Cyan']
        self.active_heads = []
        self.args = Settings()
        self.field_height = self.args.field_height
        self.field_width = self.args.field_width
        self.pixel_per_meters = 1#self.args.pixel_per_meters
        self.source_object = ColumnDataSource(data={'x': [], 'y': []})
        self.object_glyph = Circle(x='x', y='y', radius=0.5, fill_alpha=0.8, fill_color='red')
        self.source_vehicle = ColumnDataSource(data={'x': [], 'y': [], 'angle': [], 'width': [], 'height': []})

        self.source_vehicle.selected.on_change('indices', self._tap_on_veh)
        self.vehicle_glyph = Rect(x='x', y='y', angle='angle', width='width', height='height',
                                  fill_color='red', fill_alpha=0.8)
        self.image = None
        self.get_image()
        self.image_height = int(self.pixel_per_meters*self.field_height)
        self.image_width = int(self.pixel_per_meters*self.field_width)

        self.image_center = np.array([self.image_width//2, self.image_height//2])
        self.source_ellipse = []
        self.ellipse_glyph = Ellipse(x='x', y='y', width='width', height='height', angle='angle',
                                     fill_alpha='alpha', line_color=None, fill_color='blue')
        self.n_ellipses = 0

        self.source_lane = []
        self.lane_glyph = Line(x='x', y='y', line_color='gray', line_dash='dashed', line_width=3)
        self.n_lanes = 0

        self.source_arrow = [[], []]
        self.arrow_glyph = Scatter(x='x', y='y', angle='angle', size='size', marker='triangle', line_color=None)
        self.arrow_glyph_list = []

        self.source_path_fut = []
        self.source_path_pred = []
        self.source_path_past = []

        self.fut_path_glyph = Line(x='x', y='y', line_color='green', line_width=2)
        self.pred_path_glyph = Line(x='x', y='y', line_color='red', line_width=2)
        self.past_path_glyph = Line(x='x', y='y', line_color='gray', line_width=2)

        self.n_past = 0
        self.n_fut = 0
        self.n_pred = 0
        self.attention_matrix = None
예제 #13
0
파일: glyphs.py 프로젝트: timopek/bokeh
 def build_renderers(self):
     """Yield a `GlyphRenderer` for the group of data."""
     glyph = Line(x='x_values', y='y_values',
                  line_color=self.line_color,
                  line_alpha=self.line_alpha,
                  line_width=self.width,
                  line_dash=self.dash)
     yield GlyphRenderer(glyph=glyph)
예제 #14
0
def line_glyphs(data, x_field):
    fields = data.columns.values
    sources = dict(zip(fields, np.zeros(len(fields))))
    glyphs = dict(zip(fields, np.zeros(len(fields))))
    for field in fields:
        sources[field] = ColumnDataSource(data=dict(x=data[x_field], y=data[field]))
        glyphs[field] = Line(x="x", y="y", line_color="blue", line_width=2)
    return sources, glyphs
예제 #15
0
    def __init__(self,
                 car_width=0.1,
                 car_height=0.05,
                 rod_length=0.5,
                 pendulum_size=0.05):
        self.car_width = car_width
        self.car_height = car_height

        self.rod_length = rod_length
        self.pendulum_size = pendulum_size

        self.pendulum = GlyphRenderer(data_source=ColumnDataSource(
            dict(x=[0], y=[0])),
                                      glyph=Ellipse(x='x',
                                                    y='y',
                                                    width=self.pendulum_size,
                                                    height=self.pendulum_size))

        self.car = GlyphRenderer(data_source=ColumnDataSource(
            dict(x=[0], y=[0])),
                                 glyph=Rect(x='x',
                                            y='y',
                                            width=self.car_width,
                                            height=self.car_height))

        self.rod = GlyphRenderer(data_source=ColumnDataSource(
            dict(x=[0, 0], y=[0, 0])),
                                 glyph=Line(x='x', y='y', line_width=2))

        self.move = GlyphRenderer(data_source=ColumnDataSource(
            dict(x=deque([0, 1], maxlen=200), y=deque([0, 1], maxlen=200))),
                                  glyph=Ellipse(x='x',
                                                y='y',
                                                width=0.008,
                                                height=0.008,
                                                fill_alpha=0.25,
                                                line_alpha=0.0,
                                                fill_color="#cc0000"))

        self.ground = GlyphRenderer(data_source=ColumnDataSource(
            dict(x=[-100, 100], y=[-car_height / 2, -car_height / 2])),
                                    glyph=Line(x='x',
                                               y='y',
                                               line_width=1,
                                               line_alpha=0.5))
예제 #16
0
def test_Line():
    glyph = Line()
    assert glyph.x is None
    assert glyph.y is None
    yield check_line, glyph
    yield (check_props, glyph, [
        "x",
        "y",
    ], LINE)
예제 #17
0
def test_Line():
    glyph = Line()
    assert glyph.x == "x"
    assert glyph.y == "y"
    yield check_line, glyph
    yield (check_props, glyph, [
        "x",
        "y",
    ], LINE)
예제 #18
0
def test_Line() -> None:
    glyph = Line()
    assert glyph.x == field("x")
    assert glyph.y == field("y")
    check_line_properties(glyph)
    check_properties_existence(glyph, [
        "x",
        "y",
    ], LINE, GLYPH)
예제 #19
0
def test_Line():
    glyph = Line()
    assert glyph.x is None
    assert glyph.y is None
    yield check_line_properties, glyph
    yield (check_properties_existence, glyph, [
        "x",
        "y",
    ], LINE, GLYPH)
예제 #20
0
def test_Line():
    glyph = Line()
    assert glyph.x is None
    assert glyph.y is None
    check_line_properties(glyph)
    check_properties_existence(glyph, [
        "x",
        "y",
    ], LINE, GLYPH)
def make_plot(sizing_mode):
    plot = Plot(x_range=DataRange1d(),
                y_range=DataRange1d(),
                toolbar_location=None,
                sizing_mode=sizing_mode)
    plot.add_glyph(source, Line(x="x", y="y1"))
    plot.add_layout(LinearAxis(), 'below')
    plot.add_layout(LinearAxis(), 'left')
    return plot
예제 #22
0
def multiline2():
  xData={
    "a":[2,5,6,8,9,4,1,10,7,3]
  }
  x=[2,5,6,8,9,4,1,10,7,3]
  ya=[5,2,4,8,3,4,8,3,4,6]
  yb=[4,1,3,7,2,3,7,2,3,5]
  data=ColumnDataSource(data={'x':x,'ya':ya,'yb':yb})
  p=figure(title = "multiline", sizing_mode="fixed", plot_width=600, plot_height=400,tools='pan,wheel_zoom,box_zoom,save,reset')
  p.toolbar.logo=None
  from bokeh.models import LinearColorMapper
  from bokeh.models.glyphs import Line,Circle
  from bokeh.palettes import inferno,YlOrRd,Magma,PuBu,Greys
  from bokeh.transform import transform
  #p.vline_stack(['y1','y2'],x='x',source=data)
  l1=Line(x='x',y='yb',line_color='red',line_width=2)
  l2=Circle(x='x',y='ya',fill_color='blue',fill_alpha=0.4,size=7)
  r1=p.add_glyph(data,l1,name='predict')
  r2=p.add_glyph(data,l2,name='real')

  p.add_tools(
    HoverTool(tooltips = [('X,Y_real', '@x,@ya')],names=['real'])
  )
  p.add_tools(
    HoverTool(tooltips = [('X,Y_predict', '@x,@yb')],names=['predict'])
  )
  from bokeh.models import Button
  from bokeh import events
  callback = CustomJS(args=dict(source=data), code="""
          var data = source.data;
          let newList = [];
          for(var i=0;i<data['x'].length;i++){
            newList.push({
              value1: data['x'][i],
              value2: data['ya'][i],
              value3: data['yb'][i]
            })
          }
          console.log(newList)
          newList.sort(function(a,b) {
            return ((a.value1 - b.value1))
          })
          console.log(newList)
          for(var i=0;i<newList.length;i++){
            data['x'][i]=newList[i].value1
            data['ya'][i]=newList[i].value2
            data['yb'][i]=newList[i].value3
          }
          console.log(data)
          source.change.emit();
      """)

  dp = Button(label="sort")
  dp.js_on_event(events.ButtonClick, callback)
  layout = column(dp, p)
  return json.dumps(json_item(layout))
예제 #23
0
파일: grid.py 프로젝트: wesboben/bokeh
def make_plot(source, xname, yname, line_color):
    plot = Plot(min_border=50)

    plot.add_layout(LinearAxis(), 'below')
    plot.add_layout(LinearAxis(), 'left')

    plot.add_glyph(source, Line(x=xname, y=yname, line_color=line_color))

    plot.add_tools(PanTool(), WheelZoomTool())

    return plot
예제 #24
0
def population():
    xdr = FactorRange(factors=years)
    ydr = DataRange1d()
    x_scale = CategoricalScale()

    plot = Plot(x_range=xdr, y_range=ydr, x_scale=x_scale, plot_width=600, plot_height=150, toolbar_location=None)

    plot.add_layout(CategoricalAxis(major_label_orientation=pi / 4), 'below')

    known = Line(x="x", y="y", line_color="violet", line_width=2)
    known_glyph = plot.add_glyph(source_known, known)

    predicted = Line(x="x", y="y", line_color="violet", line_width=2, line_dash="dashed")
    predicted_glyph = plot.add_glyph(source_predicted, predicted)

    legend = Legend(location="bottom_right",
                    items=[("known", [known_glyph]), ("predicted", [predicted_glyph])])
    plot.add_layout(legend)

    return plot
    def generate_plots(self, doc):
        self.hist_plot = {}
        get_score_by_simulation(self.total_pandas_df, self.sq_err_names)
        self.hist_plot['plotting_data'] = np.array(
            self.total_pandas_df['score'])
        self.hist_plot['plot_width'] = 1000
        self.hist_plot['plot_height'] = 500
        self.hist_plot['title'] = 'Simulation Score Histogram'

        self.hist_plot['object_figure'] = figure(
            width=self.hist_plot['plot_width'],
            height=self.hist_plot['plot_height'],
            title=self.hist_plot['title'])

        self.hist_plot['source'] = ColumnDataSource(
            data=dict(hist=[], left_edge=[], right_edge=[]))
        self.hist_plot['pdf_source'] = ColumnDataSource(
            data=dict(x=[], y_pdf=[]))

        # get stats and gaus fit
        gauss_dict = gaussian_fit(name='score', total_df=self.total_pandas_df)
        hist = gauss_dict['hist']
        edges = gauss_dict['edges']
        x = gauss_dict['x']
        pdf = gauss_dict['pdf']

        self.hist_plot['source'].data = {
            'hist': hist,
            'left_edge': edges[:-1],
            'right_edge': edges[1:]
        }
        self.hist_plot['pdf_source'].data = {'x': x, 'y_pdf': pdf}

        self.hist_plot['quad_glyph'] = Quad(top='hist',
                                            bottom=0,
                                            left='left_edge',
                                            right='right_edge')
        self.hist_plot['pdf_glyph'] = Line(x='x',
                                           y='y_pdf',
                                           line_color="#D95B43",
                                           line_width=8,
                                           line_alpha=0.7)

        self.hist_plot['object_figure'].add_glyph(self.hist_plot['source'],
                                                  self.hist_plot['quad_glyph'])
        self.hist_plot['object_figure'].add_glyph(self.hist_plot['pdf_source'],
                                                  self.hist_plot['pdf_glyph'])

        self.hist_plot['object_figure'].yaxis.axis_label = 'Relative Frequency'
        self.hist_plot['object_figure'].xaxis.axis_label = 'Simulation Score'

        doc.add_root(self.hist_plot['object_figure'])
        self.write_text_file()
예제 #26
0
def population():
    xdr = FactorRange(factors=years)
    ydr = DataRange1d()

    plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=800, plot_height=200)

    plot.add_layout(CategoricalAxis(major_label_orientation=pi/4), 'below')

    line_known = Line(x="x", y="y", line_color="violet", line_width=2)
    line_known_glyph = plot.add_glyph(source_known, line_known)

    line_predicted = Line(x="x", y="y", line_color="violet", line_width=2, line_dash="dashed")
    line_predicted_glyph = plot.add_glyph(source_predicted, line_predicted)

    plot.add_layout(
        Legend(
            orientation="bottom_right",
            legends=[("known", [line_known_glyph]), ("predicted", [line_predicted_glyph])],
        )
    )

    return plot
예제 #27
0
def large_plot(n):
    from bokeh.models import (
        Plot, LinearAxis, Grid, GlyphRenderer,
        ColumnDataSource, DataRange1d, PanTool, ZoomInTool, ZoomOutTool, WheelZoomTool, BoxZoomTool,
        BoxSelectTool, SaveTool, ResetTool
    )
    from bokeh.models.layouts import Column
    from bokeh.models.glyphs import Line

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

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

    return col, objects
예제 #28
0
    def __init__(self,
                 body_width=0.5,
                 body_height=0.25,
                 num_bodies=2,
                 body_distance=1.0):
        self.body_width = body_width
        self.body_height = body_height
        self.num_bodies = num_bodies
        self.rod_colors = viridis(51)
        self.body_distance = body_distance

        self.bodies = []
        self.rods = []

        for _ in range(num_bodies):
            self.bodies.append(
                GlyphRenderer(data_source=ColumnDataSource(dict(x=[0], y=[0])),
                              glyph=Rect(x='x',
                                         y='y',
                                         width=self.body_height,
                                         height=self.body_width)))

        for _ in range(num_bodies - 1):
            self.rods.append(
                GlyphRenderer(data_source=ColumnDataSource(
                    dict(x=[0, 0], y=[0, 0])),
                              glyph=Line(x='x',
                                         y='y',
                                         line_width=2,
                                         line_color=self.rod_colors[0])))

        self.ground = GlyphRenderer(data_source=ColumnDataSource(
            dict(x=[-100, 100],
                 y=[-self.body_height / 2, -self.body_height / 2])),
                                    glyph=Line(x='x',
                                               y='y',
                                               line_width=1,
                                               line_alpha=0.5))
예제 #29
0
        def generate_histogram():
            nonlocal hist_plot
            hist_plot['plotting_data'] = np.array(
                data_handler.total_df[self.select_widget_hist.value])
            hist_plot['plot_width'] = 610
            hist_plot['plot_height'] = 400
            hist_plot[
                'title'] = 'Gaussian Fit of ' + self.select_widget_hist.value

            hist_plot['object_figure'] = figure(
                width=hist_plot['plot_width'],
                height=hist_plot['plot_height'],
                title=hist_plot['title'])

            hist_plot['source'] = ColumnDataSource(
                data=dict(hist=[], left_edge=[], right_edge=[]))
            hist_plot['pdf_source'] = ColumnDataSource(
                data=dict(x=[], y_pdf=[]))
            # get stats and gaus fit
            data_handler.general_stats(self.select_widget_hist.value, None)
            data_handler.gaussian_fit(
                data_handler.total_df[self.select_widget_hist.value],
                data_handler.mu, data_handler.sigma,
                min(data_handler.total_df[self.select_widget_hist.value]),
                max(data_handler.total_df[self.select_widget_hist.value]))

            hist_plot['source'].data = {
                'hist': data_handler.hist,
                'left_edge': data_handler.edges[:-1],
                'right_edge': data_handler.edges[1:]
            }
            hist_plot['pdf_source'].data = {
                'x': data_handler.x,
                'y_pdf': data_handler.pdf
            }

            hist_plot['quad_glyph'] = Quad(top='hist',
                                           bottom=0,
                                           left='left_edge',
                                           right='right_edge')
            hist_plot['pdf_glyph'] = Line(x='x',
                                          y='y_pdf',
                                          line_color="#D95B43",
                                          line_width=8,
                                          line_alpha=0.7)

            hist_plot['object_figure'].add_glyph(hist_plot['source'],
                                                 hist_plot['quad_glyph'])
            hist_plot['object_figure'].add_glyph(hist_plot['pdf_source'],
                                                 hist_plot['pdf_glyph'])
    def create_plot(self):

        # plot either last 500 or last x datapoints
        if self.steps_np.shape[0] >= self.width:
            start_index = self.width
        else:
            start_index = self.steps_np.shape[0] - 1

        # create figure: set the xrange to only show last start_index datapoints
        self.plot = figure(
            plot_height=250,
            plot_width=1000,
            x_range=(
                self.steps_np[-start_index, 0] - self.start,
                self.steps_np[-1, 0] - self.start,
            ),
            tools="crosshair,pan,reset,save,wheel_zoom",
        )

        # create line chart for step duration
        self.source = ColumnDataSource(
            data=dict(
                x=self.steps_np[:, 0] - self.start,
                y=self.steps_np[:, 1],
                step=self.steps_np[:, 2],
                metric=self.metric_names,
            )
        )
        line = Line(x="x", y="y", line_color="blue")

        # tooltip
        hover = HoverTool(
            tooltips=[
                ("index", "$index"),
                ("step", "@step"),
                ("metric", "@metric"),
                ("(x,y)", "($x, $y)"),
            ]
        )

        # create plot
        self.plot.add_tools(hover)
        self.plot.add_glyph(self.source, line)
        self.plot.xaxis.axis_label = "Time in ms"
        self.plot.yaxis.axis_label = "Step duration in ms"
        self.plot.xgrid.visible = False
        self.plot.ygrid.visible = False

        # show
        self.target = show(self.plot, notebook_handle=True)