예제 #1
0
def distribution():

    mu, sigma = 0, 0.5

    measured = np.random.normal(mu, sigma, 1000)
    hist, edges = np.histogram(measured, density=True, bins=20)

    x = np.linspace(-2, 2, 1000)
    pdf = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu) ** 2 / (2 * sigma ** 2))
    cdf = (1 + scipy.special.erf((x - mu) / np.sqrt(2 * sigma ** 2))) / 2

    output_server("distribution_reveal")

    hold()

    figure(title="Interactive plots",
           tools="pan, wheel_zoom, box_zoom, reset, previewsave",
           background_fill="#E5E5E5")
    quad(top=hist, bottom=np.zeros(len(hist)), left=edges[:-1], right=edges[1:],
         fill_color="#333333", line_color="#E5E5E5", line_width=3)

    # Use `line` renderers to display the PDF and CDF
    line(x, pdf, line_color="#348abd", line_width=8, alpha=0.7, legend="PDF")
    line(x, cdf, line_color="#7a68a6", line_width=8, alpha=0.7, legend="CDF")

    xgrid().grid_line_color = "white"
    xgrid().grid_line_width = 3
    ygrid().grid_line_color = "white"
    ygrid().grid_line_width = 3

    legend().orientation = "top_left"

    return curplot(), cursession()
예제 #2
0
def perf_std_discrete(ticks,
                      avgs,
                      stds,
                      legend=None,
                      std_width=0.3,
                      plot_width=1000,
                      plot_height=300,
                      color=BLUE,
                      alpha=1.0,
                      **kwargs):
    plotting.rect(ticks,
                  avgs, [std_width for _ in stds],
                  2 * np.array(stds),
                  line_color=None,
                  fill_color=color,
                  fill_alpha=alpha * 0.5,
                  plot_width=plot_width,
                  plot_height=plot_height,
                  **kwargs)
    plotting.hold(True)
    plotting.line(ticks,
                  avgs,
                  line_color=color,
                  line_alpha=alpha,
                  legend=legend)
    plotting.circle(ticks,
                    avgs,
                    line_color=None,
                    fill_color=color,
                    fill_alpha=alpha)
    plotting.grid().grid_line_color = 'white'
    plotting_axis()

    plotting.hold(False)
예제 #3
0
    def bokeh_plot(self):
        import os
        from bokeh.plotting import line
        from bokeh.plotting import hold, figure, show, output_file
        import numpy as np
        import bokeh.embed as embed

        figure()
        hold()

        for i in self.SensorDict:
            line(
                self.SensorDict[i]['dates'], self.SensorDict[i]['values']
            )
            print(len(self.SensorDict[i]['dates']))
            #print(self.SensorDict[i]['dates'][0])
            #print(self.SensorDict[i]['values'][0])
        print('tjo')
        os.chdir('..')
        os.chdir('..')

        output_file('plot.html', title='Plot22')




        show()
예제 #4
0
def get_plottag(script_path):
    """ Saves js in script_path and returns tag for embedding in html
    """
    import numpy as np
    import pandas as pd
    import os

    y_data = np.random.randn(100)
    x_data = pd.date_range('31-Aug-2014', periods=len(y_data))

    figure(x_axis_type='datetime', 
           tools='pan,wheel_zoom,box_zoom,reset,previewsave,crosshair', 
           name='test plot')
    hold()
    line(x_data, y_data,
         line_color="#D95B43", line_width=4, alpha=0.7, 
         legend='random', 
         background_fill= '#cccccc')
    circle(x_data, y_data, 
           color='red', fill_color=None, size=6, 
           legend='random')
    curplot().title = 'Test Plot'
    xaxis().axis_label='date'
    yaxis().axis_label='some random numbers'
    grid().grid_line_color='white'
    grid().grid_line_alpha = 0.5

    plotid = curplot()._id
    script_path = os.path.join(script_path, plotid+'.js')
    js, tag = autoload_static(curplot(), CDN, script_path=script_path)
    with open(script_path, 'w') as f:
        f.write(js)
        
    return tag
예제 #5
0
def bokeh_quantiles(ticks,
                    avgs,
                    quantiles,
                    color='#000055',
                    alpha=1.0,
                    **kwargs):
    plotting.line(ticks,
                  avgs,
                  color=color,
                  line_alpha=alpha,
                  title_text_font_size='6pt',
                  **kwargs)
    plotting.hold(True)

    if quantiles is not None:
        print(quantiles)
        x_std = list(ticks) + list(reversed(ticks))
        y_std = ([q_min for q_min, q_max in quantiles] +
                 list(reversed([q_max for q_min, q_max in quantiles])))
        plotting.patch(x_std,
                       y_std,
                       fill_color=color,
                       fill_alpha=alpha * 0.25,
                       line_color=None)
    plotting.grid().grid_line_color = 'white'
    plotting_axis()

    plotting.hold(False)
예제 #6
0
def posture_signals(kin_env,
                    m_signals,
                    title='posture graphs',
                    color='#666666',
                    alpha=1.0,
                    radius_factor=1.0,
                    swap_xy=True,
                    x_range=[-1.0, 1.0],
                    y_range=[-1.0, 1.0],
                    **kwargs):

    for m_signal in m_signals:
        m_vector = kin_env.flatten_synergies(m_signal)
        s_signal = kin_env._multiarm.forward_kin(m_vector)

        xs, ys = [0.0], [0.0]
        for i in range(kin_env.cfg.dim):
            xs.append(s_signal['x{}'.format(i + 1)])
            ys.append(s_signal['y{}'.format(i + 1)])

        if isinstance(kin_env.cfg.lengths, numbers.Real):
            total_length = kin_env.cfg.lengths * kin_env.cfg.dim
        else:
            total_length = sum(kin_env.cfg.lengths)
        total_length += 0.0

        kwargs.update({
            'x_range': x_range,
            'y_range': y_range,
            'line_color': color,
            'line_alpha': alpha,
            'fill_color': color,
            'fill_alpha': alpha,
            'title': title
        })

        if swap_xy:
            xs, ys = ys, xs

        plotting.line(xs, ys, line_width=2.0 * radius_factor, **kwargs)
        plotting.hold(True)
        plotting.grid().grid_line_color = None
        plotting.ygrid().grid_line_color = None
        plotting_axis()

        plotting.circle(xs[:1], ys[:1], radius=radius_factor * 0.015, **kwargs)
        plotting.circle(xs[1:-1],
                        ys[1:-1],
                        radius=radius_factor * 0.008,
                        **kwargs)
        plotting.circle(xs[-1:],
                        ys[-1:],
                        radius=radius_factor * 0.01,
                        color='red',
                        alpha=alpha)
    plotting.hold(False)
예제 #7
0
def build_timeplot(data):
    output_file('distribution.html', title='distribution')#, js="relative", css="relative")
    x,y=[],[]
    if len(data)>0:
        x,y=zip(*[(k, data[k]) for k in sorted(data)])
    line([pd.DatetimeIndex([dt])[0] for dt in x] , [int(yt) for yt in y],x_axis_type='datetime', tools="pan,zoom,resize", width=400,height=300, title = 'voorkomens')  
    xaxis()[0].axis_label = "Datum"
    yaxis()[0].axis_label = "# artikels"
    # Create an HTML snippet of our plot.
    snippet = curplot().create_html_snippet(embed_base_url='/static/plots/', embed_save_loc=plotdir)
    # Return the snippet we want to place in our page.
    return snippet
예제 #8
0
파일: graphs.py 프로젝트: humm/icdl2015
def posture_signals(
    kin_env,
    m_signals,
    title="posture graphs",
    color="#666666",
    alpha=1.0,
    radius_factor=1.0,
    swap_xy=True,
    x_range=[-1.0, 1.0],
    y_range=[-1.0, 1.0],
    **kwargs
):

    for m_signal in m_signals:
        m_vector = kin_env.flatten_synergies(m_signal)
        s_signal = kin_env._multiarm.forward_kin(m_vector)

        xs, ys = [0.0], [0.0]
        for i in range(kin_env.cfg.dim):
            xs.append(s_signal["x{}".format(i + 1)])
            ys.append(s_signal["y{}".format(i + 1)])

        if isinstance(kin_env.cfg.lengths, numbers.Real):
            total_length = kin_env.cfg.lengths * kin_env.cfg.dim
        else:
            total_length = sum(kin_env.cfg.lengths)
        total_length += 0.0

        kwargs.update(
            {
                "x_range": x_range,
                "y_range": y_range,
                "line_color": color,
                "line_alpha": alpha,
                "fill_color": color,
                "fill_alpha": alpha,
                "title": title,
            }
        )

        if swap_xy:
            xs, ys = ys, xs

        plotting.line(xs, ys, line_width=2.0 * radius_factor, **kwargs)
        plotting.hold(True)
        plotting.grid().grid_line_color = None
        plotting.ygrid().grid_line_color = None
        plotting_axis()

        plotting.circle(xs[:1], ys[:1], radius=radius_factor * 0.015, **kwargs)
        plotting.circle(xs[1:-1], ys[1:-1], radius=radius_factor * 0.008, **kwargs)
        plotting.circle(xs[-1:], ys[-1:], radius=radius_factor * 0.01, color="red", alpha=alpha)
    plotting.hold(False)
예제 #9
0
def line(x_range, avg, std, color='#E84A5F', dashes=(4, 2), alpha=1.0):
    plotting.line(x_range, [avg, avg],
                  line_color=color,
                  line_dash=list(dashes),
                  line_alpha=alpha)
    plotting.hold(True)
    plotting.rect([(x_range[0] + x_range[1]) / 2.0], [avg],
                  [x_range[1] - x_range[0]], [2 * std],
                  fill_color=color,
                  line_color=None,
                  fill_alpha=0.1 * alpha)
    plotting.hold(False)
예제 #10
0
def perf_std_discrete(ticks, avgs, stds, legend=None,
                      std_width=0.3, plot_width=1000, plot_height=300,
                      color=BLUE, alpha=1.0, **kwargs):
    plotting.rect(ticks, avgs, [std_width for _ in stds], 2*np.array(stds),
                  line_color=None, fill_color=color, fill_alpha=alpha*0.5,
                  plot_width=plot_width, plot_height=plot_height, **kwargs)
    plotting.hold(True)
    plotting.line(ticks, avgs, line_color=color, line_alpha=alpha, legend=legend)
    plotting.circle(ticks, avgs, line_color=None, fill_color=color, fill_alpha=alpha)
    plotting.grid().grid_line_color = 'white'
    plotting_axis()

    plotting.hold(False)
예제 #11
0
파일: graphs.py 프로젝트: humm/icdl2015
def line(x_range, avg, std, color="#E84A5F", dashes=(4, 2), alpha=1.0):
    plotting.line(x_range, [avg, avg], line_color=color, line_dash=list(dashes), line_alpha=alpha)
    plotting.hold(True)
    plotting.rect(
        [(x_range[0] + x_range[1]) / 2.0],
        [avg],
        [x_range[1] - x_range[0]],
        [2 * std],
        fill_color=color,
        line_color=None,
        fill_alpha=0.1 * alpha,
    )
    plotting.hold(False)
예제 #12
0
파일: graphs.py 프로젝트: humm/icdl2015
def bokeh_quantiles(ticks, avgs, quantiles, color="#000055", alpha=1.0, **kwargs):
    plotting.line(ticks, avgs, color=color, line_alpha=alpha, title_text_font_size="6pt", **kwargs)
    plotting.hold(True)

    if quantiles is not None:
        print(quantiles)
        x_std = list(ticks) + list(reversed(ticks))
        y_std = [q_min for q_min, q_max in quantiles] + list(reversed([q_max for q_min, q_max in quantiles]))
        plotting.patch(x_std, y_std, fill_color=color, fill_alpha=alpha * 0.25, line_color=None)
    plotting.grid().grid_line_color = "white"
    plotting_axis()

    plotting.hold(False)
예제 #13
0
def tweetsGraph():
    logger.info("Drawing graphs to %s" % path_to_graphs+"Stats.html")
    stat_db_cursor.execute('SELECT * FROM tweets')
    tweets = stat_db_cursor.fetchall()
    date, volume, cumulative, volumePast24h = zip(*[(datetime.datetime.strptime(t['date'], "%Y-%m-%dT%H"), t['current_hour'], t['cumulative'], t['past_24h']) for t in tweets])
    hourly =zip([datetime.datetime(year=d.year, month=d.month, day=d.day) for d in date],volume)
    hourly.sort()
    days, dailyVolume = zip(*[(d, sum([v[1] for v in vol])) for d,vol in itertools.groupby(hourly, lambda i:i[0])])

    bokeh_plt.output_file(path_to_graphs+"Stats.html")
    bokeh_plt.hold()
    bokeh_plt.quad(days, [d+datetime.timedelta(days=1) for d in days], dailyVolume, [0]*len(dailyVolume),  x_axis_type="datetime", color='gray', legend="Daily volume")
    bokeh_plt.line(date, volume, x_axis_type="datetime",  color='red', legend="Hourly volume")
    bokeh_plt.line(date, volumePast24h, x_axis_type="datetime", color='green', legend="Volume in the past 24 hours")
    bokeh_plt.curplot().title = "Volume"
    bokeh_plt.figure()
    bokeh_plt.line(date, cumulative, x_axis_type="datetime")
    bokeh_plt.curplot().title = "Cumulative volume"

    fig, ax = matplotlib_plt.subplots()
    f=DateFormatter("%Y-%m-%d")
    ax.xaxis.set_major_formatter(f)
    matplotlib_plt.plot(date, volume)
    matplotlib_plt.plot(date, volumePast24h)
    matplotlib_plt.plot(days, dailyVolume)
    matplotlib_plt.xticks(np.concatenate((np.array(date)[range(0,len(date),24*7)],[date[-1]])), rotation=70)
    matplotlib_plt.savefig(path_to_graphs+"volume.png", bbox_inches="tight")


    stat_db_cursor.execute('SELECT * FROM users')
    users = stat_db_cursor.fetchall()
    date, nUsers, nUsersWithFriends = zip(*[(datetime.datetime.strptime(u['date'], "%Y-%m-%dT%H:%M:%S.%f"), u['total'], u['with_friends']) for u in users])
    bokeh_plt.figure()
    bokeh_plt.line(date, nUsers, x_axis_type="datetime", legend="Total")
    bokeh_plt.line(date, nUsersWithFriends, x_axis_type="datetime", legend="Friendship collected")
    bokeh_plt.legend().orientation = "top_left"
    bokeh_plt.curplot().title = "Number of users"
    bokeh_plt.save()

    matplotlib_plt.figure()
    fig, ax = matplotlib_plt.subplots()
    f=DateFormatter("%Y-%m-%d")
    ax.xaxis.set_major_formatter(f)
    matplotlib_plt.plot(date, nUsers)
    matplotlib_plt.plot(date, nUsersWithFriends)
    matplotlib_plt.xticks(np.concatenate((np.array(date)[range(0,len(date),24*7)],[date[-1]])), rotation=70)
    matplotlib_plt.savefig(path_to_graphs+"users.png", bbox_inches="tight")
예제 #14
0
def count_by_day_graph(collection_name):
    # TODO: выделить на графике выходные дни
    import numpy as np
    from bokeh.plotting import output_file, hold, figure, line, curplot, grid, show
    a = count_by_day(collection_name)
    output_file("output/count_by_day_graph.html", title="count_by_day_graph")

    hold()

    figure(x_axis_type="datetime", tools="pan,wheel_zoom,box_zoom,reset,previewsave", plot_width=1800)

    line(np.array(a["date"], 'M64'), a['count'], color='#A6CEE3', legend='Количество статей')
    line(np.array(a["date"], 'M64'), [averange_count(collection_name)] * len(a["date"]), color='#ff0000', legend='Среднее количество статей')

    curplot().title = "Количество статей по дням"
    grid().grid_line_alpha=0.3

    show()
예제 #15
0
	def getHTML(self,params):
		df = self.getData(params)  # get data
		bokeh_plot = line(df['Date'],df['close'], color='#1c2980', legend="close", x_axis_type = "datetime", title=self.company_name)
		bokeh_plot.line(df['Date'],df['high'], color='#80641c', legend="high")
		bokeh_plot.line(df['Date'],df['low'], color='#80321c', legend="low")

		script, div = components(bokeh_plot, CDN)
		html = "%s\n%s"%(script, div)
		return html
예제 #16
0
    def create(cls):
        """
        This function is called once, and is responsible for
        creating all objects (plots, datasources, etc)
        """
        obj = cls()

        obj.source = ColumnDataSource(data=dict(x=[], y=[]))

        obj.text = TextInput(title="title", name='title', value='my sin wave')

        obj.offset = Slider(title="offset",
                            name='offset',
                            value=0.0,
                            start=-5.0,
                            end=5.0,
                            step=0.1)
        obj.amplitude = Slider(title="amplitude",
                               name='amplitude',
                               value=1.0,
                               start=-5.0,
                               end=5.0)
        obj.phase = Slider(title="phase",
                           name='phase',
                           value=0.0,
                           start=0.0,
                           end=2 * np.pi)
        obj.freq = Slider(title="frequency",
                          name='frequency',
                          value=1.0,
                          start=0.1,
                          end=5.1)

        toolset = "crosshair,pan,reset,resize,save,wheel_zoom"

        obj.plot = line('x',
                        'y',
                        tools=toolset,
                        source=obj.source,
                        plot_width=400,
                        plot_height=400,
                        line_width=3,
                        line_alpha=0.6,
                        title=obj.text.value,
                        x_range=[0, 4 * np.pi],
                        y_range=[-2.5, 2.5])

        obj.update_data()

        obj.inputs = VBoxForm(children=[
            obj.text, obj.offset, obj.amplitude, obj.phase, obj.freq
        ])

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

        return obj
예제 #17
0
def build_scatter_tooltip(x, y, tt, add_line=True, radius=3, title='My Plot',
                          xlabel='Iteration number', ylabel='Score'):
    bk.figure(title=title)
    bk.hold()
    bk.circle(
        x, y, radius=radius, source=ColumnDataSource(tt),
        fill_alpha=0.6, line_color=None, tools=TOOLS)

    if add_line:
        bk.line(x, y, line_width=2)

    xax, yax = bk.axis()
    xax.axis_label = xlabel
    yax.axis_label = ylabel

    cp = bk.curplot()
    hover = cp.select(dict(type=HoverTool))
    format_tt = [(s, '@%s' % s) for s in tt.columns]
    hover.tooltips = OrderedDict([("index", "$index")] + format_tt)
예제 #18
0
def make_object():
    source = ServerDataSource(data_url="IonXpress_004_rawlib.sam",
                              owner_username="******",
                              transform={'resample' : 'genomic_coverage',
                                         'primary_column' : 'coverage',
                                         'domain_name' : 'chr1'},
                              data={})
    x_range = Range1d(start=0, end=249250621)
    plot = line('chr1', 'counts', tools="pan,wheel_zoom,box_zoom,reset,previewsave",
                source=source, x_range=x_range)
    return plot
예제 #19
0
def bokeh_kin(kin_env, m_signal, color='#DF4949', alpha=1.0, **kwargs):

    m_vector = tools.to_vector(m_signal, kin_env.m_channels)
    s_signal = kin_env._multiarm.forward_kin(m_vector)

    xs, ys = [0.0], [0.0]
    for i in range(kin_env.cfg.dim):
        xs.append(s_signal['x{}'.format(i + 1)])
        ys.append(s_signal['y{}'.format(i + 1)])
    xs, ys = ys, xs  # we swap x and y for a more symmetrical look

    if isinstance(kin_env.cfg.lengths, numbers.Real):
        total_length = kin_env.cfg.lengths * kin_env.cfg.dim
    else:
        total_length = sum(kin_env.cfg.lengths)
    total_length += 0.0

    kwargs = {
        'plot_height': int(350 * 1.60),
        'plot_width': int(350 * 1.60),
        'x_range': [-1.0, 1.0],
        'y_range': [-1.0, 1.0],
        'line_color': color,
        'line_alpha': alpha,
        'fill_color': color,
        'fill_alpha': alpha,
        'title': ''
    }

    plotting.hold()
    plotting.line(xs, ys, **kwargs)
    plotting.grid().grid_line_color = None
    plotting.xaxis().major_tick_in = 0
    plotting.ygrid().grid_line_color = None
    plotting.yaxis().major_tick_in = 0

    plotting.circle(xs[:1], ys[:1], radius=0.015, **kwargs)
    plotting.circle(xs[1:-1], ys[1:-1], radius=0.008, **kwargs)
    plotting.circle(xs[-1:], ys[-1:], radius=0.01, color='red')
    plotting.hold(False)
예제 #20
0
def make_object():
    source = ServerDataSource(data_url="IonXpress_004_rawlib.sam",
                              owner_username="******",
                              transform={'resample' : 'genomic_coverage',
                                         'primary_column' : 'coverage',
                                         'domain_name' : 'chr5'},
                              data={})
    x_range = Range1d(start=0, end=249250621)
    plot1 = line('chr5', 'counts', tools="pan,wheel_zoom,box_zoom,reset,previewsave",
                plot_width=800, plot_height=350,
                source=source, x_range=x_range)
    plot2 = make_plot(x_range)
    return VBox(children=[plot1, plot2])
예제 #21
0
def distribution():

    mu, sigma = 0, 0.5

    measured = np.random.normal(mu, sigma, 1000)
    hist, edges = np.histogram(measured, density=True, bins=20)

    x = np.linspace(-2, 2, 1000)
    pdf = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu)**2 /
                                                    (2 * sigma**2))
    cdf = (1 + scipy.special.erf((x - mu) / np.sqrt(2 * sigma**2))) / 2

    output_server("distribution_reveal")

    hold()

    figure(title="Interactive plots",
           tools="pan, wheel_zoom, box_zoom, reset, previewsave",
           background_fill="#E5E5E5")
    quad(top=hist,
         bottom=np.zeros(len(hist)),
         left=edges[:-1],
         right=edges[1:],
         fill_color="#333333",
         line_color="#E5E5E5",
         line_width=3)

    # Use `line` renderers to display the PDF and CDF
    line(x, pdf, line_color="#348abd", line_width=8, alpha=0.7, legend="PDF")
    line(x, cdf, line_color="#7a68a6", line_width=8, alpha=0.7, legend="CDF")

    xgrid().grid_line_color = "white"
    xgrid().grid_line_width = 3
    ygrid().grid_line_color = "white"
    ygrid().grid_line_width = 3

    legend().orientation = "top_left"

    return curplot(), cursession()
예제 #22
0
	def getHTML(self,params):
		df = self.getData(params)  # get data
		try:
			bokeh_plot = plotting.line(df['Date'],df['close'], color='#1c2980', legend="close", x_axis_type = "datetime", title=self.company_name)
		except AttributeError:
			bokeh_plot = plotting.figure(x_axis_type='datetime', title=self.company_name)
			bokeh_plot.line(df['Date'],df['close'], color='#1c2980', legend="close")
		bokeh_plot.line(df['Date'],df['high'], color='#80641c', legend="high")
		bokeh_plot.line(df['Date'],df['low'], color='#80321c', legend="low")

		script, div = components(bokeh_plot, CDN)
		html = "%s\n%s"%(script, div)
		return html
예제 #23
0
파일: main.py 프로젝트: justin2061/bokeh
def make_test_plot():
    import numpy as np
    from bokeh.plotting import output_server, line

    N = 8000

    x = np.linspace(0, 4 * np.pi, N)
    y = np.sin(x)

    output_server("line.py example")

    l = line(x, y, color="#0000FF", plot_height=300, plot_width=300, tools="pan,resize")
    return l
예제 #24
0
파일: arm_vizu.py 프로젝트: humm/explorers
def bokeh_kin(kin_env, m_signal, color='#DF4949', alpha=1.0, **kwargs):

    m_vector = tools.to_vector(m_signal, kin_env.m_channels)
    s_signal = kin_env._multiarm.forward_kin(m_vector)

    xs, ys = [0.0], [0.0]
    for i in range(kin_env.cfg.dim):
        xs.append(s_signal['x{}'.format(i+1)])
        ys.append(s_signal['y{}'.format(i+1)])
    xs, ys = ys, xs # we swap x and y for a more symmetrical look

    if isinstance(kin_env.cfg.lengths, numbers.Real):
        total_length = kin_env.cfg.lengths*kin_env.cfg.dim
    else:
        total_length = sum(kin_env.cfg.lengths)
    total_length += 0.0

    kwargs ={'plot_height' : int(350*1.60),
             'plot_width'  : int(350*1.60),
             'x_range'     : [-1.0, 1.0],
             'y_range'     : [-1.0, 1.0],
             'line_color'  : color,
             'line_alpha'  : alpha,
             'fill_color'  : color,
             'fill_alpha'  : alpha,
             'title':''
            }

    plotting.hold()
    plotting.line(xs, ys, **kwargs)
    plotting.grid().grid_line_color = None
    plotting.xaxis().major_tick_in   = 0
    plotting.ygrid().grid_line_color = None
    plotting.yaxis().major_tick_in   = 0

    plotting.circle(xs[  : 1], ys[  : 1], radius=0.015, **kwargs)
    plotting.circle(xs[ 1:-1], ys[ 1:-1], radius=0.008, **kwargs)
    plotting.circle(xs[-1:  ], ys[-1:  ], radius=0.01, color='red')
    plotting.hold(False)
예제 #25
0
    def create(cls):
        """
        This function is called once, and is responsible for
        creating all objects (plots, datasources, etc)
        """
        obj = cls()

        obj.source = ColumnDataSource(data=dict(x=[], y=[]))

        obj.text = TextInput(
            title="title", name='title', value='my sin wave'
        )

        obj.offset = Slider(
            title="offset", name='offset',
            value=0.0, start=-5.0, end=5.0
        )
        obj.amplitude = Slider(
            title="amplitude", name='amplitude',
            value=1.0, start=-5.0, end=5.0
        )
        obj.phase = Slider(
            title="phase", name='phase',
            value=0.0, start=0.0, end=2*np.pi
        )
        obj.freq = Slider(
            title="frequency", name='frequency',
            value=1.0, start=0.1, end=5.1
        )

        toolset = "crosshair,pan,reset,resize,save,wheel_zoom"

        obj.plot = line('x', 'y', tools=toolset, source=obj.source,
                        plot_width=400, plot_height=400,
                        line_width=3, line_alpha=0.6,
                        title=obj.text.value,
                        x_range=[0, 4*np.pi], y_range=[-2.5, 2.5]
        )

        obj.update_data()

        obj.inputs = VBoxForm(
            children=[
                obj.text, obj.offset, obj.amplitude, obj.phase, obj.freq
            ]
        )

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

        return obj
예제 #26
0
def perf_astd(ticks,
              avgs,
              astds,
              color=BLUE,
              alpha=1.0,
              sem=1.0,
              plot_width=1000,
              plot_height=500,
              **kwargs):
    plotting.line(ticks,
                  avgs,
                  color=color,
                  line_alpha=alpha,
                  title_text_font_size='6pt',
                  plot_width=plot_width,
                  plot_height=plot_height,
                  **kwargs)
    plotting.hold(True)

    if astds is not None:
        x_std = list(ticks) + list(reversed(ticks))
        y_std = ([
            a - s_min / math.sqrt(sem)
            for a, (s_min, s_max) in zip(avgs, astds)
        ] + list(
            reversed([
                a + s_max / math.sqrt(sem)
                for a, (s_min, s_max) in zip(avgs, astds)
            ])))
        plotting.patch(x_std,
                       y_std,
                       fill_color=color,
                       fill_alpha=alpha * 0.25,
                       line_color=None)
    plotting.grid().grid_line_color = 'white'
    plotting_axis()

    plotting.hold(False)
예제 #27
0
파일: graphs.py 프로젝트: humm/icdl2015
def perf_astd(ticks, avgs, astds, color=BLUE, alpha=1.0, sem=1.0, plot_width=1000, plot_height=500, **kwargs):
    plotting.line(
        ticks,
        avgs,
        color=color,
        line_alpha=alpha,
        title_text_font_size="6pt",
        plot_width=plot_width,
        plot_height=plot_height,
        **kwargs
    )
    plotting.hold(True)

    if astds is not None:
        x_std = list(ticks) + list(reversed(ticks))
        y_std = [a - s_min / math.sqrt(sem) for a, (s_min, s_max) in zip(avgs, astds)] + list(
            reversed([a + s_max / math.sqrt(sem) for a, (s_min, s_max) in zip(avgs, astds)])
        )
        plotting.patch(x_std, y_std, fill_color=color, fill_alpha=alpha * 0.25, line_color=None)
    plotting.grid().grid_line_color = "white"
    plotting_axis()

    plotting.hold(False)
예제 #28
0
파일: views.py 프로젝트: labrepo/LabRepo
    def get(self, request, *args, **kwargs):
        return self.render_to_json_response({'plot': u''})
        # measurement_type_pk = kwargs.get('measurement_type_pk')
        # measurement_type = MeasurementType.objects.get(pk=measurement_type_pk)
        collection = Collection.objects.get(pk=kwargs.get('pk'))
        units = Unit.objects.filter(measurements__match={'measurement_type': measurement_type.pk, 'active': True},
                                    pk__in=[unit.pk for unit in collection.units], active=True)
        if units:
            bk.hold()
            bk.figure(x_axis_type="datetime", tools="pan,wheel_zoom,box_zoom,reset,previewsave")
            colors = self.get_colors(len(units))

            for i, unit in enumerate(units):
                measurements = [(measurement.created_at, measurement.value) for measurement in unit.measurements
                                if measurement.active and measurement.measurement_type == measurement_type]

                measurements.sort(key=lambda measurement: measurement[0])
                data = {
                    'date': [measurement[0] for measurement in measurements],
                    'value': [measurement[1] for measurement in measurements]
                }
                bk.line(np.array(data['date']), data['value'], color=colors[i], line_width=2, legend=unit.__unicode__())

            bk.grid().grid_line_alpha = 0.3
            xax, yax = bk.axis()
            xax.axis_label = ugettext('Date')
            yax.axis_label = ugettext('Values')

            plot = bk.curplot()

            bk.get_default_color()

            plot.title = ugettext('Measurements type')
            # plot.title = ugettext('Measurements type {}'.format(measurement_type.__unicode__()))
            js, tag = autoload_static(plot, Resources(mode='server', root_url=settings.STATIC_URL), "")
            return self.render_to_json_response({'plot': u'{}<script>{}</script>'.format(tag, js)})
        return self.render_to_json_response(ugettext('Not found'), status=404)
예제 #29
0
    def addData(self,
                xvals, yvals,
                xlabel, ylabel,
                nplotted,
                yerrors=None):

        xxvals, yyvals = Stats.filterNone((xvals, yvals))

        color, linestyle, marker = self.getFormat(nplotted)

        self.plots.append(bk.line(
            xxvals,
            yyvals,
            color=color,
            line_width=2))
예제 #30
0
파일: example.py 프로젝트: B-Rich/bokeh
 def create(self, doc):
     """
     This function is called once, and is responsible for
     creating all objects (plots, datasources, etc)
     """
     self.modelform = MyModel()
     self.modelform.create_inputs(doc)
     self.source = ColumnDataSource(data={'x':[], 'y':[]})
     self.update_data()
     self.plot = line('x', 'y', source=self.source,
                      plot_width=400, plot_height=400,
                      title=self.modelform.title
     )
     self.children.append(self.modelform)
     self.children.append(self.plot)
예제 #31
0
파일: main.py 프로젝트: fisadev/bokeh
def make_test_plot():
    import numpy as np
    from bokeh.plotting import output_server, line

    N = 8000

    x = np.linspace(0, 4*np.pi, N)
    y = np.sin(x)

    output_server("line.py example")

    l = line(
        x,y, color="#0000FF",
        plot_height=300, plot_width=300,
        tools="pan,resize")
    return l
예제 #32
0
 def create(self, doc):
     """
     This function is called once, and is responsible for
     creating all objects (plots, datasources, etc)
     """
     self.modelform = MyModel()
     self.modelform.create_inputs(doc)
     self.source = ColumnDataSource(data={'x': [], 'y': []})
     self.update_data()
     self.plot = line('x',
                      'y',
                      source=self.source,
                      plot_width=400,
                      plot_height=400,
                      title=self.modelform.title)
     self.children.append(self.modelform)
     self.children.append(self.plot)
예제 #33
0
    def getHTML(self, params):
        ticker = params['ticker']
        if ticker == 'empty':
            ticker = params['custom_ticker'].upper()
        df = self.getData(params)  # get data
        try:
            bokeh_plot = plotting.line(
                df.index, df['Close'], color='#1c2980',
                legend="Close", x_axis_type="datetime", title=ticker
            )
        except AttributeError:
            bokeh_plot = plotting.figure(x_axis_type='datetime', title=ticker)
            bokeh_plot.line(df.index, df['Close'], color='#1c2980', legend="Close")
        bokeh_plot.line(df.index, df['High'], color='#80641c', legend="High")
        bokeh_plot.line(df.index, df['Low'], color='#80321c', legend="Low")

        script, div = components(bokeh_plot, CDN)
        html = "%s\n%s" % (script, div)
        return html
예제 #34
0
def make_object():
    source = ServerDataSource(data_url="IonXpress_004_rawlib.sam",
                              owner_username="******",
                              transform={
                                  'resample': 'genomic_coverage',
                                  'primary_column': 'coverage',
                                  'domain_name': 'chr5'
                              },
                              data={})
    x_range = Range1d(start=0, end=249250621)
    plot1 = line('chr5',
                 'counts',
                 tools="pan,wheel_zoom,box_zoom,reset,previewsave",
                 plot_width=800,
                 plot_height=350,
                 source=source,
                 x_range=x_range)
    plot2 = make_plot(x_range)
    return VBox(children=[plot1, plot2])
예제 #35
0
    def getHTML(self, params):
        ticker = params['ticker']
        if ticker == 'empty':
            ticker = params['custom_ticker'].upper()
        df = self.getData(params)  # get data
        try:
            bokeh_plot = plotting.line(df.index,
                                       df['Close'],
                                       color='#1c2980',
                                       legend="Close",
                                       x_axis_type="datetime",
                                       title=ticker)
        except AttributeError:
            bokeh_plot = plotting.figure(x_axis_type='datetime', title=ticker)
            bokeh_plot.line(df.index,
                            df['Close'],
                            color='#1c2980',
                            legend="Close")
        bokeh_plot.line(df.index, df['High'], color='#80641c', legend="High")
        bokeh_plot.line(df.index, df['Low'], color='#80321c', legend="Low")

        script, div = components(bokeh_plot, CDN)
        html = "%s\n%s" % (script, div)
        return html
예제 #36
0
def parse_line(line):
    """Find sequence and rtt -- return as int, float or return None"""
    regex = re.compile(r'icmp_seq=(?P<seq>[0-9]+) .* time=(?P<time>[0-9.]+) ms')
    m = regex.search(line)
    if not m:
       return None
    return int(m.groupdict()["seq"]), float(m.groupdict()["time"])

# Use a deque to limit to 100 o entries
x_store = deque(maxlen=MAX_HISTORY)
y_store = deque(maxlen=MAX_HISTORY)

# Unfortuantely, deques can't be serialized -- change to np array
x = list(x_store)
y = list(y_store)
line(x,y, tools="", title = "Ping google.com")
xaxis()[0].axis_label = "Sequence Number"
yaxis()[0].axis_label = "RTT in ms"

save()

renderer = [r for r in curplot().renderers if isinstance(r, GlyphRenderer)][0]
ds = renderer.data_source

f = tail_generator()
for line_ in f:
    
    data = parse_line(line_)
    if data is None:
        continue
    
예제 #37
0
TODO: Replace synthetic data with data streaming from a .csv file from different sensors.
"""

import numpy as np
import bokeh.plotting as bk
from bokeh.objects import Glyph
import time

t = 0
time_x = np.array([0])
pres_y = np.array([20])

bk.output_server('Pressure')

bk.line(time_x, pres_y, color='#0000FF',
        tools='pan,wheel_zoom,box_zoom,reset,resize,crosshair,select,previewsave,embed',
        width=1200,height=300)
bk.xaxis()[0].axis_label = 'Time'
bk.yaxis()[0].axis_label = 'Pressure'

renderer = [r for r in bk.curplot().renderers if isinstance(r, Glyph)][0]
ds = renderer.data_source

while True:
    ds.data["x"] = time_x
    ds.data["y"] = pres_y
    ds._dirty = True
    bk.session().store_obj(ds)

    time.sleep(1)
예제 #38
0
import numpy as np
import bokeh.plotting as bk
from bokeh.objects import Glyph
import time

t = 0
time_x = np.array([0])
pres_y = np.array([20])

bk.output_server('Pressure')

bk.line(
    time_x,
    pres_y,
    color='#0000FF',
    tools=
    'pan,wheel_zoom,box_zoom,reset,resize,crosshair,select,previewsave,embed',
    width=1200,
    height=300)
bk.xaxis()[0].axis_label = 'Time'
bk.yaxis()[0].axis_label = 'Pressure'

renderer = [r for r in bk.curplot().renderers if isinstance(r, Glyph)][0]
ds = renderer.data_source

while True:
    ds.data["x"] = time_x
    ds.data["y"] = pres_y
    ds._dirty = True
    bk.session().store_obj(ds)
예제 #39
0
파일: bokeh_sfr.py 프로젝트: CeasarSS/books
# import the Bokeh plotting tools
from bokeh import plotting as bp

# as in the above example, load deploys.csv into a numpy array
deploydata = np.loadtxt('sfr_dep.dat',delimiter=" ")

# provide handles for the x and y columns
time = deploydata[:,0]
deploys = deploydata[:,1]

lwrs = []
for v in deploydata[:,1] : 
  lwrs.append(100-int(v/3))

bp.output_file("sfr.html", title="bokeh_sfr.py example")

bp.figure(tools="pan,wheel_zoom,box_zoom,reset,previewsave")

bp.line(time, deploys, x_axis_label="Time (m)", y_axis_label="Reactors (#)",
     color='#1F78B4', legend='SFRs')

bp.hold()

bp.line(time, lwrs, x_axis_label="Time (m)", y_axis_label="Reactors (#)",
     color="green", legend='LWRs')

bp.curplot().title = "SFRs"
bp.grid().grid_line_alpha=0.3

bp.show()  # open a browser
예제 #40
0
# provide handles for the x and y columns
time = deploydata[:, 0]
deploys = deploydata[:, 1]

lwrs = []
for v in deploydata[:, 1]:
    lwrs.append(100 - int(v / 3))

bp.output_file("sfr.html", title="bokeh_sfr.py example")

bp.figure(tools="pan,wheel_zoom,box_zoom,reset,previewsave")

bp.line(time,
        deploys,
        x_axis_label="Time (m)",
        y_axis_label="Reactors (#)",
        color='#1F78B4',
        legend='SFRs')

bp.hold()

bp.line(time,
        lwrs,
        x_axis_label="Time (m)",
        y_axis_label="Reactors (#)",
        color="green",
        legend='LWRs')

bp.curplot().title = "SFRs"
bp.grid().grid_line_alpha = 0.3
예제 #41
0
def make_spectrogram():

    plot_kw = dict(
        tools="", min_border=1, h_symmetry=False, v_symmetry=False, toolbar_location=None
    )

    freq = VBox(
        children=[
            Paragraph(text="Freq Range"),
            Slider(orientation="vertical", start=1, end=MAX_FREQ, value=MAX_FREQ, step=1, name="freq")
        ]
    )

    gain = VBox(
        children=[
            Paragraph(text="Gain"),
            Slider(orientation="vertical", start=1, end=20, value=1, step=1, name="gain")
        ]
    )

    spec_source = ColumnDataSource(data=dict(image=[], x=[]))
    spec = image_rgba(
        x='x', y=0, image='image', dw=TILE_WIDTH, dh=MAX_FREQ,
        cols=TILE_WIDTH, rows=SPECTROGRAM_LENGTH, title=None,
        source=spec_source, plot_width=800, plot_height=300,
        x_range=[0, NGRAMS], y_range=[0, MAX_FREQ],
        dilate=True, name="spectrogram", **plot_kw)

    spectrum_source = ColumnDataSource(data=dict(x=[], y=[]))
    spectrum = line(
        x="x", y="y", line_color="darkblue", title="Power Spectrum",
        source=spectrum_source, plot_width=800, plot_height=250,
        x_range=[0, MAX_FREQ], y_range=[10**(-4), 10**3], y_axis_type="log",
        name="spectrum", **plot_kw)

    signal_source = ColumnDataSource(data=dict(x=[], y=[]))
    signal = line(
        x="x", y="y", line_color="darkblue", title="Signal",
        source=signal_source, plot_width=800, plot_height=250,
        x_range=[0, TIMESLICE*1.01], y_range=[-0.1, 0.1],
        name="signal", **plot_kw)

    radial_source = ColumnDataSource(data=dict(
        inner_radius=[], outer_radius=[], start_angle=[], end_angle=[], fill_alpha=[],
    ))
    eq = annular_wedge(
        x=0, y=0, fill_color="#688AB9", fill_alpha="fill_alpha", line_color=None,
        inner_radius="inner_radius", outer_radius="outer_radius",
        start_angle="start_angle", end_angle="end_angle", title=None,
        source=radial_source, plot_width=500, plot_height=520,
        x_range=[-20, 20], y_range=[-20, 20],
        name="eq", **plot_kw)
    grid().grid_line_color=None

    lines = VBox(
        children=[spectrum, signal]
    )

    layout = VBox(
        children = [
            HBox(children=[freq, gain, spec]),
            HBox(children=[lines, eq])
        ]
    )

    return layout
예제 #42
0
               color=data["Survived"].map(colormap),alpha=0.8,
               xlabel="Fare")
    pl.show()





if __name__=="__main__":
    data = loadData("train.csv")
    data,label = buildDataset(data,False)
    
    data_to_plot = data["Age"]
    data_to_plot = data_to_plot[-np.isnan(data_to_plot)]
    
    hist,edges = np.histogram(data_to_plot,bins=20)
    
    pl.output_file('histogram.html')
    pl.figure()
    pl.hold()
    pl.quad(top=hist,bottom=0,left=edges[:-1],right=edges[1:],
            fill_color="#036564", line_color="#033649",
            title="Age distribution",xlabel="Age",ylabel="Number")
            
    pl.line(np.average([edges[1:],edges[:-1]],axis=0),hist,
            line_width=5,color="red",alpha=0.8)            
            
    pl.show()


예제 #43
0
import numpy as np
# import the Bokeh plotting tools
from bokeh import plotting as bp

# as in the above example, load decays.csv into a numpy array
decaydata = np.loadtxt('decays.csv',delimiter=",",skiprows=1)

# provide handles for the x and y columns
time = decaydata[:,0]
decays = decaydata[:,1]

bp.output_file("decays.html", title="bokeh_decay.py example")

bp.figure(tools="pan,wheel_zoom,box_zoom,reset,previewsave")

bp.line(time, decays, x_axis_label="Time (s)", y_axis_label="Decays (#)",
     color='#1F78B4', legend='Decays per second')

bp.curplot().title = "Decays"
bp.grid().grid_line_alpha=0.3

bp.show()  # open a browser
예제 #44
0
def make_spectrogram():

    plot_kw = dict(tools="",
                   min_border=1,
                   h_symmetry=False,
                   v_symmetry=False,
                   toolbar_location=None)

    freq = VBox(children=[
        Paragraph(text="Freq Range"),
        Slider(orientation="vertical",
               start=1,
               end=MAX_FREQ,
               value=MAX_FREQ,
               step=1,
               name="freq")
    ])

    gain = VBox(children=[
        Paragraph(text="Gain"),
        Slider(orientation="vertical",
               start=1,
               end=20,
               value=1,
               step=1,
               name="gain")
    ])

    spec_source = ColumnDataSource(data=dict(image=[], x=[]))
    spec = image_rgba(x='x',
                      y=0,
                      image='image',
                      dw=TILE_WIDTH,
                      dh=MAX_FREQ,
                      cols=TILE_WIDTH,
                      rows=SPECTROGRAM_LENGTH,
                      title=None,
                      source=spec_source,
                      plot_width=800,
                      plot_height=300,
                      x_range=[0, NGRAMS],
                      y_range=[0, MAX_FREQ],
                      dilate=True,
                      name="spectrogram",
                      **plot_kw)

    spectrum_source = ColumnDataSource(data=dict(x=[], y=[]))
    spectrum = line(x="x",
                    y="y",
                    line_color="darkblue",
                    title="Power Spectrum",
                    source=spectrum_source,
                    plot_width=800,
                    plot_height=250,
                    x_range=[0, MAX_FREQ],
                    y_range=[10**(-4), 10**3],
                    y_axis_type="log",
                    name="spectrum",
                    **plot_kw)

    signal_source = ColumnDataSource(data=dict(x=[], y=[]))
    signal = line(x="x",
                  y="y",
                  line_color="darkblue",
                  title="Signal",
                  source=signal_source,
                  plot_width=800,
                  plot_height=250,
                  x_range=[0, TIMESLICE * 1.01],
                  y_range=[-0.1, 0.1],
                  name="signal",
                  **plot_kw)

    radial_source = ColumnDataSource(data=dict(
        inner_radius=[],
        outer_radius=[],
        start_angle=[],
        end_angle=[],
        fill_alpha=[],
    ))
    eq = annular_wedge(x=0,
                       y=0,
                       fill_color="#688AB9",
                       fill_alpha="fill_alpha",
                       line_color=None,
                       inner_radius="inner_radius",
                       outer_radius="outer_radius",
                       start_angle="start_angle",
                       end_angle="end_angle",
                       title=None,
                       source=radial_source,
                       plot_width=500,
                       plot_height=520,
                       x_range=[-20, 20],
                       y_range=[-20, 20],
                       name="eq",
                       **plot_kw)
    grid().grid_line_color = None

    lines = VBox(children=[spectrum, signal])

    layout = VBox(children=[
        HBox(children=[freq, gain, spec]),
        HBox(children=[lines, eq])
    ])

    return layout
예제 #45
0
파일: bokeh_decay.py 프로젝트: ing7t/kod
import numpy as np

# import the Bokeh plotting tools
from bokeh import plotting as bp

# as in the above example, load decays.csv into a numpy array
decaydata = np.loadtxt("decays2.csv", delimiter=",", skiprows=1)

# provide handles for the x and y columns
time = decaydata[:, 0]
decays = decaydata[:, 1]

bp.output_file("decays.html", title="bokeh_decay.py example")

bp.figure(tools="pan,wheel_zoom,box_zoom,reset,previewsave")

bp.line(time, decays, x_axis_label="Time (s)", y_axis_label="Decays (#)", color="#1F78B4", legend="Decays per second")

bp.curplot().title = "Decays"
bp.grid().grid_line_alpha = 0.3

bp.show()  # open a browser
예제 #46
0
import numpy as np
# import the Bokeh plotting tools
from bokeh import plotting as bp

# as in the above example, load decays.csv into a numpy array
decaydata = np.loadtxt('decays.csv', delimiter=",", skiprows=1)

# provide handles for the x and y columns
time = decaydata[:, 0]
decays = decaydata[:, 1]

bp.output_file("decays.html", title="bokeh_decay.py example")

bp.figure(tools="pan,wheel_zoom,box_zoom,reset,previewsave")

bp.line(time,
        decays,
        x_axis_label="Time (s)",
        y_axis_label="Decays (#)",
        color='#1F78B4',
        legend='Decays per second')

bp.curplot().title = "Decays"
bp.grid().grid_line_alpha = 0.3

bp.show()  # open a browser