コード例 #1
0
ファイル: test_plotting.py プロジェクト: Afey/bokeh
 def test_figure(self):
     plt.figure()
     self.assertEqual(plt.curplot(), None)
     p = plt.circle([1,2,3], [1,2,3])
     self.assertEqual(plt.curplot(), p)
     plt.figure()
     self.assertEqual(plt.curplot(), None)
コード例 #2
0
def plot_circle_density(nodes, degrees, plot_width=800, plot_height=800):
    print("Plotting circle density graph")
    TOOLS="hover,pan,wheel_zoom,box_zoom,reset,click,previewsave"    
    plt.figure(plot_width=plot_width, plot_height=plot_height, tools=TOOLS)
    theta = np.random.uniform(0, 2*np.pi, size=len(nodes))
    max_d, min_d = np.max(degrees), np.min(degrees)
    scale = 1.0/np.log(degrees) - 1.0/np.log(max_d)
    xs = np.cos(theta)*scale
    ys = np.sin(theta)*scale
    source_dict = dict(
        xs = xs,
        ys = ys,
        degrees = degrees,
        nodes = nodes,
        alphas = np.log(degrees)/np.log(max(degrees)),
    )
    source = ColumnDataSource(source_dict)
    plt.hold(True)
    plt.circle('xs', 'ys', source=source,
               radius=0.0025,
               fill_alpha='alphas',
               x_axis_type=None, y_axis_type=None, 
               title="Density Distribution of Degrees")
    plt.text([max(xs), max(xs)], 
             [.95*max(ys), .85*max(ys)], 
             ["distance from center = 1 / log(deg)",
              "angle = random"], 
             angle=0,
             text_baseline="bottom", text_align="right")
    hover = [t for t in plt.curplot().tools if isinstance(t, HoverTool)][0]
    hover.tooltips = OrderedDict([
        ('node', '@nodes'), ('degree', '@degrees')
    ])
    plt.hold(False)
    return plt.curplot()
コード例 #3
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
コード例 #4
0
def build_punchcard(datamap_list, concept_list,
                    radii_list, fields_in_concept_list,
                    datamaps, concepts,
                    plot_width=1200, plot_height=800):

    source = ColumnDataSource(
        data=dict(
            datamap=datamap_list,  # x
            concept=concept_list,  # y
            radii=radii_list,
            fields_in_concept=fields_in_concept_list,
        )
    )
    output_file('')
    hold()
    figure()
    plot_properties = {
        'title': None,
        'tools': "hover,resize,previewsave",
        'y_range': [get_datamap_label(datamap) for datamap in datamaps],
        'x_range': concepts,
        'plot_width': plot_width,
        'plot_height': plot_height,
    }

    rect('concept', 'datamap',  # x, y
         1, 1,  # height, width
         source=source,
         color='white',  # put in background
         **plot_properties)

    circle('concept', 'datamap',  # x, y
           size='radii',
           source=source,
           color='black',
           **plot_properties)

    grid().grid_line_color = None
    x = xaxis()
    x.major_label_orientation = pi / 4
    hover = [t for t in curplot().tools if isinstance(t, HoverTool)][0]

    hover.tooltips = OrderedDict([
        ("Datamap", "@datamap"),
        ("Concept", "@concept"),
        ("Fields", "@fields_in_concept"),
    ])

    return curplot().create_html_snippet(
        static_path=settings.STATIC_URL,
        embed_save_loc=settings.BOKEH_EMBED_JS_DIR,
        embed_base_url=reverse('bokeh'),
    )
コード例 #5
0
ファイル: test_plotting.py プロジェクト: JBurke007/bokeh
 def test_figure(self):
     p = plt.figure()
     self.assertEqual(plt.curplot(), p)
     q = plt.circle([1,2,3], [1,2,3])
     self.assertEqual(plt.curplot(), q)
     self.assertNotEqual(p, q)
     r = plt.figure()
     self.assertEqual(plt.curplot(), r)
     self.assertNotEqual(p, r)
     self.assertNotEqual(q, r)
     plt.hold()
     s = plt.circle([1,2,3], [1,2,3])
     self.assertEqual(plt.curplot(), s)
     self.assertEqual(r, s)
コード例 #6
0
ファイル: test_plotting.py プロジェクト: xuexianwu/bokeh
 def test_figure(self):
     p = plt.figure()
     self.assertEqual(plt.curplot(), p)
     q = plt.circle([1,2,3], [1,2,3])
     self.assertEqual(plt.curplot(), q)
     self.assertNotEqual(p, q)
     r = plt.figure()
     self.assertEqual(plt.curplot(), r)
     self.assertNotEqual(p, r)
     self.assertNotEqual(q, r)
     plt.hold()
     s = plt.circle([1,2,3], [1,2,3])
     self.assertEqual(plt.curplot(), s)
     self.assertEqual(r, s)
コード例 #7
0
ファイル: process_text.py プロジェクト: remram44/memex
def bokeh_lsa(year, df):
    plt.output_file('output/lsa/' + str(year) + '.html')

    topics = [str(a) for a in df.columns]
    words = list(to_str(df.index))
    p = plt.figure(x_range=topics,
                   y_range=words,
                   plot_width=800,
                   plot_height=600,
                   title=year,
                   tools='resize, save')

    plot_sizes = []
    plot_topics = []
    plot_words = []
    print df
    for word, coeff in df.iterrows():
        for n, c in enumerate(coeff):
            if c > 0:
                plot_sizes.append(c)
                plot_topics.append(str(n))
                plot_words.append(word)
    if len(plot_sizes) == 0:
        return
    max_size = np.max(plot_sizes)
    plot_sizes = [int(a / max_size * 75) + 25 for a in plot_sizes]

    print plot_sizes, plot_words, plot_topics

    p.circle(x=plot_topics, y=plot_words, size=plot_sizes, fill_alpha=0.6)
    plt.show(p)

    return plt.curplot()
コード例 #8
0
ファイル: process_text.py プロジェクト: ViDA-NYU/memex
def bokeh_lsa(year, df):
    plt.output_file('output/lsa/'+str(year)+'.html')

    topics = [str(a) for a in df.columns]
    words = list(to_str(df.index))
    p = plt.figure(x_range=topics, y_range=words,
           plot_width=800, plot_height=600,
           title=year, tools='resize, save')

    plot_sizes = []
    plot_topics = []
    plot_words = []
    print df
    for word, coeff in df.iterrows():
        for n, c in enumerate(coeff):
            if c > 0:
                plot_sizes.append(c)
                plot_topics.append(str(n))
                plot_words.append(word)
    if len(plot_sizes) == 0:
        return
    max_size = np.max(plot_sizes)
    plot_sizes = [int(a/max_size * 75) + 25 for a in plot_sizes]

    print plot_sizes, plot_words, plot_topics

    p.circle(x=plot_topics, y=plot_words, size=plot_sizes, fill_alpha=0.6)
    plt.show(p)

    return plt.curplot()
コード例 #9
0
ファイル: app_reveal.py プロジェクト: HyperionAnalytics/bokeh
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()
コード例 #10
0
ファイル: app_reveal.py プロジェクト: HyperionAnalytics/bokeh
def animated():

    from numpy import pi, cos, sin, linspace, zeros_like

    N = 50 + 1
    r_base = 8
    theta = linspace(0, 2 * pi, N)
    r_x = linspace(0, 6 * pi, N - 1)
    rmin = r_base - cos(r_x) - 1
    rmax = r_base + sin(r_x) + 1

    colors = ["FFFFCC", "#C7E9B4", "#7FCDBB", "#41B6C4", "#2C7FB8",
              "#253494", "#2C7FB8", "#41B6C4", "#7FCDBB", "#C7E9B4"] * 5

    cx = cy = zeros_like(rmin)

    output_server("animated_reveal")

    figure(title="Animations")

    hold()

    annular_wedge(
        cx, cy, rmin, rmax, theta[:-1], theta[1:],
        x_range=[-11, 11],
        y_range=[-11, 11],
        inner_radius_units="data",
        outer_radius_units="data",
        fill_color=colors,
        line_color="black",
        tools="pan,wheel_zoom,box_zoom,reset,previewsave"
    )

    return curplot(), cursession()
コード例 #11
0
ファイル: execute_plot.py プロジェクト: Eigenstate/osprey
def plot_3(data, ss):
    """t-SNE embedding of the parameters, colored by score
    """
    scores = np.array([d['mean_test_score'] for d in data])
    # maps each parameters to a vector of floats
    warped = np.array([ss.point_to_moe(d['parameters']) for d in data])

    # Embed into 2 dimensions with t-SNE
    X = TSNE(n_components=2).fit_transform(warped)

    e_scores = np.exp(scores)
    mine, maxe = np.min(e_scores), np.max(e_scores)
    color = (e_scores - mine) / (maxe - mine)
    mapped_colors = map(rgb2hex, cm.get_cmap('RdBu_r')(color))

    bk.figure(title='t-SNE (unsupervised)')
    bk.hold()
    df_params = nonconstant_parameters(data)
    df_params['score'] = scores
    bk.circle(
        X[:, 0], X[:, 1], color=mapped_colors, radius=1,
        source=ColumnDataSource(df_params), fill_alpha=0.6,
        line_color=None, tools=TOOLS)
    cp = bk.curplot()
    hover = cp.select(dict(type=HoverTool))
    format_tt = [(s, '@%s' % s) for s in df_params.columns]
    hover.tooltips = OrderedDict([("index", "$index")] + format_tt)

    xax, yax = bk.axis()
    xax.axis_label = 't-SNE coord 1'
    yax.axis_label = 't-SNE coord 2'
コード例 #12
0
ファイル: stats.py プロジェクト: SoSweetProject/jpmOldStuffs
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")
コード例 #13
0
def plot_adj(adj, sparcity):
    N, _ = adj.shape
    TOOLS="pan,wheel_zoom,box_zoom,reset,click,previewsave"
    plt.figure(plot_width=N+100, plot_height=N+100, tools=TOOLS)
    plt.image(image=[adj], x =[0], y=[0], dw=[N], dh=[N], 
              x_range=[0, N], y_range=[0, N],
              palette=["Blues-3"],
              title="Adjacency of top %d nodes (%.2f%% sparcity)" % (N, sparcity),
              x_axis_type=None, y_axis_type=None)
    return plt.curplot()
コード例 #14
0
ファイル: utils.py プロジェクト: Fematich/article_browser
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
コード例 #15
0
ファイル: plot.py プロジェクト: Yingmin-Li/owls
def merge(*args, **kwargs):
    import bokeh.plotting as bk
    bk.figure()
    bk.hold()
    y = kwargs.get('y', None)
    x = kwargs.get('x', 'Pos')
    try:
        kwargs.pop('y')
        kwargs.pop('x')
    except:
        pass
    y = (y if type(y) == list else [y] * len(args))  #FIXME do the same for x
    for yi, p in zip(y, args):
        p.show(x=x, y=yi, color=next(kwargs["colors"]), **kwargs)
    return bk.curplot()
コード例 #16
0
ファイル: plot.py プロジェクト: Yingmin-Li/owls
def merge(*args, **kwargs):
    import bokeh.plotting as bk
    bk.figure()
    bk.hold()
    y = kwargs.get('y',None)
    x = kwargs.get('x','Pos')
    try:
        kwargs.pop('y')
        kwargs.pop('x')
    except:
        pass
    y = (y if type(y) == list else [y]*len(args)) #FIXME do the same for x
    for yi,p in zip(y,args):
        p.show(x=x, y=yi, color=next(kwargs["colors"]), **kwargs)
    return bk.curplot()
コード例 #17
0
ファイル: ghantt.py プロジェクト: aterrel/ghantt
def graph():
    print("Graphing")
    with open(DATA_FILE, "rb") as fin:
        issues = [Issue(x) for x in pickle.load(fin)]

    plotting.output_file("{}.{}.html".format(GH_USER, GH_REPO),
                         title="ghantt.py")

    numbers = [iss.number for iss in issues]

    source = ColumnDataSource(
        data=dict(
            number = [iss.number for iss in issues],
            ago = [iss.ago + iss.length/2 for iss in issues],
            length = [iss.length for iss in issues],
            title = [iss.title for iss in issues],
            pull_request = [iss.pull_request for iss in issues],
            color = [assign_color(iss) for iss in issues],
            since = ["{} days".format(int(abs(iss.ago))) for iss in issues],
        ),
    )
    plotting.hold()
    plotting.rect("ago", "number", "length", 1, source=source,
                  color="color", title="{}/{}".format(GH_USER, GH_REPO),
                  y_range=(min(numbers), max(numbers)),
                  tools="resize,hover,previewsave,pan,wheel_zoom",
                  fill_alpha=0.8)

    text_props = {
        "source": source,
        "angle": 0,
        "color": "black",
        "text_align": "left",
        "text_baseline": "middle"
    }

    plotting.grid().grid_line_color = None

    hover = [t for t in plotting.curplot().tools if isinstance(t, HoverTool)][0]
    hover.tooltips = OrderedDict([
        ("number", "@number"),
        ("title", "@title"),
        ("since", "@since"),
        ("pull_request", "@pull_request"),
    ])

    plotting.show()
コード例 #18
0
ファイル: FoamFrame.py プロジェクト: Yingmin-Li/owls
    def draw(self, x, y, z, title, func, **kwargs):
        import bokeh.plotting as bk
        #TODO: change colors if y is of list type
        y = (y if type(y) == list else [y]) # wrap y to a list so that we can iterate

        kwargs.update({ "outline_line_color":"black", #FIXME refactor
                        "plot_width":300,
                        "plot_height":300,
                      })
        bk.hold(True)
        for yi in y:
            x_data, y_data = self[x], self[yi]
            func(x=x_data,
                 y=y_data,
                 title=title,
                 **kwargs)
        bk.hold(False)
        ret = bk.curplot()

        def _label(axis, field):
           label = kwargs.get(axis + '_label', False)
           if label:
               self.properties.plot_properties.insert(field, {axis + '_label':label})
           else:
               label = self.properties.plot_properties.select(field, axis + '_label', "None")
           return label

        def _range(axis, field):
           from bokeh.objects import Range1d
           p_range_args = kwargs.get(axis + '_range', False)
           if p_range_args:
               self.properties.plot_properties.insert(field, {axis + '_range': p_range})
           else:
               p_range = self.properties.plot_properties.select(field, axis + '_range')
           if not p_range:
                return False
           else:
                return Range1d(start=p_range[0], end=p_range[1])


        bk.xaxis().axis_label = _label('x', x)
        if _range('x', x):
            ret.x_range = _range('x', x)
        bk.yaxis().axis_label = _label('y', y[0]) #TODO can this make sense for multiplots?
        if _range('y', y[0]):
            ret.y_range = _range('y', y[0])
        return ret
コード例 #19
0
    def _draw(self, x, y, z, overlay, inst_func, **kwargs):
        import bokeh.plotting as bk
        import numpy as np

        def greatest_divisor(number):
            if number == 1:
                return 1
            for i in reversed(range(number)):
                if number % i == 0:
                    return i
            else:
                return 1

        if not overlay:
            rows = []
            for name, instance in self.cases.iteritems():
                bk.figure()
                rows.append(
                    getattr(instance, inst_func)(x=x,
                                                 y=y,
                                                 title=str(name),
                                                 **kwargs)  #FIXME num cars
                )
            rows = np.array(rows).reshape(greatest_divisor(len(rows)),
                                          -1).tolist()
            return bk.GridPlot(children=rows, title="Scatter")
        else:
            bk.hold()
            colors = plot.next_color()
            exp_legend = kwargs.get("legend", None)
            if exp_legend != None:
                kwargs.pop("legend")
            exp_title = kwargs.get("title", None)
            if exp_title != None:
                kwargs.pop("title")
            for name, instance in self.cases.iteritems():
                color = next(colors)
                legend = (exp_legend if exp_legend != None else name)
                title = (exp_title if exp_title != None else "")
                getattr(instance, inst_func)(x=x,
                                             y=y,
                                             title=title,
                                             color=color,
                                             legend=legend,
                                             **kwargs)
            bk.hold(False)
            return bk.curplot()
コード例 #20
0
ファイル: timeseries.py プロジェクト: i-Hun/thesis-code
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()
コード例 #21
0
ファイル: execute_plot.py プロジェクト: Eigenstate/osprey
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)
コード例 #22
0
ファイル: utils.py プロジェクト: Fematich/article_browser
def build_plot(datalist,logx=True):
    # Set the output for our plot.
    output_file('plot.html', title='Plot')#, js="relative", css="relative")
    # Create some data for our plot.
    colors=['red','green','blue','yellow','black']
#    colors=['tomato','navy']
    hold()
    cnt=0
    for name,data in datalist:
        cnt+=1
        x,y=zip(*data)
        if logx:
            scatter([np.log(x_el) for x_el in x] ,list(y) , color=colors[cnt], legend=name)
        else:
            scatter(list(x) ,list(y) , color=colors[cnt], legend=name)
    # 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
コード例 #23
0
ファイル: app_reveal.py プロジェクト: velociraptors/bokeh
def animated():

    from numpy import pi, cos, sin, linspace, zeros_like

    N = 50 + 1
    r_base = 8
    theta = linspace(0, 2 * pi, N)
    r_x = linspace(0, 6 * pi, N - 1)
    rmin = r_base - cos(r_x) - 1
    rmax = r_base + sin(r_x) + 1

    colors = [
        "FFFFCC", "#C7E9B4", "#7FCDBB", "#41B6C4", "#2C7FB8", "#253494",
        "#2C7FB8", "#41B6C4", "#7FCDBB", "#C7E9B4"
    ] * 5

    cx = cy = zeros_like(rmin)

    output_server("animated_reveal")

    figure(title="Animations",
           x_range=[-11, 11],
           y_range=[-11, 11],
           tools="pan,wheel_zoom,box_zoom,reset,previewsave")

    hold()

    annular_wedge(
        cx,
        cy,
        rmin,
        rmax,
        theta[:-1],
        theta[1:],
        inner_radius_units="data",
        outer_radius_units="data",
        fill_color=colors,
        line_color="black",
    )

    return curplot(), cursession()
コード例 #24
0
ファイル: app_reveal.py プロジェクト: velociraptors/bokeh
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()
コード例 #25
0
ファイル: MultiFrame.py プロジェクト: Yingmin-Li/owls
    def _draw(self, x, y, z, overlay, inst_func, **kwargs):
        import bokeh.plotting as bk
        import numpy as np
        def greatest_divisor(number):
            if number == 1:
                return 1
            for i in reversed(range(number)):
                if number % i == 0:
                    return i
            else:
                return 1

        if not overlay:
            rows=[]
            for name, instance in self.cases.iteritems():
                bk.figure()
                rows.append(
                        getattr(instance, inst_func)
                            (x=x, y=y, title=str(name), **kwargs) #FIXME num cars
                    )
            rows = np.array(rows).reshape(greatest_divisor(len(rows)),-1).tolist()
            return bk.GridPlot(children=rows, title="Scatter")
        else:
           bk.hold()
           colors = plot.next_color()
           exp_legend = kwargs.get("legend", None)
           if exp_legend != None:
                kwargs.pop("legend")
           exp_title = kwargs.get("title", None)
           if exp_title != None:
                kwargs.pop("title")
           for name, instance in self.cases.iteritems():
                color = next(colors)
                legend = (exp_legend if exp_legend != None else name)
                title = (exp_title if exp_title != None else "")
                getattr(instance, inst_func)(x=x, y=y, title=title, color=color, legend=legend, **kwargs)
           bk.hold(False)
           return bk.curplot()
コード例 #26
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)
コード例 #27
0
ファイル: problem1.py プロジェクト: pvarsh/pr_informatics
def drawPlot(shapeFilename, zipBorough, zipMaxAgency):
  # Read the ShapeFile
  dat = shapefile.Reader(shapeFilename)
  
  # Creates a dictionary for zip: {lat_list: [], lng_list: []}.
  zipCodes = []
  hoverZip = []
  hoverAgency = []
  hoverComplaints = []
  polygons = {'lat_list': [], 'lng_list': [], 'centerLat_list': [], 'centerLon_list': []}

  record_index = 0
  for r in dat.iterRecords():
    currentZip = r[0]

    # Keeps only zip codes in NY area.
    if currentZip in zipMaxAgency: # was in zipBorough:
      # zipCodes.append(currentZip) # moving this line into the parts loop

      # Gets shape for this zip.
      shape = dat.shapeRecord(record_index).shape
      for part in range(len(shape.parts)):
        zipCodes.append(currentZip)
        hoverZip.append(currentZip)
        hoverAgency.append(zipMaxAgency[currentZip][0])
        hoverComplaints.append(zipMaxAgency[currentZip][1])
        start = shape.parts[part]
        if part == len(shape.parts) - 1:
          end = len(shape.points)
        else:
          end   = shape.parts[part + 1]
          
        points = shape.points[start : end]

        # Breaks into lists for lat/lng.
        lngs = [p[0] for p in points]
        lats = [p[1] for p in points]

        # Calculate centers
        center_lngs = min(lngs) + (max(lngs) - min(lngs))/2
        center_lats = min(lats) + (max(lats) - min(lats))/2

        # Store centroids for current part shape
        polygons['centerLat_list'].append(center_lats)
        polygons['centerLon_list'].append(center_lngs)

        # Stores lat/lng for current zip shape.
        polygons['lng_list'].append(lngs)
        polygons['lat_list'].append(lats)

    record_index += 1

  # Palette
  ##d9d9d9
  brewer11 = ['#8dd3c7', '#ffffb3', '#bebada','#fb8072','#80b1d3','#fdb462','#b3de69','#fccde5','#d9d9d9','#bc80bd','#ccebc5']
  #brewer11 = ['#a6cee3', '#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c','#fdbf6f','#ff7f00','#cab2d6','#6a3d9a','#ffff99']

  #agencies = sorted(list({zipMaxAgency[zipCode] for zipCode in zipMaxAgency}))
  
  biggestComplaints = {}
  for zz, aa in zipMaxAgency.iteritems():
    if aa[0] in biggestComplaints:
      biggestComplaints[aa[0]] += 1
    else:
      biggestComplaints[aa[0]] = 1
  
  # sorting agencies by number of zip codes (to try to get better colors)
  agencies = list(biggestComplaints.iteritems())
  agencies = sorted(agencies, key = lambda x: x[1], reverse = True)
  agencies = [agency[0] for agency in agencies]
  
  # Assign colors to agencies 
  agencyColor = {agencies[i] : brewer11[i] for i in range(len(brewer11))}
  polygons['colors'] = [agencyColor[zipMaxAgency[zipCode][0]] for zipCode in zipCodes]
  
  # Prepare hover
  #source = bk.ColumnDataSource(data=dict(hoverAgency=hoverAgency, hoverZip=hoverZip, hoverComplaintCount=hoverComplaintCount,))
  source = bk.ColumnDataSource(data=dict(hoverZip = hoverZip, hoverAgency = hoverAgency, hoverComplaints = hoverComplaints),)
  # Creates the Plot
  bk.output_file("problem1.html")
  bk.hold()
  
  TOOLS="pan,wheel_zoom,box_zoom,reset,previewsave,hover"
  fig = bk.figure(title="311 Complaints by Zip Code", \
         tools=TOOLS, plot_width=800, plot_height=650)
  
  # Creates the polygons.
  bk.patches(polygons['lng_list'], polygons['lat_list'], fill_color=polygons['colors'], line_color="gray", source = source)
  
  # RP: add hover
  hover = bk.curplot().select(dict(type=HoverTool))
  hover.tooltips = OrderedDict([
    ("Zip", "@hoverZip"),
    ("Agency", "@hoverAgency"),
    ("Number of complaints", "@hoverComplaints"),
  ])
  
  ### Zip codes as text on polygons 
  #for i in range(len(polygons['centerLat_list'])):
  #  y = polygons['centerLat_list'][i]
  #  x = polygons['centerLon_list'][i]
  #  zipCode = zipCodes[i]
  #  bk.text([x], [y], text=zipCode, angle=0, text_font_size="8pt", text_align="center", text_baseline="middle")
 
  fonts = ["Comic sans MS", "Papyrus", "Curlz", "Impact", "Zapf dingbats", "Comic sans MS", "Papyrus", "Curlz", "Impact", "Zapf Dingbats", "Comic sans MS"]
   
  ### Legend
  x = -73.66
  y = 40.50
  #x = -74.25
  #y = 40.9
  for agency, color in agencyColor.iteritems():
    #print "Color: ", a
    #print "x:", x
    #print "y:", y
   
    bk.rect([x], [y], color = color, width=0.03, height=0.015)
    bk.text([x], [y], text = agency, angle=0, text_font_size="7pt", text_align="center", text_baseline="middle")
    y = y + 0.015

  #bokeh.embed.components(fig, bokeh.resources.CDN)
  bk.show()
コード例 #28
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
コード例 #29
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)

    t = t + 1
    time_x = np.append(time_x, time_x[t - 1] + 1)
    pres_y = np.append(
        pres_y, pres_y[t - 1] + np.random.random() * pres_y[t - 1] * 0.01)
コード例 #30
0
ファイル: plot_data.py プロジェクト: NISTFire/nist-fire
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)

    t = t + 1
    time_x = np.append(time_x,
                       time_x[t-1]+1)
    pres_y = np.append(pres_y,
                       pres_y[t-1] + np.random.random()*pres_y[t-1]*0.01)
コード例 #31
0
# Make a text glyph for each rect glyph to show the cabinet names and locations
bk.text(x=dict(field="posx", units="data"),
     y=dict(field="text_locy", units="data"),
     text=dict(field="loc", units="data"),
     text_font_style="bold", text_font_size="12pt", **text_props)

bk.text(x=dict(field="posx", units="data"),
     y=dict(field="text_namey", units="data"),
     text=dict(field="name", units="data"),
     text_font_style="bold", text_font_size="9pt", **text_props)

bk.text(x=dict(field="posx", units="data"),
     y=dict(field="text_suby", units="data"),
     text=dict(field="sub", units="data"),
     text_font_style="bold", text_font_size="9pt", **text_props)

# turn off grid lines
bk.grid().grid_line_color = None
# Add hovertool to show equipment in tooltips
hover = bk.curplot().select(dict(type=HoverTool))
hover.tooltips = OrderedDict([
    ("name", "@name"),
    ("subsystem", "@sub"),
    ("equipment","@equip"),
    ("phone","@phone")
])

# Show the graph
bk.show()
コード例 #32
0
ファイル: problem1.py プロジェクト: pvarsh/pr_informatics
def drawPlot(shapeFilename, zipBorough, zipMaxAgency):
    # Read the ShapeFile
    dat = shapefile.Reader(shapeFilename)

    # Creates a dictionary for zip: {lat_list: [], lng_list: []}.
    zipCodes = []
    hoverZip = []
    hoverAgency = []
    hoverComplaints = []
    polygons = {
        'lat_list': [],
        'lng_list': [],
        'centerLat_list': [],
        'centerLon_list': []
    }

    record_index = 0
    for r in dat.iterRecords():
        currentZip = r[0]

        # Keeps only zip codes in NY area.
        if currentZip in zipMaxAgency:  # was in zipBorough:
            # zipCodes.append(currentZip) # moving this line into the parts loop

            # Gets shape for this zip.
            shape = dat.shapeRecord(record_index).shape
            for part in range(len(shape.parts)):
                zipCodes.append(currentZip)
                hoverZip.append(currentZip)
                hoverAgency.append(zipMaxAgency[currentZip][0])
                hoverComplaints.append(zipMaxAgency[currentZip][1])
                start = shape.parts[part]
                if part == len(shape.parts) - 1:
                    end = len(shape.points)
                else:
                    end = shape.parts[part + 1]

                points = shape.points[start:end]

                # Breaks into lists for lat/lng.
                lngs = [p[0] for p in points]
                lats = [p[1] for p in points]

                # Calculate centers
                center_lngs = min(lngs) + (max(lngs) - min(lngs)) / 2
                center_lats = min(lats) + (max(lats) - min(lats)) / 2

                # Store centroids for current part shape
                polygons['centerLat_list'].append(center_lats)
                polygons['centerLon_list'].append(center_lngs)

                # Stores lat/lng for current zip shape.
                polygons['lng_list'].append(lngs)
                polygons['lat_list'].append(lats)

        record_index += 1

    # Palette
    ##d9d9d9
    brewer11 = [
        '#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3', '#fdb462',
        '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd', '#ccebc5'
    ]
    #brewer11 = ['#a6cee3', '#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c','#fdbf6f','#ff7f00','#cab2d6','#6a3d9a','#ffff99']

    #agencies = sorted(list({zipMaxAgency[zipCode] for zipCode in zipMaxAgency}))

    biggestComplaints = {}
    for zz, aa in zipMaxAgency.iteritems():
        if aa[0] in biggestComplaints:
            biggestComplaints[aa[0]] += 1
        else:
            biggestComplaints[aa[0]] = 1

    # sorting agencies by number of zip codes (to try to get better colors)
    agencies = list(biggestComplaints.iteritems())
    agencies = sorted(agencies, key=lambda x: x[1], reverse=True)
    agencies = [agency[0] for agency in agencies]

    # Assign colors to agencies
    agencyColor = {agencies[i]: brewer11[i] for i in range(len(brewer11))}
    polygons['colors'] = [
        agencyColor[zipMaxAgency[zipCode][0]] for zipCode in zipCodes
    ]

    # Prepare hover
    #source = bk.ColumnDataSource(data=dict(hoverAgency=hoverAgency, hoverZip=hoverZip, hoverComplaintCount=hoverComplaintCount,))
    source = bk.ColumnDataSource(data=dict(hoverZip=hoverZip,
                                           hoverAgency=hoverAgency,
                                           hoverComplaints=hoverComplaints), )
    # Creates the Plot
    bk.output_file("problem1.html")
    bk.hold()

    TOOLS = "pan,wheel_zoom,box_zoom,reset,previewsave,hover"
    fig = bk.figure(title="311 Complaints by Zip Code", \
           tools=TOOLS, plot_width=800, plot_height=650)

    # Creates the polygons.
    bk.patches(polygons['lng_list'],
               polygons['lat_list'],
               fill_color=polygons['colors'],
               line_color="gray",
               source=source)

    # RP: add hover
    hover = bk.curplot().select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([
        ("Zip", "@hoverZip"),
        ("Agency", "@hoverAgency"),
        ("Number of complaints", "@hoverComplaints"),
    ])

    ### Zip codes as text on polygons
    #for i in range(len(polygons['centerLat_list'])):
    #  y = polygons['centerLat_list'][i]
    #  x = polygons['centerLon_list'][i]
    #  zipCode = zipCodes[i]
    #  bk.text([x], [y], text=zipCode, angle=0, text_font_size="8pt", text_align="center", text_baseline="middle")

    fonts = [
        "Comic sans MS", "Papyrus", "Curlz", "Impact", "Zapf dingbats",
        "Comic sans MS", "Papyrus", "Curlz", "Impact", "Zapf Dingbats",
        "Comic sans MS"
    ]

    ### Legend
    x = -73.66
    y = 40.50
    #x = -74.25
    #y = 40.9
    for agency, color in agencyColor.iteritems():
        #print "Color: ", a
        #print "x:", x
        #print "y:", y

        bk.rect([x], [y], color=color, width=0.03, height=0.015)
        bk.text([x], [y],
                text=agency,
                angle=0,
                text_font_size="7pt",
                text_align="center",
                text_baseline="middle")
        y = y + 0.015

    #bokeh.embed.components(fig, bokeh.resources.CDN)
    bk.show()
コード例 #33
0
ファイル: start.py プロジェクト: MShaffar19/lab7genomics
def make_plot(xr):
    yr = Range1d(start=-10, end=10)
    figure(plot_width=800,
           plot_height=350,
           y_range=yr,
           x_range=xr,
           tools="xpan,xwheel_zoom,hover,box_zoom,reset")
    hold()
    genes = pd.read_csv('/home/hugoshi/data/lab7/genes.refseq.hg19.bed',
                        sep='\t',
                        skiprows=[0],
                        header=None)
    genes.rename(columns={0: "chromosome", 1: "start", 2: "end"}, inplace=True)
    genes = genes[genes.chromosome == 'chr5']
    g_len = len(genes)
    quad(
        genes.start - 0.5,  # left edge
        genes.end - 0.5,  # right edge
        [2.3] * g_len,  # top edge
        [1.7] * g_len,
        ['blue'] * g_len)  # bottom edge
    exons = pd.read_csv('/home/hugoshi/data/lab7/exons.refseq.hg19.bed',
                        sep='\t',
                        skiprows=[0],
                        header=None)
    exons.columns = ["chromosome", "start", "end", "meta1", "meta2", "meta3"]
    exons = exons[exons.chromosome == 'chr5']
    e_len = len(exons)
    quad(
        exons.start - 0.5,  # left edge
        exons.end - 0.5,  # right edge
        [1.3] * e_len,  # top edge
        [0.7] * e_len,
        ['blue'] * e_len)  # bottom edge

    df = pd.read_csv('/home/hugoshi/data/lab7/CHP2.20131001.hotspots.bed',
                     sep='\t',
                     skiprows=[0],
                     header=None)
    df.columns = ["chromosome", "start", "end", "meta1", "meta2", "meta3"]
    df = df[df.chromosome == 'chr5']
    singles = df[df.start + 1 == df.end]
    widers = df[df.start + 1 != df.end]
    slen = len(singles)
    wlen = len(widers)
    s_source = ColumnDataSource(data=dict(start=singles.start,
                                          end=singles.end,
                                          meta1=singles.meta1,
                                          meta2=singles.meta2,
                                          meta3=singles.meta3))
    rect(
        'start',  # x center
        [1] * slen,  # y center
        [0.9] * slen,
        [1] * slen,
        color=['red'] * slen,
        source=s_source)  # height
    hover = [t for t in curplot().tools if isinstance(t, HoverTool)][0]
    hover.tooltips = OrderedDict([
        # add to this
        ("position", "@start"),
        ("meta 1", "@meta1"),
        ("meta 2", "@meta2"),
        ("meta 3", "@meta3")
    ])

    quad(
        widers.start - 0.5,  # left edge
        widers.end - 0.5,  # right edge
        [0.3] * wlen,  # top edge
        [-0.3] * wlen)  # bottom edge

    hold()
    return curplot()
コード例 #34
0
def plot_points(cells,
                style="circle",
                size=2,
                color=None,
                figure=None,
                **kwargs):
    """
    Plot molecule locations.

    If no colour is explicitly defined, colouring is based on the cell index.

    Arguments:

        cells (Partition):
            full partition

        style (str):
            point marker style

        size (float):
            point marker size (in screen units)

        color (str or numpy.ndarray):
            cell colours

        figure (bokeh.plotting.figure.Figure):
            figure handle

    returns:

        list: handles of the various clouds of points

    """
    # for compatibility with tramway.plot.mesh.plot_points
    try:
        kwargs.pop("min_count")
    except KeyError:
        pass

    if isinstance(cells, np.ndarray):
        points = cells
        label = None
    elif isinstance(cells, pd.DataFrame):
        points = cells[["x", "y"]].values
        label = None
    elif isinstance(cells, Partition):
        points = cells.descriptors(cells.points, asarray=True)
        label = cells.cell_index
        npts = points.shape[0]
        ncells = cells.location_count.size
        # if label is not a single index vector, convert it following
        # tessellation.base.Delaunay.cell_index with `preferred`='force index'.
        merge = mplt.nearest_cell(points, cells.tessellation.cell_centers)
        label = format_cell_index(cells.cell_index,
                                  format="array",
                                  select=merge,
                                  shape=(npts, ncells))

    if isstructured(points):
        x = points["x"]
        y = points["y"]
    else:
        x = points[:, 0]
        y = points[:, 1]

    if figure is None:
        assert False
        try:
            figure = plt.curplot()  # does not work
        except:
            figure = plt.figure()

    handles = []

    if label is None:
        if color is None:
            color = "k"
        elif isinstance(color, (pd.Series, pd.DataFrame)):
            raise NotImplementedError
            color = np.asarray(color)
        if isinstance(color, np.ndarray):
            raise NotImplementedError
            cmin, cmax = np.min(color), np.max(color)
            color = (color - cmin) / (cmax - cmin)
            cmap = plt.get_cmap()
            color = [cmap(c) for c in color]
        else:
            color = long_colour_name(color)
        h = figure.scatter(x,
                           y,
                           marker=style,
                           color=color,
                           size=size,
                           **kwargs)
        handles.append(h)
    else:
        L = np.unique(label)
        if color in [None, "light"]:
            if color == "light" and "alpha" not in kwargs:
                kwargs["alpha"] = 0.2
            if 2 < len(L):
                color = __colors__
                color = ["gray"] + list(
                    itertools.islice(itertools.cycle(color), len(L)))
            elif len(L) == 2:
                color = ["gray", "k"]
            else:
                color = "k"
        elif isinstance(color, str) and L.size == 1:
            color = [color]
        for i, l in enumerate(L):
            clr_i = long_colour_name(color[i])
            h = figure.scatter(x[label == l],
                               y[label == l],
                               marker=style,
                               color=clr_i,
                               size=size,
                               **kwargs)
            handles.append(h)

    ## resize window
    # try:
    #    figure.x_range = Range1d(*cells.bounding_box['x'].values)
    #    figure.y_range = Range1d(*cells.bounding_box['y'].values)
    # except AttributeError:
    #    pass
    # except ValueError:
    #    traceback.print_exc()

    return handles
コード例 #35
0
def plot_trajectories(trajs,
                      color=None,
                      loc_style="circle",
                      figure=None,
                      **kwargs):
    """
    Plot trajectories.

    If no colour is explicitly defined, colouring is based on the trajectory index.

    Arguments:

        trajs (pandas.DataFrame):
            full partition

        loc_style (str):
            location marker style

        loc_size (float):
            location marker size (in screen units)

        color (str or numpy.ndarray):
            trajectory colours

        figure (bokeh.plotting.figure.Figure):
            figure handle

    returns:

        list: handles of the glyphs

    """
    loc_kwargs = {}
    line_kwargs = {}
    for attr in dict(kwargs):
        if attr.startswith("loc_"):
            loc_kwargs[attr[4:]] = kwargs.pop(attr)
        if attr.startswith("line_"):
            if attr == "line_width":
                # compatibility for old bokeh versions
                line_kwargs[attr] = kwargs.pop(attr)
                continue
            line_kwargs[attr[5:]] = kwargs.pop(attr)

    loc_kwargs.update(kwargs)
    line_kwargs.update(kwargs)

    lines_x, lines_y = [], []
    for _, df in trajs.groupby([trajs["n"]]):
        lines_x.append(df["x"].values)
        lines_y.append(df["y"].values)

    if figure is None:
        assert False
        try:
            figure = plt.curplot()  # does not work
        except:
            figure = plt.figure()

    handles = []

    if color is None:
        ntrajs = len(lines_x)
        if color in [None, "light"]:
            if color == "light" and "alpha" not in kwargs:
                kwargs["alpha"] = 0.2
            if 2 < ntrajs:
                color = __colors__
                color = ["gray"] + list(
                    itertools.islice(itertools.cycle(color), ntrajs))
            elif ntrajs == 2:
                color = ["gray", "k"]
            else:
                color = "k"
        elif isinstance(color, str) and ntrajs == 1:
            color = [color]
        for i, line in enumerate(zip(lines_x, lines_y)):
            line_x, line_y = line
            clr_i = long_colour_name(color[i])
            h = figure.line(line_x, line_y, color=clr_i, **line_kwargs)
            handles.append(h)
            h = figure.scatter(line_x,
                               line_y,
                               color=clr_i,
                               marker=loc_style,
                               **loc_kwargs)
            handles.append(h)
    else:
        color = long_colour_name(color)
        h = figure.multi_line(lines_x, lines_y, color=color, **line_kwargs)
        handles.append(h)
        h = figure.scatter(list(itertools.chain(*lines_x)),
                           list(itertools.chain(*lines_y)),
                           color=color,
                           marker=loc_style,
                           **loc_kwargs)
        handles.append(h)

    return handles
コード例 #36
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
コード例 #37
0
ファイル: stedata.py プロジェクト: reedessick/nmodelte
      fig = bplt.figure()
      bplt.hold()

      ### build data source for hover tool
      source = bplt.ColumnDataSource(data=dict(x=all_x, y=all_y, stefilename=all_stefilename, Nmodes=all_Nmodes, Ngens=all_Ngens, Ntriples=all_Ntriples))

      ### plot circle glyphs
      bplt.circle(all_x, all_y, source=source, tools=TOOLS, fill_color=None, fill_alpha=0.6, line_color=all_color, Title="%s vs %s"%(xlabel,  ylabel), plot_width=plot_width, plot_height=plot_height)
#      bplt.circle(all_x, all_y, radius=radii, source=source, tools=TOOLS, fill_color=None, fill_alpha=0.6, line_color=all_color, Title="%s vs %s"%(xlabel,  ylabel))

      ### annotate circle glyphs
#      text(x, y, text=inds, alpha=0.5, text_font_size="5pt", text_baseline="middle", text_align="center", angle=0)

      ### find hover tool, and tell it what to look for
      hover = [t for t in bplt.curplot().tools if isinstance(t, HoverTool)][0]
      hover.tooltips = OrderedDict([ 
                                    #("index", "$index"), 
                                    ("(x,y)", "($x, $y)"),
                                    ("stefilename", "@stefilename"),
                                    ("Nmodes","@Nmodes"),
                                    ("Ntriples","@Ntriples"),
                                    ("Ngens","@Ngens"),
                                   ])

      ### label axes
      bplt.xaxis().axis_label=xlabel
      bplt.yaxis().axis_label=ylabel
      

#  bplt.show() 
コード例 #38
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
コード例 #39
0
ファイル: start.py プロジェクト: B-Rich/lab7genomics
def make_plot(xr):
    yr = Range1d(start=-10, end=10)
    figure(plot_width=800, plot_height=350,
           y_range=yr,
           x_range=xr,
           tools="xpan,xwheel_zoom,hover,box_zoom,reset")
    hold()
    genes = pd.read_csv('/home/hugoshi/data/lab7/genes.refseq.hg19.bed', sep='\t',
                        skiprows=[0], header=None)
    genes.rename(columns={
        0: "chromosome",
        1: "start",
        2: "end"},
                 inplace=True
    )
    genes = genes[genes.chromosome == 'chr5']
    g_len = len(genes)
    quad(genes.start - 0.5,      # left edge
         genes.end - 0.5,        # right edge
         [2.3] * g_len,            # top edge
         [1.7] * g_len,
         ['blue'] * g_len)           # bottom edge
    exons = pd.read_csv('/home/hugoshi/data/lab7/exons.refseq.hg19.bed', sep='\t', skiprows=[0], header=None)
    exons.columns = ["chromosome", "start", "end", "meta1", "meta2", "meta3"]
    exons = exons[exons.chromosome == 'chr5']
    e_len = len(exons)
    quad(exons.start - 0.5,      # left edge
         exons.end - 0.5,        # right edge
         [1.3] * e_len,            # top edge
         [0.7] * e_len,
         ['blue'] * e_len)           # bottom edge

    df = pd.read_csv('/home/hugoshi/data/lab7/CHP2.20131001.hotspots.bed', sep='\t', skiprows=[0], header=None)
    df.columns = ["chromosome", "start", "end", "meta1", "meta2", "meta3"]
    df = df[df.chromosome == 'chr5']
    singles = df[df.start+1 == df.end]
    widers = df[df.start+1 != df.end]
    slen = len(singles)
    wlen = len(widers)
    s_source = ColumnDataSource(
    data = dict(
        start=singles.start,
        end=singles.end,
        meta1=singles.meta1,
        meta2=singles.meta2,
        meta3=singles.meta3))
    rect('start',    # x center
         [1]*slen,         # y center
         [0.9]*slen,
         [1]*slen,
         color=['red']*slen,
         source=s_source)         # height
    hover = [t for t in curplot().tools if isinstance(t, HoverTool)][0]
    hover.tooltips = OrderedDict([
        # add to this
        ("position", "@start"),
        ("meta 1", "@meta1"),
        ("meta 2", "@meta2"),
        ("meta 3", "@meta3")
    ])

    quad(widers.start - 0.5,      # left edge
         widers.end - 0.5,        # right edge
         [0.3] * wlen,            # top edge
         [-0.3] * wlen)           # bottom edge

    hold()
    return curplot()
コード例 #40
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