示例#1
0
def dist_interact(P, S, d_0, n=50):
    # Interactively plot the unconditional distribution of X_n where {X_n, n >= 0} is a DTMC
    xlabels = list(map(str, S))
    p = bplt.figure(x_range=xlabels)  # Create a Bokeh figure
    source = ColumnDataSource(data=dict(x=xlabels, top=d_0))  # Start with d_0
    glyph = VBar(x="x", top="top", bottom=0, width=0.8,
                 fill_color='blue')  # Specify a vertical bar plot
    labels = LabelSet(x='x',
                      y='top',
                      text='top',
                      text_align='center',
                      source=source)  # Label each bar with the value
    p.add_glyph(source, glyph)
    p.add_layout(labels)
    p.yaxis.axis_label = 'd_n'
    p.y_range = Range1d(0, 1)
    handle = None

    def update(n):
        # Function for updating the data and pushing to the figure handle
        source.data['top'] = np.round(
            np.dot(d_0, np.linalg.matrix_power(P, n)), 4)
        if handle is not None:
            push_notebook(handle=handle)

    display(Math(r'$d_0 = ' + pmatrix([d_0], frac=True) +
                 '$'))  # Display initial distribution

    # Interactive slider and plot
    widgets.interact(update,
                     n=widgets.IntSlider(value=0,
                                         min=0,
                                         max=n,
                                         description='n'))
    handle = show(p, notebook_handle=True)
示例#2
0
def create_bar_chart(data, title, x_name, y_name, hover_tool=None):
    """Creates a bar chart plot with the exact styling for the centcom
       dashboard. Pass in data as a dictionary, desired plot title,
       name of x axis, y axis and the hover tool HTML.
    """
    source = ColumnDataSource(data)
    xdr = FactorRange(factors=data[x_name])
    ydr = Range1d(start=0,end=1)

    tools = []
    if hover_tool:
        tools = [hover_tool,]

    plot = figure(title=title, x_range=xdr, y_range=ydr, h_symmetry=True, v_symmetry=True,
                  min_border=0, toolbar_location="above", tools=tools,
                  outline_line_color="#666666")

    glyph = VBar(x=x_name, top=y_name, bottom=0, width=.8)
    plot.add_glyph(source, glyph)

    xaxis = LinearAxis()
    yaxis = LinearAxis()

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
    plot.toolbar.logo = None
    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = "#999999"
    plot.yaxis.axis_label = "Prediction Probability"
    plot.ygrid.grid_line_alpha = 0.1
    plot.xaxis.axis_label = "Recommend Prediction"
    plot.xaxis.major_label_orientation = 1
    return plot
示例#3
0
def create_bar_chart(data,
                     title,
                     x_name,
                     y_name,
                     hover_tool=None,
                     width=1200,
                     height=300):
    """
    Creates a bar chart plot with the exact styling for the centcom
       dashboard. Pass in data as a dictionary, desired plot title,
       name of x axis, y axis and the hover tool HTML.
    """
    source = ColumnDataSource(data)

    xdr = FactorRange(
        factors=data[x_name])  # xdr = FactorRange(factors=data[x_name])

    ydr = Range1d(start=0, end=max(data[y_name]))

    tools = []
    if hover_tool:
        tools = [
            hover_tool,
        ]

    plot = figure(title=title,
                  x_range=xdr,
                  y_range=ydr,
                  plot_width=width,
                  plot_height=height,
                  h_symmetry=False,
                  v_symmetry=False,
                  min_border=0,
                  toolbar_location="above",
                  tools=tools,
                  responsive=True,
                  outline_line_color="#666666")

    glyph = VBar(x=x_name,
                 top=y_name,
                 bottom=0,
                 width=.8,
                 fill_color="#e12127")
    plot.add_glyph(source, glyph)

    xaxis = LinearAxis()
    yaxis = LinearAxis()

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
    plot.toolbar.logo = None
    plot.min_border_top = 0
    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = "#999999"
    plot.yaxis.axis_label = "Count"
    plot.ygrid.grid_line_alpha = 0.1
    plot.xaxis.axis_label = "Bins"
    plot.xaxis.major_label_orientation = 1
    plot.xaxis.minor_tick_line_color = "orange"
    return plot
示例#4
0
def sort(idx, metric):
    if metric == 'Layer':
        metric_idx = -2
    else:
        metric_idx = metric_names.index(metric)

    tmp_metrics = metrics.copy()
    reverse = True
    if metric == 'Average distance ratio' or metric == 'Layer':
        reverse = False
    tmp_metrics = sorted(tmp_metrics,
                         key=lambda a: a[1 + metric_idx],
                         reverse=reverse)
    xs_tmp = [metric[-1] + 1 for metric in tmp_metrics]
    for jdx, i in enumerate(xs_tmp):
        xs[idx][i - 1] = jdx + 1
    sources[idx] = ColumnDataSource(dict(x=xs[idx], top=ys[idx]))

    plots[idx].renderers.remove(renderers[idx])
    plots[idx].xaxis.ticker = [i + 1 for i in range(len(xs[idx]))]

    override = {}
    for i in range(len(metrics)):
        override[xs[idx][i]] = str(i + 1)
    plots[idx].xaxis.major_label_overrides = override

    renderers[idx] = plots[idx].add_glyph(
        sources[idx], VBar(x='x', top='top', bottom=0, width=0.2))
def create_bar_chart(data, title, x_name, y_name, hover_tool = None, width = 1200, height = 300):
	source = ColumnDataSource(data)
	xdr = FactorRange("0 < i < 0.01", "0.01 <= i < 0.1", "0.1 <= i < 1", "1 <= i < 5", "5 <= i < 25", "25 <= i < 50", "50 <= i < 250", "250 <= i < 1000", "i => 1000")
	ydr = Range1d(start = 0, end = max(data[y_name])*1.1)

	tools = []
	if hover_tool:
		tools = [hover_tool]

	plot = figure(title=title, x_range=xdr, y_range=ydr, plot_width=width,
                  plot_height=height, h_symmetry=False, v_symmetry=False,
                  min_border=0, toolbar_location="above", tools=tools,
                  responsive=True, outline_line_color="#666666")

	glyph = VBar(x = x_name, top = y_name, bottom = 0, width = 0.8, fill_color = "#e12127")
	plot.add_glyph(source, glyph)

	xaxis = LinearAxis()
	yaxis = LinearAxis()

	plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
	plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
	plot.toolbar.logo = None
	plot.min_border_top = 0
	plot.xgrid.grid_line_color = None
	plot.ygrid.grid_line_color = "#999999"
	plot.yaxis.axis_label = "Number of transactions"
	plot.ygrid.grid_line_alpha = 0.1
	plot.xaxis.axis_label = "Amount of BTC transacted (i = transaction value)"
	plot.xaxis.major_label_orientation = 1
	return plot
示例#6
0
def init_mention_plot():
    cprint('%s: init @ mentios barcharts...' % TAG, 'yellow', attrs=['bold'])
    global mention_count
    global mention_barplot
    mention_count = count_mentions()
    y = []
    mentions = []
    for (mention, freq) in mention_count:
        y.append(freq)
        mentions.append(mention)
    x = np.arange(len(mentions))
    source = ColumnDataSource(dict(
        x=x,
        top=y,
    ))
    glyph = VBar(x='x', top='top', bottom=0, width=0.85, fill_color='#ff7f0e')
    mention_barplot.add_glyph(source, glyph)

    xaxis = LinearAxis()
    xaxis.ticker = x
    xaxis.major_label_overrides = {
        i: mention
        for i, mention in enumerate(mentions)
    }
    mention_barplot.add_layout(xaxis, 'below')
    mention_barplot.xaxis.major_label_orientation = +np.pi / 2

    yaxis = LinearAxis()
    yaxis.axis_label = 'Overall number of @ mentions'
    yaxis.axis_label_text_font_size = '14pt'
    yaxis.ticker = np.linspace(0, max(y), 11, dtype=np.int)[1:]
    mention_barplot.add_layout(yaxis, 'left')

    mention_barplot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    mention_barplot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
示例#7
0
def create_bar_chart(data, title, x_name, y_name, hover_tool = None, width = 1200, height = 300):
	source = ColumnDataSource(data)
	xdr = FactorRange(factors = data[x_name])
	ydr = Range1d(start = 250000, end = 450000)

	tools = []
	if hover_tool:
		tools = [hover_tool]

	plot = figure(title=title, x_range=xdr, y_range=ydr, plot_width=width,
                  plot_height=height, h_symmetry=False, v_symmetry=False,
                  min_border=0, toolbar_location="above", tools=tools,
                  responsive=True, outline_line_color="#666666")

	glyph = VBar(x = x_name, top = y_name, bottom = 0, width = 0.8, fill_color = "#e12127")
	plot.add_glyph(source, glyph)

	xaxis = LinearAxis()
	yaxis = LinearAxis()

	plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
	plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
	plot.toolbar.logo = None
	plot.min_border_top = 0
	plot.xgrid.grid_line_color = None
	plot.ygrid.grid_line_color = "#999999"
	plot.yaxis.axis_label = "Value of transaction (BTC)"
	plot.ygrid.grid_line_alpha = 0.1
	plot.xaxis.axis_label = "Transaction Block Number"
	plot.xaxis.major_label_orientation = 1
	return plot
示例#8
0
def draw_vol():
    g1 = VBar(x='T',
              top='V',
              bottom=0,
              width=timeframe * 1000 - 2,
              fill_color='cyan',
              line_color='black')
    return g1
示例#9
0
def draw_stand_candles():
    global timeframe
    g1 = VBar(x='T',
              top='O',
              bottom='C',
              width=timeframe * 1000 - 2,
              fill_color='black',
              line_color='black')

    return g1
示例#10
0
def create_bar_chart(data,
                     title,
                     x_name,
                     y_name,
                     hover_tool=None,
                     width=1100,
                     height=400):
    """Creates a bar chart plot with the exact styling for the centcom
       dashboard. Pass in data as a dictionary, desired plot title,
       name of x axis, y axis and the hover tool HTML.
    """
    source = ColumnDataSource(data)
    xdr = FactorRange(factors=list(data[x_name]))
    ydr = Range1d(start=0, end=max(data[y_name]) * 1.05)

    tools = []
    if hover_tool:
        tools = [
            hover_tool,
        ]

    plot = figure(title=title,
                  x_range=xdr,
                  y_range=ydr,
                  plot_width=width,
                  plot_height=height,
                  min_border=0,
                  toolbar_location="above",
                  tools=tools,
                  outline_line_color="#666666")

    glyph = VBar(x=x_name,
                 top=y_name,
                 bottom=0,
                 width=.8,
                 fill_color="#ffdf00")
    plot.add_glyph(source, glyph)
    plot.add_tools(WheelZoomTool())
    plot.add_tools(BoxZoomTool())
    plot.add_tools(ZoomOutTool())

    xaxis = LinearAxis()
    yaxis = LinearAxis()

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
    plot.toolbar.logo = None
    plot.min_border_top = 0
    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = "#999999"
    plot.yaxis.axis_label = "Weight"
    plot.ygrid.grid_line_alpha = 0.1
    plot.xaxis.axis_label = "Grouping"
    plot.xaxis.major_label_orientation = 1
    return plot
示例#11
0
def create_bar_chart(data,
                     title,
                     x_name,
                     y_name,
                     hover_tool=None,
                     width=1200,
                     height=300):
    """Создаёт столбчатую диаграмму.
        Принимает данные в виде словаря, подпись для графика,
        названия осей и шаблон подсказки при наведении.
    """
    source = ColumnDataSource(data)
    xdr = FactorRange(factors=data[x_name])
    ydr = Range1d(start=0, end=max(data[y_name]) * 1.5)

    tools = []
    if hover_tool:
        tools = [
            hover_tool,
        ]

    plot = figure(title=title,
                  x_range=xdr,
                  y_range=ydr,
                  plot_width=width,
                  plot_height=height,
                  h_symmetry=False,
                  v_symmetry=False,
                  min_border=0,
                  toolbar_location="above",
                  tools=tools,
                  responsive=True,
                  outline_line_color="#666666")

    glyph = VBar(x=x_name,
                 top=y_name,
                 bottom=0,
                 width=.8,
                 fill_color="#e12127")
    plot.add_glyph(source, glyph)

    xaxis = LinearAxis()
    yaxis = LinearAxis()

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
    plot.toolbar.logo = None
    plot.min_border_top = 0
    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = "#999999"
    plot.yaxis.axis_label = "Bugs found"
    plot.ygrid.grid_line_alpha = 0.1
    plot.xaxis.axis_label = "Days after app deployment"
    plot.xaxis.major_label_orientation = 1
    return plot
示例#12
0
def create_bar_chart(data,
                     title,
                     x_name,
                     y_name,
                     hover_tool=None,
                     width=1200,
                     height=300):
    """
    Création d'un bargraph qui compte l'occurence du nombre d'album dans le top 200 (seules les 20 premieres valeurs sont affichées)
    """
    source = ColumnDataSource(data)
    xdr = FactorRange(factors=data[x_name])
    ydr = Range1d(start=0, end=max(data[y_name]) * 1.5)

    tools = []
    if hover_tool:
        tools = [
            hover_tool,
        ]

    plot = figure(title=title,
                  x_range=xdr,
                  y_range=ydr,
                  plot_width=width,
                  plot_height=height,
                  h_symmetry=False,
                  v_symmetry=False,
                  min_border=0,
                  toolbar_location="above",
                  tools=tools,
                  outline_line_color="#666666")

    glyph = VBar(x=x_name,
                 top=y_name,
                 bottom=0,
                 width=.8,
                 fill_color="#e8ddb5")
    plot.add_glyph(source, glyph)

    xaxis = LinearAxis()
    yaxis = LinearAxis()

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
    plot.toolbar.logo = None
    plot.min_border_top = 0
    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = "#999999"
    plot.yaxis.axis_label = "Number of albums"
    plot.ygrid.grid_line_alpha = 0.1
    plot.xaxis.major_label_orientation = 1
    return plot
示例#13
0
def test_VBar():
    glyph = VBar()
    assert glyph.x is None
    assert glyph.width is None
    assert glyph.top is None
    assert glyph.bottom == 0
    check_fill_properties(glyph)
    check_line_properties(glyph)
    check_properties_existence(glyph, [
        "x",
        "width",
        "top",
        "bottom",
    ], FILL, LINE, GLYPH)
示例#14
0
def test_VBar():
    glyph = VBar()
    assert glyph.x is None
    assert glyph.width is None
    assert glyph.top is None
    assert glyph.bottom == 0
    yield check_fill, glyph
    yield check_line, glyph
    yield (check_props, glyph, [
        "x",
        "width",
        "top",
        "bottom",
    ], FILL, LINE)
示例#15
0
def bar_glyphs(data, xlabels=None):
    fields = data.columns.values
    sources = dict(zip(fields, np.zeros(len(fields))))
    glyphs = dict(zip(fields, np.zeros(len(fields))))
    for field in fields:
        if xlabels is None:
            x = data[field].index
            width = 1
        else:
            x = xlabels
            width = 1
        sources[field] = ColumnDataSource(data=dict(x=x, top=data[field].values))
        glyphs[field] = VBar(x="x", top="top", bottom=0, width=width, fill_color='blue')
    return sources, glyphs
示例#16
0
def test_VBar() -> None:
    glyph = VBar()
    assert glyph.x == field("x")
    assert glyph.width is None
    assert glyph.top is None
    assert glyph.bottom == 0
    check_fill_properties(glyph)
    check_hatch_properties(glyph)
    check_line_properties(glyph)
    check_properties_existence(glyph, [
        "x",
        "width",
        "top",
        "bottom",
    ], FILL, HATCH, LINE, GLYPH)
def create_bar_chart(data, title, x_name, y_name, width=1200, height=300):
    source = ColumnDataSource(data)
    xdr = FactorRange(factors=data[x_name])
    ydr = Range1d(start=0, end=max(data[y_name]) * 1.5)

    plot = figure(title=title, x_range=xdr, y_range=ydr)
    glyph = VBar(x=x_name, top=y_name, bottom=0, width=.8)
    plot.add_glyph(source, glyph)

    xaxis = LinearAxis()
    yaxis = LinearAxis()

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

    return plot
示例#18
0
def hist_glyphs(data, bins=None):
    fields = data.columns.values
    sources = dict(zip(fields, np.zeros(len(fields))))
    glyphs = dict(zip(fields, np.zeros(len(fields))))
    for field in fields:
        if bins is None:
            counts = pd.Series(data[field].value_counts(sort=False, ascending=True).sort_index())
            x = counts.index
            width = 1
        else:
            counts = pd.Series(data[field].value_counts(sort=False, ascending=True, bins=bins).sort_index())
            x = counts.index.values.mid
            width = np.mean(counts.index.length)
        sources[field] = ColumnDataSource(data=dict(x=x, top=counts.values))
        glyphs[field] = VBar(x="x", top="top", bottom=0, width=width, fill_color='blue')
    
    return sources, glyphs
示例#19
0
文件: app.py 项目: wushuzh/barchart
def create_bar_chart(data,
                     title,
                     x_name,
                     y_name,
                     hover_tool=None,
                     width=1200,
                     height=300):
    """Creates a barchart plot with the exact styling for the centcom
       dashboard, Pass in data as a dictionary, desired plot title,
       name of x axis, y axis.
    """
    source = ColumnDataSource(data)
    xdr = FactorRange(factors=data[x_name])
    ydr = Range1d(start=0, end=max(data[y_name]) * 1.5)

    tools = []
    if hover_tool:
        tools = [
            hover_tool,
        ]

    plot = figure(title=title,
                  x_range=xdr,
                  y_range=ydr,
                  tools=tools,
                  plot_width=width,
                  plot_height=height,
                  toolbar_location="above")

    glyph = VBar(x=x_name, width=.8, top=y_name, fill_color="#e12127")
    plot.add_glyph(source, glyph)

    xaxis = LinearAxis()
    yaxis = LinearAxis()

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
    plot.yaxis.axis_label = "Bugs found"
    plot.xaxis.axis_label = "Days after app deployment"

    plot.toolbar.logo = None
    plot.xgrid.grid_line_color = None
    plot.xaxis.major_label_orientation = 1

    return plot
示例#20
0
def init_user_plot():
    cprint('%s: init @ users barcharts...' % TAG, 'yellow', attrs=['bold'])
    global user_count
    global user_barplot
    user_count = count_users()
    y = []
    users = []
    for (user, freq) in user_count.items():
        y.append(freq)
        users.append(user)
    x = np.arange(len(users))

    wlist = []
    for user in users:
        prefixes = ['@' + user]
        for prefix, freq in sorted(user_tweet_freq[user].items(),
                                   key=lambda kv: kv[1],
                                   reverse=True)[:10]:
            prefixes.append(' %s:%d' % (prefix, freq))
        wlist.append(list(prefixes))

    source = ColumnDataSource(dict(x=x, top=y, wlist=wlist))
    glyph = VBar(x='x', top='top', bottom=0, width=0.85, fill_color='#1f77b4')
    user_barplot.add_glyph(source, glyph)

    xaxis = LinearAxis()
    xaxis.ticker = x
    xaxis.major_label_overrides = {
        i: '@' + user
        for i, user in enumerate(users)
    }
    #xaxis.major_label_standoff = -35
    user_barplot.add_layout(xaxis, 'below')
    user_barplot.xaxis.major_label_orientation = +np.pi / 2

    yaxis = LinearAxis()
    yaxis.axis_label = 'Overall number of tweets per @'
    yaxis.axis_label_text_font_size = '14pt'
    yaxis.ticker = np.linspace(0, max(y), 11, dtype=np.int)[1:]
    user_barplot.add_layout(yaxis, 'left')

    user_barplot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    user_barplot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
示例#21
0
def create_bar_chart(data, title, x_name, y_name, hover_tool=None,
                     width=1200, height=300):
    """
        Creates a bar chart plot with the exact styling for the centcom
        dashboard. Pass in data as a dictionary, desired plot title,
        name of x axis, y axis and the hover tool HTML.
        
    """
    source = ColumnDataSource(data)
    xdr = FactorRange(factors=data[x_name])
    ydr = Range1d(start=0,end=max(data[y_name])*1.5)

    tools = []

    if hover_tool:
        tools = [hover_tool,]

    plot = figure(title=title, x_range=xdr, y_range=ydr, plot_width=width,  x_axis_type="datetime", 
                  plot_height=height,
                  min_border=0, toolbar_location="above", tools=tools, sizing_mode='fixed',
                  outline_line_color="#666666")

    glyph = VBar(x=x_name, top=y_name, bottom=0, width=.8,
                 fill_color="#e12127")
    plot.add_glyph(source, glyph)

    plot.xaxis.ticker = DaysTicker(days=np.arange(1,32))

    xaxis = LinearAxis()
    yaxis = LinearAxis()

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
    plot.toolbar.logo = None
    plot.min_border_top = 0
    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = "#999999"
    plot.yaxis.axis_label = "Bugs found"
    plot.ygrid.grid_line_alpha = 0.1
    plot.xaxis.axis_label = "Days after app deployment"
    plot.xaxis.major_label_orientation = 1

    return plot
示例#22
0
    def drawGraph(self, **options):

        p = []
        source = []
        iterator = 0
        for hisTitle, projectionList in zip(*[iter(self.selectionList)] * 2):
            dimList = list(map(int, projectionList))
            nDim = len(dimList)
            if nDim > 1:
                raise NotImplementedError(
                    "Sorry!!.. Multidimensional projections have not been implemented, yet"
                )
            histogram = self.histArray.FindObject(hisTitle).Projection(
                dimList[0])
            cds = makeCDS(histogram)
            histLabel = histogram.GetTitle()
            xLabel = histogram.GetXaxis().GetTitle()
            yLabel = histogram.GetYaxis().GetTitle()
            localHist = figure(title=histLabel,
                               tools=options['tooltips'],
                               background_fill_color=options['bg_color'],
                               y_axis_type=options['y_axis_type'],
                               x_axis_type=options['x_axis_type'])
            glyph = VBar(top='value',
                         x='bin',
                         width=abs(cds.data['bin'][2] - cds.data['bin'][1]) /
                         1.5,
                         fill_color=options['color'],
                         line_color=options['line_color'])
            localHist.add_glyph(cds, glyph)
            localHist.y_range.start = 0
            localHist.xaxis.axis_label = xLabel
            localHist.yaxis.axis_label = yLabel
            source.append(cds)
            p.append(localHist)
            iterator = iterator + 1
        pAll = gridplot(p,
                        ncols=options['nCols'],
                        plot_width=options['plot_width'],
                        plot_height=options['plot_height'])
        handle = show(pAll, notebook_handle=True)
        return pAll, handle, source
示例#23
0
vbar_renderer = p2.vbar(  # creates bars
    x='x',
    top='y',
    width=0.5,
    source=sourcep2,  # defines source
    color='blue',  # default color of the bars

    # properties of selected / unselected bars
    #selection_fill_alpha = 1.0,                     # opacity of selected bar
    #nonselection_fill_alpha=0.2,                    # opacity of non-selected bar
)
from bokeh.models.glyphs import VBar
vbar_selected = VBar(fill_alpha=0.2,
                     fill_color='blue',
                     line_color='blue',
                     hatch_pattern='right_diagonal_line',
                     hatch_color='blue',
                     hatch_alpha=1.0,
                     hatch_weight=0.5)
vbar_nonselected = VBar(fill_alpha=0.2, fill_color='blue', line_color='blue')
vbar_renderer.selection_glyph = vbar_selected
vbar_renderer.nonselection_glyph = vbar_nonselected

p2.xgrid.grid_line_color = None  # removes gridlines

picker = ColorPicker(
    title="Line Color")  # allows to change the color of the bars
picker.js_link(
    'color', vbar_renderer.selection_glyph,
    'fill_color')  # link the selected bar color properties to the selector
picker.js_link('color', vbar_renderer.selection_glyph, 'line_color')
示例#24
0
redo_1exp_btn = Button(label="Redo experiment")

# tracks if one of the parameter changed to know if we start the stats from
# 0 again
has_param_changed = True

source_1exp = ColumnDataSource(data=dict(n=[], error=[]))

p_1exp = figure(plot_height=350,
                title="1 time error",
                x_axis_type="log",
                y_range=[0, 100],
                tools="ypan, ywheel_pan, ywheel_zoom",
                y_axis_label="error",
                x_axis_label="nb participants")
glyph = VBar(x='n', top='error', bottom=0.1, width="n", hatch_scale=None)
p_1exp.add_glyph(source_1exp, glyph)
p_1exp.y_range.start = 0
p_1exp.x_range.range_padding = 0.1
p_1exp.xaxis.major_label_orientation = 1
p_1exp.xgrid.grid_line_color = None


def modular_abs(x, y, p):
    return (min((x - y) % p, (y - x) % p))


def update_1exp():
    sanitize_params()
    eps_val = float(eps.value)
    small_delta_val = float(small_delta.value)
示例#25
0
def meditation_figs(data, height=500, width=1300):
    #Timeseries Plot
    bz_daily = BoxZoomTool()
    wz_cumu = WheelZoomTool(dimensions='width')

    plot_daily_tools = [
        PanTool(dimensions='width'), bz_daily,
        ResetTool(),
        SaveTool()
    ]
    plot_cumu_tools = [
        PanTool(dimensions='width'), wz_cumu,
        ResetTool(),
        SaveTool()
    ]

    data['date_str'] = data['date'].map(str)

    cds_w = ColumnDataSource(
        dict(date=data['date'],
             date_str=data['date_str'],
             meditation_time=data['meditation_time']))
    cds_s = ColumnDataSource(
        dict(date=data['date'],
             date_str=data['date_str'],
             meditation_time=data['meditation_time']))

    d = cds_w.data
    d_s = cds_w.data

    #Calculate weeklong MA value, and cumulative value
    m_t_ma, m_t_c = [], []

    # #MA (inital values: 10;0;0;10;10;10;10)
    m_t_ma.append(10.0)
    m_t_ma.append(5.0)
    m_t_ma.append(3.33)
    m_t_ma.append(5.0)
    m_t_ma.append(6.0)
    m_t_ma.append(6.67)
    m_t_ma.append(7.14)

    for j in range(7, len(d['date'])):
        m_t_ma.append(
            (d['meditation_time'][j] + d['meditation_time'][j - 1] +
             d['meditation_time'][j - 2] + d['meditation_time'][j - 3] +
             d['meditation_time'][j - 4] + d['meditation_time'][j - 5] +
             d['meditation_time'][j - 6]) / 7.0)

    # print(d['date'].count())
    # print(d.get(datetime.date(2018,12,30)))
    cds_w.add(m_t_ma, name='m_t_ma')

    #Cumu (inital value: 10)
    m_t_c.append(10.0)

    for k in range(1, d['date'].count()):
        m_t_c.append(d['meditation_time'][k] + m_t_c[-1])

    cds_w.add(m_t_c, name='m_t_c')

    #PLOT DAILY
    plot_daily = figure(x_axis_type="datetime",
                        title="Daily Meditation",
                        h_symmetry=False,
                        v_symmetry=False,
                        min_border=0,
                        plot_height=height,
                        plot_width=width,
                        toolbar_location="above",
                        outline_line_color="#666666",
                        tools=plot_daily_tools)
    glyph = VBar(x="date",
                 top="meditation_time",
                 bottom=0,
                 width=.8,
                 fill_color="#41A2E8",
                 line_color="#41A2E8")
    plot_daily.add_glyph(cds_w, glyph)
    plot_daily.line('date',
                    'm_t_ma',
                    name='m_t_ma',
                    source=cds_w,
                    line_color="#8B0A50",
                    line_width=3,
                    line_alpha=0.6,
                    legend="Moving Average (7 days)")

    plot_daily.legend.location = "top_left"
    plot_daily.legend.click_policy = "hide"
    plot_daily.yaxis.axis_label = "Minutes"

    #plot_daily.Bar('date', 'meditation_time', source=cds_w, name='meditation_time')
    plot_cumu = figure(x_axis_type="datetime",
                       title="Cumulative Meditation",
                       h_symmetry=False,
                       v_symmetry=False,
                       min_border=0,
                       plot_height=height,
                       plot_width=width,
                       toolbar_location="above",
                       outline_line_color="#666666",
                       active_scroll=wz_cumu,
                       tools=plot_cumu_tools)

    glyph = VBar(x="date",
                 top="m_t_c",
                 bottom=0,
                 width=.8,
                 fill_color="#41A2E8",
                 line_color="#41A2E8")
    plot_cumu.add_glyph(cds_w, glyph)
    plot_cumu.yaxis.visible = False

    #plot_daily = Histogram(cds_w, 'meditation_time', title="Daily Meditation", plot_height=height, plot_width=width, active_scroll=wz)

    #plot_cumu = Histogram(cds_w, 'meditation_time', title="Daily Meditation", plot_height=height, plot_width=width, active_scroll=wz)
    #plot_max = figure(x_axis_type="datetime", title="MAXes", h_symmetry=False, v_symmetry=False, min_border=0, plot_height=height, plot_width=width, toolbar_location="above", outline_line_color="#666666", active_scroll=wz_max,tools=plot_max_tools_d)

    script, (plot_daily_div, plot_cumu_div) = components(
        (plot_daily, plot_cumu))

    return script, plot_daily_div, plot_cumu_div
示例#26
0
def create_line_chart(data,
                      title,
                      x_name,
                      y_name,
                      hover_tool=None,
                      width=800,
                      height=300,
                      fill_color="#fcb900"):
    """Creates a bar chart plot with the exact styling for the centcom
       dashboard. Pass in data as a dictionary, desired plot title,
       name of x axis, y axis and the hover tool HTML.
    """
    source = ColumnDataSource(data)
    xdr = FactorRange(factors=data[x_name])
    ydr = Range1d(start=0, end=max(data[y_name]) * 1.5)

    tools = []
    if hover_tool:
        tools = [
            hover_tool,
        ]

    plot = figure(title=title,
                  x_range=xdr,
                  y_range=ydr,
                  plot_width=width,
                  plot_height=height,
                  h_symmetry=False,
                  v_symmetry=False,
                  min_border=0,
                  toolbar_location="above",
                  tools=tools,
                  responsive=True,
                  outline_line_color="#666666",
                  background_fill_alpha=0.0,
                  border_fill_alpha=0.0)

    #glyph = Line(x=x_name, y=y_name, line_color="#F46D43", line_width=6, line_alpha=0.6)
    glyph = VBar(x=x_name,
                 top=y_name,
                 bottom=0,
                 width=1,
                 fill_color=fill_color)
    #glyph2 = VBar(x=x_name, top='costs', bottom=0, width=1, fill_color='#e12127')
    #e12127
    plot.add_glyph(source, glyph)
    #plot.add_glyph(source, glyph2)

    xaxis = LinearAxis()
    yaxis = LinearAxis()

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
    plot.toolbar.logo = None
    plot.min_border_top = 0
    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = "#999999"
    plot.yaxis.axis_label = "usage"
    plot.ygrid.grid_line_alpha = 0.1
    plot.xaxis.axis_label = "days"
    plot.xaxis.major_label_orientation = 1
    return plot
示例#27
0
文件: VBar.py 项目: PhilWa/bokeh-1
))

xdr = DataRange1d()
ydr = DataRange1d()

plot = Plot(title=None,
            x_range=xdr,
            y_range=ydr,
            plot_width=300,
            plot_height=300,
            h_symmetry=False,
            v_symmetry=False,
            min_border=0,
            toolbar_location=None)

glyph = VBar(x="x", top="top", bottom=0, width=0.5, fill_color="#b3de69")
plot.add_glyph(source, glyph)

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

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

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

curdoc().add_root(plot)

show(plot)
    def generate_plot(self):
        """Calculates mean and standard deviation for measure(s) by model,
        then generates a bar plot of model vs mean performance.

        TODO: Finish this doc.

        """

        # Use this for a built-in bar plot instead,
        # but doesn't work with custom hover tool
        #p = Bar(self.data,label='modelname',values=self.measure,agg='mean',\
        #        title='Mean %s Performance By Model'%self.measure,legend=None,\
        #        tools=tools, color='modelname')
        #self.script,self.div = components(p)
        #return

        # TODO: hardcoded self.measure[0] for now, but should incorporate
        #       a for loop somewhere to subplot for each selected measure

        # TODO: add significance information (see plot_bar_pretty
        #       and randttest in narf_analysis)

        # build new pandas series of stdev values to be added to dataframe
        # if want to show more info on tooltip in the future, just need
        # to build an appropriate series to add and then build its tooltip
        #in the create_hover function

        modelnames = self.data.index.levels[0].tolist()
        stdev_col = pd.Series(index=modelnames)
        mean_col = pd.Series(index=modelnames)
        median_col = pd.Series(index=modelnames)
        n_cells_col = pd.Series(index=modelnames)
        #for each model, find the stdev and mean over the measure values, then
        #assign those values to new Series objects to use for the plot
        for model in modelnames:
            values = self.data[self.measure[0]].loc[model]
            stdev = values.std(skipna=True)
            mean = values.mean(skipna=True)
            median = values.median(skipna=True)
            if (math.isnan(stdev)) or (math.isnan(mean)) or (math.isnan(median)):
                # If either statistic comes out as NaN, entire column was NaN,
                # so model doesn't have the necessary data.
                continue
            stdev_col.at[model] = stdev
            mean_col.at[model] = mean
            median_col.at[model] = median
            n_cells_col.at[model] = values.count()

        newData = pd.DataFrame.from_dict({
                'stdev':stdev_col, 'mean':mean_col, 'median':median_col,
                'n_cells':n_cells_col,
                })
        # Drop any models with NaN values, since that means they had no
        # performance data for one or more columns.
        newData.dropna(axis=0, how='any', inplace=True)
        if newData.size == 0:
            self.script,self.div = (
                    "Error, no plot to display.",
                    "None of the models contained valid performance data."
                    )
            return
        dat_source = ColumnDataSource(newData)

        tools = [
                PanTool(), SaveTool(), WheelZoomTool(),
                ResetTool(), self.create_hover()
                ]
        xrange = FactorRange(factors=modelnames)
        yrange = Range1d(
                start=0,
                end=(max(newData['mean'])*1.5)
                )
        p = figure(
                x_range=xrange, x_axis_label=(
                        "Modelname, prefix: {0}, suffix: {1}"
                        .format(self.pre, self.suf)
                        ),
                y_range=yrange, y_axis_label='Mean %s'%self.measure[0],
                title="Mean %s Performance By Model"%self.measure[0],
                tools=tools, responsive=True, toolbar_location=TOOL_LOC,
                toolbar_sticky=TOOL_STICK,
                output_backend="svg"
                )
        p.xaxis.major_label_orientation=-(np.pi/4)
        glyph = VBar(
                x='index', top='mean', bottom=0, width=VBAR_WIDTH,
                fill_color=VBAR_FILL, line_color='black'
                )
        p.add_glyph(dat_source,glyph)

        # workaround to prevent title and toolbar from overlapping
        grid = gridplot(
            [p], ncols=GRID_COLS, responsive=True,
            )
        self.script, self.div = components(grid)
示例#29
0
for colRef,bar in enumerate(ylist,1):
    y.append(calcEnergy(condf,bar))
    colorList.append(Category10[(len(ylist)+2)][colRef])
    
barDict = dict(x=ylist, top=y, col = colorList)

barDS = ColumnDataSource((barDict))


for colRef,line in enumerate(ylist,1):
    lines = fig.line(x='DateTime', y=line, source=dataSource, 
                 color = Category10[(len(ylist)+2)][colRef],
                line_width=2) 

bars = VBar(x='x', top='top',width=0.5,
            line_color='col',
           fill_color='col')
barfig.add_glyph(barDS, bars)

fig.outline_line_color = None
fig.background_fill_color = "#efefef"

fig.xaxis.formatter = DatetimeTickFormatter(days = [ '%a%e-%b'])
fig.xaxis.minor_tick_line_color = 'black'

#fig.axis.major_tick_line_color = None
fig.axis.axis_line_color = 'black'
fig.y_range.start=0
barfig.y_range.start=0
#fig.yaxis.axis_label = 'Total electricity supplied in Quarter (TWh)'
示例#30
0
def plot_va(filename, tag, kind, color=DEFAULT_COLOR, orient='horizontal'):
    bp.curdoc().clear()

    title = verbose_kinds[kind] + ' variability analysis for {} iJO1366 model'\
                                    .format(tag)
    data = pd.read_csv(os.path.join(outputs_folder, filename), index_col=0)

    if not data.columns[0] in ['minimum', 'maximum']:
        data.columns = ['minimum', 'maximum']

    data += 1e-9  # Resolution of the solver
    f = lambda x: np.sqrt(x[0] * x[1])
    # data['score'] = data.mean(axis=1)
    data['score'] = data.apply(f, axis=1)
    data.sort_values(by='score', ascending=False, inplace=True)
    data['y'] = range(len(data))
    data['name'] = data.index

    source = ColumnDataSource(data)

    xdr = DataRange1d()
    ydr = DataRange1d()

    _tools_to_show = 'box_zoom,pan,save,hover,reset,tap,wheel_zoom'

    if orient == 'vertical':
        p1 = bp.figure(
            title=title,
            x_range=xdr,
            y_range=ydr,
            x_axis_type='log',
            plot_width=600,
            plot_height=1000,
            tools=_tools_to_show,
            # h_symmetry=False, v_symmetry=False,
            min_border=0)
        glyph = HBar(y="y",
                     right="maximum",
                     left="minimum",
                     height=0.9,
                     fill_color=color,
                     fill_alpha=0.5,
                     line_color=None)
        p1.add_glyph(source, glyph)

        p1.circle(x='score',
                  y='y',
                  fill_color=color,
                  line_color=None,
                  source=source)
        axis1 = p1.xaxis
        axis2 = p1.yaxis
    elif orient == 'horizontal':
        p1 = bp.figure(
            title=title,
            x_range=ydr,
            y_range=xdr,
            y_axis_type='log',
            plot_width=1000,
            plot_height=600,
            tools=_tools_to_show,
            # h_symmetry=False, v_symmetry=False,
            min_border=0)

        glyph = VBar(x="y",
                     top="maximum",
                     bottom="minimum",
                     width=0.9,
                     fill_color=color,
                     fill_alpha=0.5,
                     line_color=None)
        p1.add_glyph(source, glyph)

        p1.circle(y='score',
                  x='y',
                  fill_color=color,
                  line_color=None,
                  source=source)
        axis1 = p1.yaxis
        axis2 = p1.xaxis
    else:
        raise ValueError("orient should be 'vertical' or 'horizontal'")

    # Fix ticks
    label_dict = {}
    for i, s in enumerate(data.index):
        label_dict[i] = s
    axis2.formatter = FuncTickFormatter(code="""
                                            var labels = %s;
                                            return labels[tick];
                                        """ % label_dict)
    axis1.axis_label = '[{}]'.format(verbose_kinds[kind])

    # p1.yaxis.ticker = [x for x in range(len(data))]

    hover = p1.select(dict(type=HoverTool))
    hover.tooltips = [
        (verbose_kinds[kind], "@name"),
        ("min", "@minimum"),
        ("max", "@maximum"),
    ]
    hover.mode = 'mouse'

    path = os.path.join(plots_folder, 'va_' + filename)
    bp.output_file(path + '.html')
    bp.show(p1)
    p1.output_backend = 'svg'
    export_svgs(p1, filename=path + '.svg')
    bp.curdoc().clear()

    return data