Пример #1
0
def legend():
    # Set ranges
    xdr = Range1d(0, 100)
    ydr = Range1d(0, 500)
    # Create plot
    plot = Plot(
        x_range=xdr,
        y_range=ydr,
        title="",
        plot_width=500,
        plot_height=500,
        min_border=0,
        toolbar_location=None,
        outline_line_color="#FFFFFF",
    )

    # For each color in your palette, add a Rect glyph to the plot with the appropriate properties
    palette = RdBu11
    width = 40
    for i, color in enumerate(palette):
        rect = Rect(x=40,
                    y=(width * (i + 1)),
                    width=width,
                    height=40,
                    fill_color=color,
                    line_color='black')
        plot.add_glyph(rect)

    # Add text labels and add them to the plot
    minimum = Text(x=50, y=0, text=['-6 ºC'])
    plot.add_glyph(minimum)
    maximum = Text(x=50, y=460, text=['6 ºC'])
    plot.add_glyph(maximum)

    return plot
Пример #2
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
	def createMainEmojiWindow(self):
		plot = figure(title="", plot_width=self.keyboardWidth, plot_height=self.keyboardHeight,
			x_range= (-.5,10-.5),y_range = (0,3*self.keyboardYSpacing),
		    h_symmetry=False, v_symmetry=False, min_border=0,
		    toolbar_location=None,tools = "")

		plot.grid.visible = False
		plot.axis.visible = False

		emojiGlyph = Text(x="x", y="y", text="text", angle=0, 
			text_color="black",text_alpha = 1,text_font_size='65pt',text_align = "center")

		source = self.createKeyboardCoordinates()

		plot.add_glyph(source, emojiGlyph,name = "emojis")

		circleGlyph = Circle(x="x", y="y",radius=.5,fill_alpha = 0,line_alpha = 0)
		circGlypher = plot.add_glyph(source, circleGlyph)

		emojiLetterText =  Text(x="x", y="y", text="letters", angle=0,y_offset=-80,x_offset= -40,
			text_color="black",text_alpha = 1,
			text_font_size='20pt',text_align = "center")
		plot.add_glyph(source,emojiLetterText)

		hoverer = HoverTool(renderers=[circGlypher], tooltips=self.TOOLTIPS)
		plot.add_tools(hoverer)

		plot.on_event(Tap,self.emojiTapCallback)
		# plot.on_event(DoubleTap,self.emojiDoubleTapCallback)

		return plot
Пример #4
0
 def polyLine(self, figure):
     self.source_polyline = ColumnDataSource(data.EMPTY)
     render_line = figure.multi_line(xs="xs",
                                     ys="ys",
                                     source=self.source_polyline,
                                     alpha=0.3,
                                     color="red",
                                     level="overlay")
     text = Text(x="xs",
                 y="ys",
                 text=value("abc"),
                 text_color="red",
                 text_font_size="12pt")
     render_line1 = figure.add_glyph(self.source_polyline, text)
     tool2 = FreehandDrawTool(renderers=[render_line], )
     self.source_polyline.js_on_change(
         'data',
         bokeh.models.CustomJS(args=dict(datasource=render_line.data_source,
                                         starting_font_size="30px",
                                         figure=figure,
                                         starting_colour="red",
                                         text=Text()),
                               code="""
         console.log(datasource.data);
             """))
     return tool2
Пример #5
0
def make_plot(title='Forecasts'):
    '''
    # Generates the axes and background for the data to be plot on
    #
    :param title:
    :return:
    '''
    plot = figure(plot_height=500, plot_width=500, tools=["pan,reset,save, wheel_zoom", hover],
                     x_range=[-4, 4], y_range=[-4, 4])

    plot.title.text = title

    # Mark the 8 sectors
    x = 4
    y = 0.707107
    linewidth = 0.25
    plot.line([-x, -y], [-x, -y], line_width=0.5, line_alpha=0.6)
    plot.line([y, x], [y, x], line_width=0.5, line_alpha=0.6)
    plot.line([-x, -y], [x, y], line_width=0.5, line_alpha=0.6)
    plot.line([y, x], [-y, -x], line_width=0.5, line_alpha=0.6)
    plot.line([-x, -1], [0, 0], line_width=0.5, line_alpha=0.6)
    plot.line([1, x], [0, 0], line_width=0.5, line_alpha=0.6)
    plot.line([0, 0], [-x, -1], line_width=0.5, line_alpha=0.6)
    plot.line([0, 0], [1, x], line_width=0.5, line_alpha=0.6)

    xt, yt = 3., 1.5
    phase_marker_source = ColumnDataSource(data=dict(xt=[-xt, -yt, yt, xt, xt, yt, -yt, -xt],
                                                     yt=[-yt, -xt, -xt, -yt, yt, xt, xt, yt],
                                                     phase_labels=[str(i) for i in range(1, 9)]))
    labels = LabelSet(x='xt', y='yt', text='phase_labels', level='glyph',
                      x_offset=0, y_offset=0, source=phase_marker_source,
                      render_mode='canvas', text_color='grey', text_font_size="30pt", text_alpha=0.25)
    plot.add_layout(labels)
    plot.circle([0], [0], radius=1, color="white", line_color='grey', alpha=0.6)

    phase_name_source = ColumnDataSource(dict(x=[0, 0], y=[-3.75, 3.], text=['Indian \n Ocean', 'Western \n Pacific']))
    glyph = Text(x="x", y="y", text="text", angle=0., text_color="grey", text_align='center', text_alpha=0.25)
    plot.add_glyph(phase_name_source, glyph)

    phase_name_source = ColumnDataSource(dict(x=[-3.], y=[0], text=['West. Hem\n Africa']))
    glyph = Text(x="x", y="y", text="text", angle=np.pi / 2., text_color="grey", text_align='center', text_alpha=0.25)
    plot.add_glyph(phase_name_source, glyph)

    phase_name_source = ColumnDataSource(dict(x=[3.], y=[0], text=['Maritime\n continent']))
    glyph = Text(x="x", y="y", text="text", angle=-np.pi / 2., text_color="grey", text_align='center', text_alpha=0.25)
    plot.add_glyph(phase_name_source, glyph)

    plot.xaxis[0].axis_label = 'RMM1'
    plot.yaxis[0].axis_label = 'RMM2'

    return plot
	def createEmojiFigure(self,figureType,name):
		#creates either a row or column to display emojies in
		numCategories = 10
		if figureType == "Column":
			height = self.colHeight
			width = self.colWidth
			xRange = (-.5,.5)
			yRange = (-.5,numCategories-.5)
			yOffset = 20

		else:
			height = self.rowHeight
			width = self.rowWidth
			xRange = (-.5,numCategories-.5)
			yRange = (-.4,.6)
			yOffset = 20

		categoriesFigure = figure(title = "Title",
			plot_height = height, plot_width = width,
			x_range=xRange,y_range=yRange,
			toolbar_location = None,tools = "")

		categoriesFigure.axis.visible = False
		categoriesFigure.grid.visible = False

		categorySourceDict = dict(x=[], y=[], text=[],names = [],fills = [],indices=[])

		# categorySourceDict = self.createCategoryGlyphSource(categoriesDict,figureType)
		categorySource = ColumnDataSource(categorySourceDict,name = name)

		#text glyph to display emojies
		categoriesGlyph = Text(x="x", y="y", text="text", angle=0,y_offset=yOffset,
			text_color="black",text_alpha = 1,
			text_font_size='35pt',text_align = "center")

		categoriesFigure.add_glyph(categorySource, categoriesGlyph)

		if figureType == "Row":
			categoryIndexText =  Text(x="x", y="y", text="indices", angle=0,y_offset=-10,x_offset= -50,
				text_color="black",text_alpha = 1,
				text_font_size='20pt',text_align = "center")
			categoriesFigure.add_glyph(categorySource,categoryIndexText)

		#hidden circle glyph used to allow hovertool to work to show tooltips
		categoryCircleGlyph = Circle(x="x", y="y",radius=.45,fill_alpha = 0,line_alpha = "fills")
		circleGlyph = categoriesFigure.add_glyph(categorySource, categoryCircleGlyph, name = "circles")
		#create hover tool and add it to figure
		categoryHoverer = HoverTool(renderers=[circleGlyph], tooltips=self.TOOLTIPS)
		categoriesFigure.add_tools(categoryHoverer)

		return categoriesFigure
def PowerLine(x_label,
              y_label,
              grid_space,
              title,
              name1,
              name2,
              minN,
              maxN,
              size,
              leyend,
              vertices,
              vertical=True):
    """Bokeh plot of Power joint with respect to the gait cycle, plus zero points detection"""
    f = figure(x_axis_label=x_label,
               y_axis_label=y_label,
               plot_width=grid_space,
               plot_height=grid_space,
               title=title)
    color = 0
    a = np.array(np.zeros(vertices))
    for diff in name2.columns[minN:maxN]:
        f.line(x=name1,
               y=name2[diff],
               color=Spectral6[color],
               line_width=size,
               legend=diff)
        color += 1
        asign = np.sign(name2[diff][0:])  # To detect signs of numbers
        signchange = ((np.roll(asign, 1) - asign) != 0).astype(
            int)  # To detect the change of signs
        j, = np.where(
            signchange == 1)  # To detect the position where sign changes
        try:
            a = np.vstack((a, j[:vertices]))
        except ValueError:
            print(
                "The number of times in which the data cross zeros is less than the number of vertices especified in %s"
                % diff)
            j1 = np.zeros(vertices - j.shape[0])
            j = np.append(j, j1)
            a = np.vstack((a, j))
    if vertical:
        instances = ColumnDataSource(
            dict(x=[-5, 15, 45, 75],
                 y=np.ones(4) * 1.5,
                 text=["Heel Strike", "Roll Over", "Push Off", "Swing"]))
        prom = np.true_divide(a.sum(0), (a != 0).sum(0))
        for i in np.true_divide(a[1:, 1:].sum(0), (a[1:, 1:] != 0).sum(0)):
            f.ray(x=i,
                  y=-1,
                  length=100,
                  angle=1.57079633,
                  color=Spectral6[color],
                  line_dash="4 4"
                  )  ## np.true_divide excludes 0 values to do the average
        glyph = Text(x="x", y="y", text="text", angle=0.0, text_color="black")
        f.add_glyph(instances, glyph)
        a = np.vstack((a, prom))
    f.legend.location = leyend
    return f, a[1:, 1:].astype(int)
Пример #8
0
def plot_sequence(seq,
                  plot_width=1000,
                  plot_height=20,
                  fontsize='10pt',
                  xaxis=True,
                  tools=""):
    """Plot a single sequence.

    Args:
        seq: sequence to plot, a string
        xaxis: display x-axis tick labels or not
        tools: which bokeh tools to display, if needed
    """

    if seq is None or len(seq) == 0:
        return plotters.plot_empty('no sequence',
                                   plot_width=plot_width,
                                   plot_height=plot_height)
    text = list(seq)
    N = len(seq)
    x = np.array(range(N)) + 1

    colors = utils.get_sequence_colors([seq])
    source = ColumnDataSource(dict(x=x, text=text, colors=colors))
    x_range = Range1d(0, N, bounds='auto')
    p = figure(plot_width=plot_width,
               plot_height=plot_height,
               x_range=x_range,
               y_range=(0, 1),
               tools=tools,
               min_border=0,
               toolbar_location='below')
    rects = Rect(x="x",
                 y=0,
                 width=1,
                 height=2,
                 fill_color="colors",
                 line_color=None,
                 fill_alpha=0.4)
    p.add_glyph(source, rects)
    if len(seq) < 200:
        glyph = Text(x="x",
                     y=0,
                     text="text",
                     text_align='center',
                     text_color="black",
                     text_font="monospace",
                     text_font_size=fontsize)
        p.add_glyph(source, glyph)
    p.grid.visible = False
    if xaxis == False:
        p.xaxis.visible = False
    else:
        if plot_height < 40:
            p.plot_height = 50
        if tools != "":
            p.plot_height = 70
    p.yaxis.visible = False
    p.toolbar.logo = None
    return p
Пример #9
0
def plot(a):
    panels = a.rotated_panel_positions
    x = [x['x'] for x in panels]
    y = [x['y'] for x in panels]
    ids = [x['panelId'] for x in panels]
    angles = [x['o'] for x in panels]

    pad_x = (max(x) - min(x)) * .1
    pad_y = (max(y) - min(y)) * .1
    output_file('plot.html')
    plot = figure(x_range=(min(x) - pad_x, max(x) + pad_x),
                  y_range=(min(y) - pad_y, max(y) + pad_y))
    source = ColumnDataSource(dict(x=x, y=y, text=ids))
    plot.triangle(x,
                  y,
                  angle=angles,
                  angle_units='deg',
                  size=70,
                  color='#cccccc',
                  fill_color=None,
                  line_width=4)
    glyph = Text(x='x',
                 y='y',
                 text='text',
                 angle=0,
                 text_align='center',
                 text_color='#FF0000')
    plot.add_glyph(source, glyph)
    show(plot)
Пример #10
0
def plot_demo():
    p = figure(plot_width=600,
               plot_height=600,
               tools=['box_zoom', 'reset', 'pan'],
               title="",
               x_range=(-0.6, 0.6),
               y_range=(-0.6, 0.6))
    source = ColumnDataSource(
        data=dict(x=Y[:, 0],
                  y=Y[:, 1],
                  color=[
                      'orange', 'orange', 'orange', 'green', 'green', 'green',
                      'blue', 'blue', 'blue'
                  ],
                  names=mydemo))
    p.circle('x',
             'y',
             color='color',
             size=20,
             source=source,
             fill_alpha=0.4,
             line_color=None)
    p.xaxis[0].axis_label = 'Dimension 1'
    p.yaxis[0].axis_label = 'Dimension 2'
    glyph = Text(x="x",
                 y="y",
                 text="names",
                 angle=0.5,
                 text_color="#1a3c72",
                 text_font_size="1.5em")
    p.add_glyph(source, glyph)
    return p
Пример #11
0
    def create_network_plot(self, nodes_source, title='', width=800):
        plot = figure(plot_width=width,
                      plot_height=700,
                      tools=['tap', 'box_zoom', 'reset', 'pan', 'wheel_zoom'],
                      title=title)
        plot.title.text_font = "helvica"
        plot.title.text_font_style = "bold"
        plot.title.text_font_size = "20px"
        plot.background_fill_color = "beige"
        plot.background_fill_alpha = 0.2
        g1 = Circle(x='x', y='y', size=2, fill_color='blue')
        g1_r = plot.add_glyph(source_or_glyph=nodes_source, glyph=g1)
        g1_hover = HoverTool(renderers=[g1_r],
                             tooltips=[('name', '@name'),
                                       ('count', '@counts')])
        glyph_text = Text(x="x",
                          y="y",
                          text="name",
                          text_color="#ff4a4a",
                          text_font_size='6pt',
                          text_alpha=0.7)

        plot.add_glyph(nodes_source, glyph_text)
        plot.add_tools(g1_hover)
        plot.grid.grid_line_color = None
        plot.axis.visible = False
        return plot, g1_r, glyph_text
Пример #12
0
def make_plot(xname, yname, xax=False, yax=False, text=None):
    plot = Plot(x_range=xdr,
                y_range=ydr,
                background_fill_color="#efe8e2",
                border_fill_color='white',
                title="",
                min_border=2,
                h_symmetry=False,
                v_symmetry=False,
                plot_width=250,
                plot_height=250)

    circle = Circle(x=xname,
                    y=yname,
                    fill_color="color",
                    fill_alpha=0.2,
                    size=4,
                    line_color="color")
    r = plot.add_glyph(source, circle)

    xdr.renderers.append(r)
    ydr.renderers.append(r)

    xticker = BasicTicker()
    if xax:
        xaxis = LinearAxis()
        plot.add_layout(xaxis, 'below')
        xticker = xaxis.ticker
    plot.add_layout(Grid(dimension=0, ticker=xticker))

    yticker = BasicTicker()
    if yax:
        yaxis = LinearAxis()
        plot.add_layout(yaxis, 'left')
        yticker = yaxis.ticker
    plot.add_layout(Grid(dimension=1, ticker=yticker))

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

    if text:
        text = " ".join(text.split('_'))
        text = Text(x={
            'field': 'xcenter',
            'units': 'screen'
        },
                    y={
                        'field': 'ycenter',
                        'units': 'screen'
                    },
                    text=[text],
                    angle=pi / 4,
                    text_font_style="bold",
                    text_baseline="top",
                    text_color="#ffaaaa",
                    text_alpha=0.7,
                    text_align="center",
                    text_font_size="28pt")
        plot.add_glyph(text_source, text)

    return plot
Пример #13
0
def test_Text():
    glyph = Text()
    assert glyph.x == "x"
    assert glyph.y == "y"
    assert glyph.text == "text"
    assert glyph.angle == "angle"
    yield check_text, glyph
    yield check_props, glyph, ["x", "y", "text", "angle"], TEXT
Пример #14
0
def test_Text():
    glyph = Text()
    assert glyph.x is None
    assert glyph.y is None
    assert glyph.text == "text"
    assert glyph.angle == 0
    yield check_text_properties, glyph
    yield (check_properties_existence, glyph,
           ["x", "y", "text", "angle", "angle_units", "x_offset",
            "y_offset"], TEXT, GLYPH)
Пример #15
0
def test_Text():
    glyph = Text()
    assert glyph.x == "x"
    assert glyph.y == "y"
    assert glyph.text == "text"
    assert glyph.angle == 0
    yield check_text, glyph
    yield (check_props, glyph,
           ["x", "y", "text", "angle", "angle_units", "x_offset",
            "y_offset"], TEXT)
 def st_RHS_plotting(self):
     """
     Plot the drag factors on a sharp cornered rectanglar exposed member
     """
     plot = Plot(title=None, match_aspect=True)
     glyph = Rect(x=0,
                  y=0,
                  width=self.d,
                  height=self.b,
                  fill_color="#cab2d6")
     plot.add_glyph(glyph)
     plot.add_layout(
         Arrow(end=NormalHead(fill_color="orange"),
               x_start=0,
               y_start=self.b / 4,
               x_end=0,
               y_end=self.b / 2))
     plot.add_layout(
         Arrow(end=NormalHead(fill_color="orange"),
               x_start=-self.d / 2,
               y_start=0,
               x_end=-self.d / 4,
               y_end=0))
     plot.add_layout(LinearAxis(), 'below')
     plot.add_layout(LinearAxis(), 'left')
     plot.add_glyph(
         Text(
             x=0,
             y=self.b / 2,
             text=[
                 f"Cf_y = {self.Cf_y:.2f}\nsigma_wind = {self.sigma_wind_vert/1000:.2f} kPa"
             ],
             text_align="left"))
     plot.add_glyph(
         Text(
             x=-self.d / 4,
             y=0,
             text=[
                 f"Cf_x = {self.Cf_x:.2f}\nsigma_wind = {self.sigma_wind_horiz/1000:.2f} kPa"
             ],
             text_align="left"))
     return plot
Пример #17
0
def test_Text() -> None:
    glyph = Text()
    assert glyph.x == field("x")
    assert glyph.y == field("y")
    assert glyph.text == "text"
    assert glyph.angle == 0
    check_text_properties(glyph)
    check_properties_existence(
        glyph,
        ["x", "y", "text", "angle", "angle_units", "x_offset", "y_offset"],
        TEXT, GLYPH)
Пример #18
0
def generate_cluster_graph(dataframe):
    node_number = len(dataframe.columns)
    if node_number >= 150000:
        N = 40
        x = linspace(-2, 2, N)
        y = linspace(0,0, N)
        a = "Sorry, the dataset is too large to split"
        text = [a[i] for i in range(N)]
        source = ColumnDataSource(dict(x=x, y=y, text=text))
        plot = Plot(
            title=None, plot_width=600, plot_height=300,
            min_border=0, toolbar_location=None)

        glyph = Text(x="x", y="y", text="text", angle=0.1, text_color="#96deb3")
        plot.add_glyph(source, glyph)
        curdoc().add_root(plot)
        return plot
    else:
        cluster_n, counter, cluster_label_df = K_mean_cluster(dataframe)
        data = ColumnDataSource({"Label": list(counter.keys()), "Size": list(counter.values()),
                                 "circle_size": [item/10 + 10 for item in counter.values()],
                                 "color": [["olive","navy"][i%2] for i in counter.keys()]})

        data.selected.js_on_change('indices', CustomJS(args=dict(data=data), code="""
                let inds = cb_obj.indices;
                let labels = [];
                for (let i = 0; i < inds.length; i++){
                    let label = data.data.Label[inds[i]]
                    labels[i] = label
                }
                console.log(labels);
                $.post("/api/filter/clustering/choose/" + labels[0], function(response){
                    document.getElementById('start-tool-cluster').disabled = false;
                });
            """))

        TOOLTIPS = [
            ("Label", "@Label"),
            ("Number of nodes in this cluster", "@Size"),
        ]

        p = figure(plot_width=400, plot_height=300, tools=['wheel_zoom','box_zoom', 'hover','tap', 'reset'], tooltips=TOOLTIPS)
        p.circle("Label", "Label", size="circle_size", color="color", alpha=0.5, source=data)
        p.title.text_color = "olive"
        p.title.text_font = "times"
        p.title.text_font_style = "italic"

        p.background_fill_color = None
        p.border_fill_color = None
        p.outline_line_color = None
        #p.xaxis.visible = False
        p.yaxis.visible = False
        p.grid.visible = False
        return p
Пример #19
0
def add_gauge(radius, max_value, length, direction, color, major_step, minor_step):
    major_angles, minor_angles = [], []
    major_labels, minor_labels = [], []

    total_angle = start_angle - end_angle

    major_angle_step = float(major_step)/max_value*total_angle
    minor_angle_step = float(minor_step)/max_value*total_angle

    major_angle = 0

    while major_angle <= total_angle:
        major_angles.append(start_angle - major_angle)
        major_angle += major_angle_step

    minor_angle = 0

    while minor_angle <= total_angle:
        minor_angles.append(start_angle - minor_angle)
        minor_angle += minor_angle_step

    major_labels = [ major_step*i for i, _ in enumerate(major_angles) ]
    minor_labels = [ minor_step*i for i, _ in enumerate(minor_angles) ]

    n = major_step/minor_step
    minor_angles = [ x for i, x in enumerate(minor_angles) if i % n != 0 ]
    minor_labels = [ x for i, x in enumerate(minor_labels) if i % n != 0 ]

    glyph = Arc(x=0, y=0, radius=radius, start_angle=start_angle, end_angle=end_angle, direction="clock", line_color=color, line_width=2)
    plot.add_glyph(glyph)

    rotation = 0 if direction == 1 else -pi

    x, y = zip(*[ polar_to_cartesian(radius, angle) for angle in major_angles ])
    angles = [ angle + rotation for angle in major_angles ]
    source = ColumnDataSource(dict(x=x, y=y, angle=angles))

    glyph = Ray(x="x", y="y", length=data(length), angle="angle", line_color=color, line_width=2)
    plot.add_glyph(source, glyph)

    x, y = zip(*[ polar_to_cartesian(radius, angle) for angle in minor_angles ])
    angles = [ angle + rotation for angle in minor_angles ]
    source = ColumnDataSource(dict(x=x, y=y, angle=angles))

    glyph = Ray(x="x", y="y", length=data(length/2), angle="angle", line_color=color, line_width=1)
    plot.add_glyph(source, glyph)

    x, y = zip(*[ polar_to_cartesian(radius+2*length*direction, angle) for angle in major_angles ])
    text_angles = [ angle - pi/2 for angle in major_angles ]
    source = ColumnDataSource(dict(x=x, y=y, angle=text_angles, text=major_labels))

    glyph = Text(x="x", y="y", angle="angle", text="text", text_align="center", text_baseline="middle")
    plot.add_glyph(source, glyph)
Пример #20
0
    def make_bar_plot(self):
        # create a new plot
        x_rr = Range1d(start=0.0, end=6.0)
        y_rr = Range1d(start=0.0, end=10.0)
        TOOLS = "box_select,lasso_select"
        bar_plot = figure(tools=TOOLS,
                          width=400,
                          height=350,
                          x_range=x_rr,
                          y_range=y_rr,
                          title="Average Rating")

        #x's and y's based on selected_df
        sdf = self.selected_df[['names', 'ratings']]

        xvals = [1.0 * i + 0.5 for i in range(0, len(sdf['names']))]
        rightvals = [1.0 * i + 0.85 for i in range(0, len(sdf['names']))]
        ratings = [r for r in sdf['ratings']]
        bottoms = [0] * len(ratings)
        y_text = [y + 1.0 for y in ratings]
        all_names = [n for n in sdf['names']]

        print "all_names ", all_names

        #bar_plot.circle(xvals, ratings, size=12)
        bar_plot.quad(xvals, rightvals, ratings, bottoms, fill="teal")

        #glyph = Text(x=xvals, y=y_text, text=sdf['names'], angle=pi/4,
        #text_align="left", text_baseline="middle")

        glyphs = [
            Text(x=x,
                 y=y,
                 text=[n],
                 angle=pi / 4,
                 text_align="left",
                 text_baseline="middle")
            for x, y, n in zip(xvals, y_text, all_names)
        ]

        for g in glyphs:
            bar_plot.add_glyph(g)

        bar_plot.xaxis.major_tick_line_color = None
        bar_plot.xaxis.minor_tick_line_color = None
        #bar_plot.xaxis.major_tick_line_width = 3
        #bar_plot.xaxis.minor_tick_line_color = "orange"

        bar_plot.yaxis.minor_tick_line_color = None

        bar_plot.xgrid.grid_line_color = None
        bar_plot.ygrid.grid_line_color = None
        self.bar_plot = bar_plot
Пример #21
0
def plot_source(X, y, p):
    x_min, x_max = np.min(X, 0), np.max(X, 0)
    X = (X - x_min) / (x_max - x_min)
    colors = brewer["Spectral"][len(unique_classes)]
    for c in unique_classes:
        f = y == c
        source = ColumnDataSource(dict(x=X[:, 0][f], y=X[:, 1][f], text=y[f]))
        glyph = Text(x="x",
                     y="y",
                     text="text",
                     angle=0.3,
                     text_color=colors[c])
        p.add_glyph(source, glyph)
Пример #22
0
 def draw_text(scene: Plot, origin: tuple, text: str, font_size: int,
               font_family: str, color: tuple):
     source = ColumnDataSource(
         dict(x=[origin[0]], y=[origin[1]], text=[text]))
     glyph = Text(x="x",
                  y="y",
                  text="text",
                  text_color='#{0:02x}{1:02x}{2:02x}'.format(*color),
                  text_font_size=str(font_size) + "pt",
                  text_font=font_family)
     # TODO: Here was TextToken (must align to left)
     scene.add_glyph(source, glyph)
     return MPLRenderer.get_text_width(text, font_size, font_family)
Пример #23
0
 def PowerLine(self,
               name1,
               name2,
               vertices,
               x_label='Cycle (Percent.)',
               y_label='Power (W/kg)',
               grid_space=450,
               title='Power cycle plot at the joint',
               minN=None,
               maxN=None,
               size=2,
               leyend='top_left',
               vertical=True,
               text=False):
     """Bokeh plot of Power joint with respect to the gait cycle, plus zero points detection"""
     f = figure(x_axis_label=x_label,
                y_axis_label=y_label,
                plot_width=grid_space,
                plot_height=grid_space,
                title=title)
     color = 0
     for diff in name1.columns[minN:maxN]:
         f.line(x=name2,
                y=name1[diff],
                color=Spectral6[color],
                line_width=size,
                legend=diff)
         if vertical:
             for i in vertices:
                 f.ray(x=i,
                       y=-1.5,
                       length=100,
                       angle=1.57079633,
                       color=Pastel2[8][color],
                       line_dash="4 4")
         if text:
             instances = ColumnDataSource(
                 dict(
                     x=[-5, 15, 45, 75],
                     y=np.ones(4) * 1.5,
                     text=["Heel Strike", "Roll Over", "Push Off",
                           "Swing"]))
             glyph = Text(x="x",
                          y="y",
                          text="text",
                          angle=0.0,
                          text_color="black")
             f.add_glyph(instances, glyph)
         color += 1
     f.legend.location = leyend
     return f
Пример #24
0
def make_healthscore_plot():

    layout = go.Layout(margin=go.layout.Margin(
        l=0,  #left margin
        r=0,  #right margin
        b=0,  #bottom margin
        t=0,  #top margin
    ))

    data = pd.DataFrame(['Col', "Val"])
    data['Col'] = ['Healthy', 'Unhealthy']
    data['Val'] = [15.8, 84.2]
    data['Angle'] = data['Val'] / data['Val'].sum() * 2 * pi
    data['color'] = ["olivedrab", "lightgrey"]
    txt = ['Health Score \n     84.2%', 'Health Score \n     84.2%']

    src = ColumnDataSource(
        data=dict(color=data['color'], angle=data['Angle'], text=txt))
    p = figure(plot_height=370,
               x_range=(-.35, .55),
               background_fill_color=None)

    glyph = Text(x=0,
                 y=1,
                 x_offset=-65,
                 y_offset=35,
                 text="text",
                 text_font_size="18pt",
                 text_color="#707070")

    p.annular_wedge(x=0,
                    y=1,
                    inner_radius=0.15,
                    outer_radius=0.25,
                    direction="clock",
                    start_angle=cumsum('angle', include_zero=True),
                    end_angle=cumsum('angle'),
                    line_color="white",
                    fill_color='color',
                    source=src)

    p.add_glyph(src, glyph)
    p.outline_line_color = None
    p.axis.axis_label = None
    p.axis.visible = False
    p.grid.grid_line_color = None
    p.background_fill_color = None

    return p
Пример #25
0
def gen_bokeh_plot():
    # retrieve current active symbol and data source
    data_source = DATA_STORE['data_source']
    title_source = DATA_STORE['title_source']

    # calculate mean absolute deviation (MAD)
    title = Title(text='Predicted vs Actual Market Open Price')

    plot = Plot(title=title,
                plot_width=1200,
                plot_height=800,
                h_symmetry=False,
                v_symmetry=False,
                min_border=0,
                toolbar_location='right')

    val_glyph = Line(x='date',
                     y='val_open',
                     line_color='black',
                     line_width=1.5)
    pred_glyph = Line(x='date',
                      y='pred_open',
                      line_color='blue',
                      line_width=1.5,
                      line_dash='dashed')
    plot.add_glyph(data_source, val_glyph)  # renderer 0
    plot.add_glyph(data_source, pred_glyph)  # renderer 1

    text_glyph = Text(x='x', y='y', text='text')
    plot.add_glyph(title_source, text_glyph)

    # Format plot
    li1 = LegendItem(label='actual', renderers=[plot.renderers[0]])
    li2 = LegendItem(label='predicted', renderers=[plot.renderers[1]])
    legend1 = Legend(items=[li1, li2], location='top_right')
    plot.add_layout(legend1)

    xaxis = DatetimeAxis()
    xaxis.formatter = DatetimeTickFormatter(years=['%Y'],
                                            months=['%m/%Y'],
                                            days=['%d/%m/%Y'])
    xaxis.major_label_orientation = np.pi / 4
    plot.add_layout(xaxis, 'below')

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

    return plot
Пример #26
0
def plot_tab(mytitle, Yin=None, notation=None, sizes=1):
    threshhold = 5
    titles, ind = fuzzy_find2(mytitle,
                              shelf=cat_books,
                              maxshow=8,
                              threshhold=5)
    links = cat_books['link'][ind]

    Dist = string_distance(titles + [mytitle], limit=5, placeholder=None)
    # 3. calculate Y
    Y = manifold.MDS(n_components= 2, n_init =  10, dissimilarity='precomputed')\
                     .fit_transform(Dist)
    # 4. get notation
    notation = titles + [mytitle]
    similarity = threshhold - Dist[-1, :]
    # plot
    p = figure(
        plot_width=500,
        plot_height=500,
        tools=["tap", 'box_zoom', 'reset', 'pan'],
        title="Book titles similar to \" " + mytitle + "\"",
    )
    source = ColumnDataSource(data=dict(x=Y[:, 0],
                                        y=Y[:, 1],
                                        color=['blue'] * len(titles) + ['red'],
                                        urls=list(links) + ['/'],
                                        names=notation))
    p.circle('x',
             'y',
             color='color',
             size=20,
             source=source,
             fill_alpha=0.4,
             line_color=None)
    p.xaxis[0].axis_label = 'Dimension 1'
    p.yaxis[0].axis_label = 'Dimension 2'
    glyph = Text(x="x",
                 y="y",
                 text="names",
                 angle=0.5,
                 text_color="#1a3c72",
                 text_font_size="1.5em")
    p.add_glyph(source, glyph)
    url = "@urls"
    taptool = p.select(type=TapTool)
    taptool.callback = OpenURL(url=url)
    return p
Пример #27
0
def create_village_map(survey):
    s = survey[["village_name", "_gps_point_latitude", "_gps_point_longitude"]]
    g = s.groupby("village_name")
    mean = g.agg([np.mean])
    mean = mean.reset_index()
    mean.columns = ['_'.join(col).strip() for col in mean.columns.values]
    mean.columns = ['vn', 'lat_mean', 'lon_mean']
    x_range = Range1d()
    y_range = Range1d()
    map_options = GMapOptions(lat=-2.588, lng=140.5170, zoom=11)
    plot = GMapPlot(x_range=x_range,
                    y_range=y_range,
                    map_options=map_options,
                    title="Lake Sentani")
    dot_source = ColumnDataSource(data=dict(
        lat=[float(x) for x in survey['_gps_point_latitude']],
        lon=[float(y) for y in survey['_gps_point_longitude']],
        uuid=[str(x) for x in survey['_uuid']],
        vName=[str(x) for x in survey['village_name']],
        size=[.0001 for x in survey['_uuid']],
    ))
    plot.map_options.map_type = "terrain"
    circle = Circle(x='lon',
                    y='lat',
                    radius='size',
                    fill_color='red',
                    fill_alpha=0.9)
    plot.add_glyph(dot_source, circle)
    text_source = ColumnDataSource(
        data=dict(vn=[str(x) for x in mean['vn']],
                  lat=[float(x) for x in mean['lat_mean']],
                  lon=[float(x) for x in mean['lon_mean']]))
    text = Text(x="lon", y="lat", text="vn", text_color="maroon")
    plot.add_glyph(text_source, text)
    reset = ResetTool()
    pan = PanTool()
    wheel_zoom = WheelZoomTool()
    box_zoom = BoxZoomTool()

    plot.add_tools(pan, wheel_zoom, box_zoom, reset)

    xaxis = LinearAxis(axis_label="lon.", major_tick_in=0)
    plot.add_layout(xaxis, 'below')
    yaxis = LinearAxis(axis_label="lat.", major_tick_in=0)
    plot.add_layout(yaxis, 'left')
    return plot
Пример #28
0
def mdsplot():
    xdr = DataRange1d(sources=[mdssource.columns("x")])
    ydr = DataRange1d(sources=[mdssource.columns("y")])

    title = "Intertopic Distance Map (via multidimensional scaling)"
    plot = Plot(title=title,
                title_text_font_size="16px",
                x_range=xdr,
                y_range=ydr,
                plot_width=mdswidth,
                plot_height=mdsheight)

    circle1 = Circle(x="x",
                     y="y",
                     radius=dict(field="r", units="screen"),
                     fill_color=base_color,
                     fill_alpha=0.2)
    circle2 = Circle(x="x",
                     y="y",
                     radius=dict(field="r", units="screen"),
                     fill_color=high_color,
                     fill_alpha=0.6)

    circles = GlyphRenderer(data_source=mdssource,
                            glyph=circle1,
                            selection_glyph=circle2,
                            nonselection_glyph=circle1)
    plot.renderers.append(circles)

    plot.add_glyph(
        mdssource,
        Text(x="x",
             y="y",
             text="text",
             text_font_style="bold",
             text_align="center",
             text_baseline="middle",
             text_font_size="11px"))

    plot.tools.append(TapTool(plot=plot, renderers=[circles]))

    #plot.add_layout(LinearAxis(axis_label="PC1"), "below")
    #plot.add_layout(LinearAxis(axis_label="PC2"), "left")

    return plot
Пример #29
0
    def yield_renderers(self):
        """Use the marker glyphs to display the arcs and beziers.
        Takes reference points from data loaded at the ColumnDataSource.
        """
        beziers = Bezier(x0='start_x',
                         y0='start_y',
                         x1='end_x',
                         y1='end_y',
                         cx0='cx0',
                         cy0='cy0',
                         cx1='cx1',
                         cy1='cy1',
                         line_alpha='weight',
                         line_color='colors')

        yield GlyphRenderer(data_source=self.connection_data, glyph=beziers)

        arcs = Arc(x=0,
                   y=0,
                   radius=1,
                   line_width=10,
                   start_angle='start_angle',
                   end_angle='end_angle',
                   line_color='line_color')

        yield GlyphRenderer(data_source=self.arcs_data, glyph=arcs)

        if self.label:

            text_props = {
                "text_color": "#000000",
                "text_font_size": "8pt",
                "text_align": "left",
                "text_baseline": "middle"
            }

            labels = Text(x='text_x',
                          y='text_y',
                          text='text',
                          angle='angles',
                          **text_props
                          )

            yield GlyphRenderer(data_source=self.text_data, glyph=labels)
Пример #30
0
    def create_forecast_status_charts(self):
        self.forecast_status_cds = ColumnDataSource(data={
            "x": [],
            "stage": [],
            "prediction": []
        })
        self.forecast_status_figure = figure(plot_width=400,
                                             plot_height=100,
                                             toolbar_location=None)
        self.forecast_status_figure.line(
            "x",
            "stage",
            source=self.forecast_status_cds,
            line_color="red",
            line_alpha=0.5,
        )
        self.forecast_status_figure.line("x",
                                         "prediction",
                                         source=self.forecast_status_cds,
                                         line_color="black")
        self.forecast_status_figure.axis.visible = False
        self.forecast_status_figure.xgrid.grid_line_color = None
        self.forecast_status_figure.ygrid.grid_line_color = None

        # figure for status
        self.status_text_cds = ColumnDataSource(data={
            "x": [0],
            "y": [0],
            "text": ["Calibration"]
        })
        self.status_text_figure = figure(plot_width=200,
                                         plot_height=100,
                                         toolbar_location=None)
        self.status_text_figure.axis.visible = False
        self.status_text_figure.xgrid.grid_line_color = None
        self.status_text_figure.ygrid.grid_line_color = None
        status_text = Text(x="x", y="y", text="text", text_color="black")
        self.status_text_figure.add_glyph(self.status_text_cds, status_text)

        self.update_button = Button(label="Start session")