def area_charts():
    defaults.width = 400
    defaults.height = 400

    # create some example data
    data = dict(
        python=[2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111],
        pypy=[
            12, 33, 47, 15, 126, 121, 144, 233, 254, 225, 226, 267, 110, 130
        ],
        jython=[
            22, 43, 10, 25, 26, 101, 114, 203, 194, 215, 201, 227, 139, 160
        ],
    )

    area1 = Area(data,
                 title="Area Chart",
                 legend="top_left",
                 xlabel='time',
                 ylabel='memory')

    area2 = Area(data,
                 title="Stacked Area Chart",
                 legend="top_left",
                 stack=True,
                 xlabel='time',
                 ylabel='memory')

    output_file("area.html", title="area.py example")

    show(row(area1, area2))
Esempio n. 2
0
def plot(concdf, outputfile="test.html"):
    newtime = concdf
    newtime["Times"] = map(lambda x: (float(x) / 60) - 8, concdf["Times"])

    data = pd.melt(newtime, id_vars="Times")
    # oldtimes = data["Times"]
    # resettimes = []
    # for time in oldtimes:
    #     if time >= 24:
    #         resettimes.append(time-24)
    #     else:
    #         resettimes.append(time)
    # data["Times"] = resettimes
    area = Area(data,
                x="Times",
                y="value",
                legend='top_right',
                title="T-Rx Optimized Treatment Schedule",
                xlabel="Hours (post 8am)",
                ylabel="% Remaining in Patient",
                color="variable")
    output_file(outputfile, title="T-RxPlot")
    save(area)
    print os.getcwd()
    # show(area)
    return
def get_concentration_area_chart(df):
    """Creates area chart visualizing portfolio concentration by position"""
    df = (
        df[["Symbol", "Concentration"]]
        .sort_values("Concentration")
        .set_index("Symbol")
        .cumsum()
        .reset_index()
        .drop("Symbol", axis=1)
    )

    chart = Area(
        df['Concentration'].astype(float),
        title='Cumulative Portfolio Concentration',
        ylabel='% of Total Value',
        xlabel='Number of Positions',
        plot_width=1200,
        plot_height=400,
        legend=False,
        color='#4285f4'
    )

    chart.x_range.start, chart.x_range.end = 0, df.shape[0]

    return file_html(chart, INLINE)
Esempio n. 4
0
def create_analysis(id):
    """
    View a pre-created analysis
    """
    # Get file path from database by id
    file = File.query.get_or_404(id).file

    # Get filename for template
    file_name = os.path.basename(file)
    # Get file path and file extension
    file_path, file_extension = os.path.splitext(file_name)

    # Get file from server to process into data frame
    if file_extension == '.csv':
        # Load CSV file type
        df = pd.DataFrame(pd.read_csv(file, encoding="ISO-8859-1", parse_dates=['Order Date']))
    else:
        # Load files with excel based file extensions
        df = pd.DataFrame(pd.read_excel(file, encoding="ISO-8859-1", parse_dates=['Order Date']))

    # Add columns for sales where profit is plus or zero to negative
    df_sales = df
    df_sales['Profitable'] = df['Sales'].where(df['Profit'] > 0, 0)
    df_sales['Unprofitable'] = df['Sales'].where(df['Profit'] <= 0, 0)

    # Filter only columns needed
    df_sales = df_sales[['Order Date', 'Customer Segment', 'Profit', 'Sales', 'Profitable', 'Unprofitable']]

    # Group by Segment
    df_sales2 = df_sales.groupby(['Customer Segment', 'Order Date']).sum()
    df_sales2 = df_sales2.reset_index(drop=False)

    # Group by Month
    df_mo = df_sales2.set_index('Order Date').groupby('Customer Segment').resample('M').sum()
    df_mo = df_mo.reset_index(drop=False)

    # Change column header to remove space for using as index
    df_segs = df_mo.rename(columns={'Customer Segment': 'Segment'})

    # Setting unique axis to pick up single Customer Segment
    cons_df = df_segs[df_segs['Segment'] == df_segs.Segment.unique()[0]]

    # Filter only columns for chart
    cons_df_area = cons_df[['Order Date', 'Profitable', 'Unprofitable']]

    # Reset index for chart axis labels
    cons_df_area = cons_df_area.set_index(['Order Date']).resample('M').sum()

    # When adding stack=True, Y labels skew.  Fixed with NumeralTickFormatter
    title1 = df_segs.Segment.unique()[0]
    cons_area = Area(cons_df_area, title=title1, legend="top_left",
                xlabel='', ylabel='Profit', plot_width=700, plot_height=400,
                stack=True,
                    )
    cons_area.yaxis[0].formatter = NumeralTickFormatter(format="0,00")
    html = file_html(cons_area, CDN, "html")

    # this is a placeholder template
    return render_template('auth/analyses/render.html', data=html, title="Area Chart")
    def area_chart(df, interval, rolling):
        # re-sampling
        df = df_stitched.resample(str(interval) + 'S').sum().fillna(0) / (
            1000 / 50) * (60 / interval)  # Each sample is 50ms
        # Gives number of seconds spoken per min

        # rename columns if names were given
        if member_names:
            for member_key in member_names:
                df.rename(columns=member_names, inplace=True)

        if rolling:
            df = df.rolling(min_periods=1, window=5,
                            center=True).mean()  # To smooth graph

        start = unix_time_ms(df.index[0])
        start_datetime = datetime.datetime.utcfromtimestamp(start / 1000)
        end = unix_time_ms(df.index[len(df.index) - 1])
        end_datetime = datetime.datetime.utcfromtimestamp(end / 1000)

        df.reset_index(level='datetime',
                       inplace=True)  # To input x values into area chart

        if rolling:
            graph_title = 'Contribution per Minute per Member for Meeting ' + meeting_name + ' (with rolling mean) \
            from ' + start_datetime.strftime(
                '%I:%M %p') + ' to ' + end_datetime.strftime('%I:%M %p')
        else:
            graph_title = 'Contribution per Minute per Member for Meeting ' + meeting_name + ' (without rolling mean) \
            from ' + start_datetime.strftime(
                '%I:%M %p') + ' to ' + end_datetime.strftime('%I:%M %p')

        area = Area(
            df,
            x='datetime',  # Column name
            title=graph_title,
            legend='top_left',
            stack=True,
            xlabel='Time of Day',
            ylabel='Number of Seconds',
            xscale='datetime',
            width=1700,
            height=400,
            tools='xpan, xwheel_zoom, box_zoom, reset, resize',
        )

        # Format tick labels on x-axis
        area.below[0].formatter = DatetimeTickFormatter()
        area.below[0].formatter.formats = dict(years=['%Y'],
                                               months=['%b %Y'],
                                               days=['%d %b %Y'],
                                               hours=['%I:%M %P'],
                                               hourmin=['%I:%M %P'],
                                               minutes=['%I:%M %P'],
                                               minsec=['%I:%M:%S %P'],
                                               seconds=['%I:%M:%S %P'])

        return area
Esempio n. 6
0
    def showBacktestingResult(self):
        """显示回测结果"""
        d = self.calculateBacktestingResult()

        # 输出
        self.output('-' * 30)
        self.output('First Trade:\t%s' % d['timeList'][0])
        self.output('Last Trade:\t%s' % d['timeList'][-1])

        self.output('Total Trades:\t%s' % formatNumber(d['totalResult']))
        self.output('Total Return:\t%s' % formatNumber(d['capital']))
        self.output('Maximum Drawdown: \t%s' %
                    formatNumber(min(d['drawdownList'])))

        self.output('Ave Trade:\t%s' %
                    formatNumber(d['capital'] / d['totalResult']))
        self.output('Ave Slippage:\t%s' %
                    formatNumber(d['totalSlippage'] / d['totalResult']))
        self.output('Ave Commission:\t%s' %
                    formatNumber(d['totalCommission'] / d['totalResult']))

        self.output('Win Ratio\t\t%s%%' % formatNumber(d['winningRate']))
        self.output('Ave Win\t%s' % formatNumber(d['averageWinning']))
        self.output('Ave Loss\t%s' % formatNumber(d['averageLosing']))
        self.output('Profit Factor:\t%s' % formatNumber(d['profitLossRatio']))

        # Use Bokeh to plot
        from bokeh.charts import Area, Line, Histogram
        from bokeh.layouts import column
        from bokeh.io import show

        plotdata = {
            "TradeN": range(len(d['capitalList'])),
            "Equity Curve": d['capitalList'],
            "Maximum Drawdown": d['drawdownList'],
            "Profit/Loss": d['pnlList']
        }

        f1 = Line(plotdata,
                  x="TradeN",
                  y="Equity Curve",
                  color="blue",
                  width=1000,
                  height=300)
        f2 = Area(plotdata,
                  x="TradeN",
                  y="Maximum Drawdown",
                  color="tomato",
                  width=1000,
                  height=300)
        f3 = Histogram(plotdata,
                       values="Profit/Loss",
                       bins=30,
                       color="green",
                       width=1000,
                       height=300)

        show(column(f1, f2, f3))
Esempio n. 7
0
def doPlot_Area(data, nrDataSource):
    p = Area(data,
             title="Area Chart: " + nrDataSource['name'],
             legend="top_left",
             xlabel=data.columns[0],
             ylabel=data.columns[1])

    c = components(p, resources=None, wrap_script=False, wrap_plot_info=True)
    return c
def area_plot_table(table, **kwargs):
    """
    Plot a tabular DataFrame with an index and multiple columns representing
    categories using a Bokeh area chart.

    In addition to the keyword parameters accepted by bokeh.charts.Area, this
    function accepts the following additional keyword arguments:

    number_of_categories: integer
        The number of categories ranked by total value to use.
    xaxis_formatter: TickFormatter
        The formatter to use for x axis values.
    yaxis_formatter: TickFormatter
        The formatter to use for y axis values.
    x_range: Range1d
        A range to use for the X-axis.
    y_range: Range1d
        A range to use for the Y-axis.
    """
    if kwargs.has_key('number_of_categories'):
        acreage_table = analysis.select_top_n_columns(
            table, kwargs['number_of_categories'])
    else:
        acreage_table = table
    acre_plot = Area(
        acreage_table.reset_index(),
        x='year',
        y=map(str, acreage_table.columns),
        stack=True,
        **_remove_custom_keys(kwargs)
    )
    if kwargs.has_key('x_range'):
        acre_plot.xrange = kwargs['x_range']
    else:
        acre_plot.x_range = Range1d(acreage_table.index.min(), acreage_table.index.max())
    if kwargs.has_key('y_range'):
        acre_plot.y_range = kwargs['y_range']
    else:
        acre_plot.y_range = Range1d(0, acreage_table.max().sum())
    if kwargs.has_key('xaxis_formatter'):
        acre_plot._xaxis.formatter = kwargs['xaxis_formatter']
    if kwargs.has_key('yaxis_formatter'):
        acre_plot._yaxis.formatter = kwargs['yaxis_formatter']
    return acre_plot
Esempio n. 9
0
def showArea(times):
    data = dict(BootTime=totalboot(times))

    area = Area(data,
                title="Area Chart",
                legend="top_left",
                xlabel='Start Up #',
                ylabel='Time (s)')

    show(area)
Esempio n. 10
0
def create_area_chart(data, palette):
    return Area(data,
                title=palette,
                stack=True,
                palette=standard_palettes.get(palette),
                legend=None,
                xlabel='',
                ylabel='',
                xgrid=False,
                ygrid=False,
                tools='')
Esempio n. 11
0
def create_area_chart(data, palette):
    _chart_styling = dict(height=300,
                          width=300,
                          xgrid=False,
                          ygrid=False,
                          tools="")
    return Area(data,
                title=palette,
                stack=True,
                palette=standard_palettes.get(palette),
                **_chart_styling)
Esempio n. 12
0
def plot_stacked(concdf, outputfile="test.html"):
    # divide by 60 for time
    # get x val to be time
    data = concdf.set_index(['Times'])
    area = Area(data,
                legend='top_right',
                stack=True,
                title="Plasma Concentration over Time",
                xlabel="Time",
                ylabel="Concentration")
    output_file(outputfile, title="Concentraion Plot")
    # show(area)
    return
Esempio n. 13
0
def test_responsive_legacy_chart_starts_at_correct_size(
        output_file_url, selenium):
    values = dict(
        apples=[2, 3, 7, 5, 26, 221, 44, 233, 254, 25, 2, 67, 10, 11],
        oranges=[
            22, 43, 10, 25, 26, 101, 114, 203, 194, 215, 201, 227, 139, 160
        ],
    )

    area = Area(values, title="Area Chart", responsive=True)
    save(area)

    selenium.set_window_size(width=1000, height=600)
    selenium.get(output_file_url)

    canvas = selenium.find_element_by_tag_name('canvas')
    wait_for_canvas_resize(canvas, selenium)

    # Canvas width should be just under 1000
    assert canvas.size['width'] > 900
    assert canvas.size['width'] < 1000
Esempio n. 14
0
def area_plot_table(table, **kwargs):
    """
    Plot a tabular DataFrame with an index and multiple columns representing
    categories using a Bokeh area chart.

    In addition to the keyword parameters accepted by bokeh.charts.Area, this
    function accepts the following additional keyword arguments:

    number_of_categories: integer
        The number of categories ranked by total value to use.
    xaxis_formatter: TickFormatter
        The formatter to use for x axis values.
    yaxis_formatter: TickFormatter
        The formatter to use for y axis values.
    x_range: Range1d
        A range to use for the X-axis.
    y_range: Range1d
        A range to use for the Y-axis.
    """
    if kwargs.has_key('number_of_categories'):
        acreage_table = analysis.select_top_n_columns(
            table, kwargs['number_of_categories'])
    else:
        acreage_table = table
    acre_plot = Area(acreage_table.reset_index(),
                     x='year',
                     y=map(str, acreage_table.columns),
                     stack=True,
                     **_remove_custom_keys(kwargs))
    if kwargs.has_key('x_range'):
        acre_plot.xrange = kwargs['x_range']
    else:
        acre_plot.x_range = Range1d(acreage_table.index.min(),
                                    acreage_table.index.max())
    if kwargs.has_key('y_range'):
        acre_plot.y_range = kwargs['y_range']
    else:
        acre_plot.y_range = Range1d(0, acreage_table.max().sum())
    if kwargs.has_key('xaxis_formatter'):
        acre_plot._xaxis.formatter = kwargs['xaxis_formatter']
    if kwargs.has_key('yaxis_formatter'):
        acre_plot._yaxis.formatter = kwargs['yaxis_formatter']
    return acre_plot
Esempio n. 15
0

logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(module)s - %(levelname)s ##\t  %(message)s")
log = logging.getLogger()




# create some example data
data = dict(
    python=[2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111],
    pypy=[12, 33, 47, 15, 126, 121, 144, 233, 254, 225, 226, 267, 110, 130],
    jython=[22, 43, 10, 25, 26, 101, 114, 203, 194, 215, 201, 227, 139, 160],
)

area = Area(data, title="Area Chart", legend="top_left",
            xlabel='time', ylabel='memory')


@app.route("/api_analytics/nrendpoint", methods=["GET"])
def getNodeRedEndpoint():
	e = {"url":appConfig.nodered_url}
	return Response(json.dumps(e), mimetype="application/json")





def doPlot1(data, nrDataSource):
	p = Bar(data, data.columns[0], values=data.columns[1], title="Bar graph: " + nrDataSource['name'], xlabel=data.columns[0], ylabel=data.columns[1], plot_width=900, responsive=True)
	c = components(p, resources=None, wrap_script=False, wrap_plot_info=True)
	return c
Esempio n. 16
0
timelineChart.line("date","polarity", color = "green", line_width=1, source = timelineSource)
timelineChart.line("date","magnitude", color = "gray", line_width=1, source = timelineSource)
timelineChart.y_range = Range1d(0, 100)

#area chart
areadata = dict(
    surprise=surpriseArray,
    like=likeArray,
    excite=exciteArray,
    disappoint=disappointArray,
    angry=angryArray,
    hate=hateArray
)

area = Area(areadata, title="情感走势图", legend="top_left",
             stack=True, xlabel='时间', ylabel='百分比', plot_width=730, plot_height=300, responsive=True, toolbar_location="below",
           toolbar_sticky=False,tools = ["wheel_zoom","box_zoom","reset","save"])
area.toolbar.logo = None
area.x_range = Range1d(0, 152)
area.y_range = Range1d(0, 1)

#scatter chart

scatterhover = HoverTool(
        tooltips="""
        <div>
            <div>
                <span style="font-size: 15px;">极性 @polarity</span>
            </div>
            <div>
                <span style="font-size: 15px;">浓度 @magnitude</span>
Esempio n. 17
0
from collections import OrderedDict

from bokeh.charts import Area, show, vplot, output_file, defaults

defaults.width = 400
defaults.height = 400

# create some example data
xyvalues = OrderedDict(
    python=[2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111],
    pypy=[12, 33, 47, 15, 126, 121, 144, 233, 254, 225, 226, 267, 110, 130],
    jython=[22, 43, 10, 25, 26, 101, 114, 203, 194, 215, 201, 227, 139, 160],
)

output_file(filename="area.html")

area1 = Area(xyvalues,
             title="Area Chart",
             xlabel='time',
             ylabel='memory',
             legend="top_left")

area2 = Area(xyvalues,
             title="Stacked Area Chart",
             stack=True,
             xlabel='time',
             ylabel='memory',
             legend="top_left")

show(vplot(area1, area2))
Esempio n. 18
0
from collections import OrderedDict
from bokeh.charts import Area

# create some example data
xyvalues = OrderedDict(
    python=[2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111],
    pypy=[12, 33, 47, 15, 126, 121, 144, 233, 254, 225, 226, 267, 110, 130],
    jython=[22, 43, 10, 25, 26, 101, 114, 203, 194, 215, 201, 227, 139, 160],
)

# create an area chart
area = Area(xyvalues,
            title="Area Chart",
            xlabel='time',
            ylabel='memory',
            filename="area.html",
            stacked=True,
            legend="top_left").legend("top_left")
area.show()
Esempio n. 19
0
from collections import OrderedDict
from bokeh.charts import Area

# create some example data
xyvalues = OrderedDict(
    python=[2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111],
    pypy=[12, 33, 47, 15, 126, 121, 144, 233, 254, 225, 226, 267, 110, 130],
    jython=[22, 43, 10, 25, 26, 101, 114, 203, 194, 215, 201, 227, 139, 160],
)

# create an area chart
area = Area(
    xyvalues, title="Area Chart", xlabel='time',
    ylabel='memory', filename="area.html",
    facet=False, stacked=True,
)
area.legend("top_left").show()
    def _plot_public_data_statistics(self, all_data, version_attr_name,
                                     title_name, label_cb):
        """
        generic method to plot flight hours one data type
        :param all_data: list with all types as string
        :param version_attr_name: attribute name of _VersionData
        :param title_name: name of the data for the title (and hover tool)
        :param label_cb: callback to create the label
        :return: bokeh plot
        """

        # change data structure
        data_hours = {}  # key=data id, value=list of hours for each version
        for d in all_data:
            data_hours[d] = []

        versions = []  # sorted list of all versions
        for ver in sorted(self._version_data,
                          key=functools.cmp_to_key(_Log.compare_version)):
            versions.append(ver)

            # all data points of the requested type for this version
            version_type_data = getattr(self._version_data[ver],
                                        version_attr_name)

            for d in all_data:
                if not d in version_type_data:
                    version_type_data[d] = 0.
                data_hours[d].append(version_type_data[d])

        # cumulative over each version
        for key in all_data:
            data_hours[key] = np.array(data_hours[key])
            data_hours[key + "_cum"] = np.cumsum(data_hours[key])

        # create a 2D numpy array. We could directly pass the dict to the bokeh
        # plot, but then we don't have control over the sorting order
        X = np.zeros((len(all_data), len(versions)))
        i = 0
        all_data_sorted = []
        for key in sorted(
                all_data,
                key=lambda data_key: data_hours[data_key + "_cum"][-1]):
            X[i, :] = data_hours[key + "_cum"]
            all_data_sorted.append(key)
            i += 1
        all_data = all_data_sorted

        colors = viridis(len(all_data))
        # alternative: use patches: http://bokeh.pydata.org/en/latest/docs/gallery/brewer.html
        area = Area(X,
                    title="Flight Hours per " + title_name,
                    tools=TOOLS,
                    active_scroll=ACTIVE_SCROLL_TOOLS,
                    stack=True,
                    xlabel='version (including development states)',
                    ylabel='',
                    color=colors)

        # now set the labels
        for i in range(len(all_data)):
            area.legend[0].items[i].label = props.value(
                label_cb(all_data[i], False))
        area.legend[0].items.reverse()

        # stack the data: we'll need it for the hover tool
        last = np.zeros(len(versions))
        for i in range(len(all_data)):
            last = last + X[i, :]
            data_hours[all_data[i] + '_stacked'] = last
        data_hours['x'] = np.arange(len(versions))

        # hover tool
        source = ColumnDataSource(data=data_hours)
        for d in all_data:
            renderer = area.circle(x='x',
                                   y=d + '_stacked',
                                   source=source,
                                   size=10,
                                   alpha=0,
                                   name=d)
            g1_hover = HoverTool(renderers=[renderer],
                                 tooltips=[
                                     (title_name, label_cb(d, True)),
                                     ('Flight hours (only this version)',
                                      '@' + d + '{0,0.0}'),
                                     ('Flight hours (up to this version)',
                                      '@' + d + '_cum{0,0.0}')
                                 ])
            area.add_tools(g1_hover)

        # TODO: space x-axis entries according to version release date?
        area.xaxis.formatter = FuncTickFormatter(code="""
            var versions = """ + str(versions) + """;
            return versions[Math.floor(tick)]
        """)
        area.xaxis.ticker = FixedTicker(ticks=list(range(len(versions))))
        self._setup_plot(area)
        return area
Esempio n. 21
0
    def generate_graph(self):
        """
        Generate the graph; return a 2-tuple of strings, script to place in the
        head of the HTML document and div content for the graph itself.

        :return: 2-tuple (script, div)
        :rtype: tuple
        """
        logger.debug('Generating graph for %s', self._graph_id)
        # tools to use
        tools = [
            PanTool(),
            BoxZoomTool(),
            WheelZoomTool(),
            SaveTool(),
            ResetTool(),
            ResizeTool()
        ]

        # generate the stacked area graph
        try:
            g = Area(
                self._data, x='Date', y=self._y_series_names,
                title=self._title, stack=True, xlabel='Date',
                ylabel='Downloads', tools=tools,
                # note the width and height will be set by JavaScript
                plot_height=400, plot_width=800,
                toolbar_location='above', legend=False
            )
        except Exception as ex:
            logger.error("Error generating %s graph", self._graph_id)
            logger.error("Data: %s", self._data)
            logger.error("y=%s", self._y_series_names)
            raise ex

        lines = []
        legend_parts = []
        # add a line at the top of each Patch (stacked area) for hovertool
        for renderer in g.select(GlyphRenderer):
            if not isinstance(renderer.glyph, Patches):
                continue
            series_name = renderer.data_source.data['series'][0]
            logger.debug('Adding line for Patches %s (series: %s)', renderer,
                         series_name)
            line = self._line_for_patches(self._data, g, renderer, series_name)
            if line is not None:
                lines.append(line)
                legend_parts.append((series_name, [line]))

        # add the Hovertool, specifying only our line glyphs
        g.add_tools(
            HoverTool(
                tooltips=[
                    (self._y_name, '@SeriesName'),
                    ('Date', '@FmtDate'),
                    ('Downloads', '@Downloads'),
                ],
                renderers=lines,
                line_policy='nearest'
            )
        )

        # legend outside chart area
        legend = Legend(legends=legend_parts, location=(0, 0))
        g.add_layout(legend, 'right')
        return components(g)
Esempio n. 22
0
from collections import OrderedDict

from bokeh.charts import Area, show, output_file

# create some example data
xyvalues = OrderedDict(
    python=[2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111],
    pypy=[12, 33, 47, 15, 126, 121, 144, 233, 254, 225, 226, 267, 110, 130],
    jython=[22, 43, 10, 25, 26, 101, 114, 203, 194, 215, 201, 227, 139, 160],
)

output_file(filename="area.html")

area = Area(xyvalues,
            title="Area Chart",
            xlabel='time',
            ylabel='memory',
            stacked=True,
            legend="top_left").legend("top_left")

show(area)
Esempio n. 23
0
from bokeh.charts import Area, show, output_file, defaults
from bokeh.layouts import row

defaults.width = 400
defaults.height = 400

# create some example data
data = dict(
    python=[2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111],
    pypy=[12, 33, 47, 15, 126, 121, 144, 233, 254, 225, 226, 267, 110, 130],
    jython=[22, 43, 10, 25, 26, 101, 114, 203, 194, 215, 201, 227, 139, 160],
)

area1 = Area(data, title="Area Chart", legend="top_left",
             xlabel='time', ylabel='memory')

area2 = Area(data, title="Stacked Area Chart", legend="top_left",
             stack=True, xlabel='time', ylabel='memory')

output_file("area.html", title="area.py example")

show(row(area1, area2))
Esempio n. 24
0
#!/usr/bin/python
#coding:utf-8
from bokeh.plotting import figure, output_file, show
from bokeh.charts import Area, show, vplot, output_file

# create some example data
data = dict(
    # p_top = [[25,100],[1000,100],[10000,100]],
    python=[110, 110, 100],
    # bottom = [100,100,90]
)
#zhushi = '''
area = Area(
    data,  #x = [25,1000,10000],
    title="Area Chart",
    legend="top_left",
    # x_axis_type="log",
    # y_range=(60,120),
    # stack=True,
    # xlabel='频率(Hz)', ylabel='限值(dBμA)'
)

output_file('area.html')

p = area
show(p)
#'''
#print data[p_top]
Esempio n. 25
0
output_file('output/bokeh/stocks.html', mode='cdn')
show(p)

#
pri_fin_mat2 = pri_fin_mat
pri_fin_mat2['Date'] = pri_fin_mat2.index
cdf = ColumnDataSource(pri_fin_mat2)
del pri_fin_mat2
p = figure()
p.line(x='Date', y='Gold', source=cdf)
output_file('output/bokeh/stocks.html', mode='cdn')
show(p)


# 2
p2 = Area(pri_fin_mat.Stocks.fillna(0))
output_file("output/bokeh/p2.html")
show(p2)

# 3
cdf = ColumnDataSource(pri_fin_mat)
p3 = figure()
#p3.line('date', 'Stocks', source=cdf)
p3.line(pri_fin_mat.index, pri_fin_mat.Bonds)
hover = HoverTool()
p3.add_tools(hover)
output_file('output/bokeh/s2.html', mode='cdn')
show(p3)

# 4
Esempio n. 26
0
def simple_chart(request,counter_name):
	counter_len = len(Counter.objects.values())
	
	Date = [Counter.objects.values()[i]["pub_date"] for i in range(counter_len)]
	name = counter_name
	y_values = Counter.objects.values_list("counter_value",flat=True).filter(counter_name=counter_name)
	
	points = zip(Date,y_values)
	 
	ddict = OrderedDict({'Date':Date})
	#ddict[name] = y_values
	
	TOOLS="pan,wheel_zoom,box_zoom,reset,hover,save"	
	p = figure(width=1200, height=400, x_axis_type="datetime",tools=TOOLS,title=name+"'s Metrics" )	
	p.min_border_left = 100
	p.min_border_top = 50
	p.border_fill = 'whitesmoke'
	p.ygrid.band_fill_color = "#E6E6FA"	
	p.title_text_color = "olive"
	p.title_text_font = "times"
	p.title_text_font_style = "italic"	
	

	p.outline_line_width = 7
	p.outline_line_alpha = 0.3
	p.outline_line_color = "black"	
	
	
	source = ColumnDataSource(
       		 data=dict(
		
		rates = [slope(points[i][0].microsecond,points[i][1],points[i+1][0].microsecond,points[i+1][1]) for i in range(len(points)-1)]
		)       		 
   	 )	


	hover = p.select(dict(type=HoverTool))
	hover.point_policy = "follow_mouse"
	hover.tooltips = OrderedDict([
	("Counter Name",name),
   	("Rate of count","@rates c/us"),
	])
	
	p.line(Date,y_values,line_width=1,source=source)
	p.square(Date, y_values, fill_color=None, line_color="green",size=4)
	script1, div1 = components(p, CDN)

	hist = Histogram(list(y_values),bins=50,title='Histogram',color="#778899")
	hist.border_fill = 'whitesmoke'
	hist.background_fill = "beige"
	
	script2, div2 = components(hist, CDN)
	
	area = Area(list(y_values),title="CDF")
	area.border_fill ="whitesmoke"
	area.background_fill = "#191970"
		
	script3, div3 = components(area,CDN)

	


	context = RequestContext(request,{"the_script1":script1, "the_div1":div1,"the_script2":script2,"the_div2":div2,"the_script3":script3,"the_div3":div3})	

	return render(request, "counters_app/simple_bokeh.html",context)