Python bokeh.plotting.figure() Examples

The following are 30 code examples of bokeh.plotting.figure(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bokeh.plotting , or try the search function .
Example #1
Source File: temperature.py    From bigquery-bokeh-dashboard with Apache License 2.0 7 votes vote down vote up
def make_plot(self, dataframe):
        self.source = ColumnDataSource(data=dataframe)
        self.plot = figure(
            x_axis_type="datetime", plot_width=600, plot_height=300,
            tools='', toolbar_location=None)
        self.plot.quad(
            top='max_temp', bottom='min_temp', left='left', right='right',
            color=Blues4[2], source=self.source, legend='Magnitude')
        line = self.plot.line(
            x='date', y='avg_temp', line_width=3, color=Blues4[1],
            source=self.source, legend='Average')
        hover_tool = HoverTool(tooltips=[
            ('Value', '$y'),
            ('Date', '@date_readable'),
        ], renderers=[line])
        self.plot.tools.append(hover_tool)

        self.plot.xaxis.axis_label = None
        self.plot.yaxis.axis_label = None
        self.plot.axis.axis_label_text_font_style = 'bold'
        self.plot.x_range = DataRange1d(range_padding=0.0)
        self.plot.grid.grid_line_alpha = 0.3

        self.title = Paragraph(text=TITLE)
        return column(self.title, self.plot) 
Example #2
Source File: viz2.py    From scipy2015-blaze-bokeh with MIT License 6 votes vote down vote up
def timeseries():
    # Get data
    df = pd.read_csv('data/Land_Ocean_Monthly_Anomaly_Average.csv')
    df['datetime'] = pd.to_datetime(df['datetime'])
    df = df[['anomaly','datetime']]
    df['moving_average'] = pd.rolling_mean(df['anomaly'], 12)
    df = df.fillna(0)
    
    # List all the tools that you want in your plot separated by comas, all in one string.
    TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,previewsave"

    # New figure
    t = figure(x_axis_type = "datetime", width=1000, height=200,tools=TOOLS)

    # Data processing
    # The hover tools doesn't render datetime appropriately. We'll need a string. 
    # We just want dates, remove time
    f = lambda x: str(x)[:7]
    df["datetime_s"]=df[["datetime"]].applymap(f)
    source = ColumnDataSource(df)

    # Create plot
    t.line('datetime', 'anomaly', color='lightgrey', legend='anom', source=source)
    t.line('datetime', 'moving_average', color='red', legend='avg', source=source, name="mva")

    # Style
    xformatter = DatetimeTickFormatter(formats=dict(months=["%b %Y"], years=["%Y"]))
    t.xaxis[0].formatter = xformatter
    t.xaxis.major_label_orientation = math.pi/4
    t.yaxis.axis_label = 'Anomaly(ºC)'
    t.legend.orientation = "bottom_right"
    t.grid.grid_line_alpha=0.2
    t.toolbar_location=None

    # Style hover tool
    hover = t.select(dict(type=HoverTool))
    hover.tooltips = """
        <div>
            <span style="font-size: 15px;">Anomaly</span>
            <span style="font-size: 17px;  color: red;">@anomaly</span>
        </div>
        <div>
            <span style="font-size: 15px;">Month</span>
            <span style="font-size: 10px; color: grey;">@datetime_s</span>
        </div>
        """
    hover.renderers = t.select("mva")

    # Show plot
    #show(t)
    return t

# Add title 
Example #3
Source File: plotting.py    From pytfa with Apache License 2.0 6 votes vote down vote up
def plot_histogram(values, **kwargs):
    """
    Convenience function. Plots a histogram of flat 1D data.

    :param values:
    :return:
    """


    hist, edges = np.histogram(values, **kwargs)

    p1 = figure(tools="save")

    p1.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],
            fill_color="#036564", line_color="#033649")


    return p1 
Example #4
Source File: test_all.py    From ipyvolume with MIT License 6 votes vote down vote up
def test_bokeh():
    from bokeh.plotting import figure
    import ipyvolume.bokeh

    x, y, z = np.random.random((3, 100))

    p3.figure()
    scatter = p3.scatter(x, y, z)

    tools = "wheel_zoom,box_zoom,box_select,lasso_select,help,reset,"
    p = figure(title="E Lz space", tools=tools, width=500, height=500)
    r = p.circle(x, y, color="navy", alpha=0.2)
    ipyvolume.bokeh.link_data_source_selection_to_widget(r.data_source, scatter, 'selected')

    from bokeh.resources import CDN
    from bokeh.embed import components

    script, div = components(p)
    template_options = dict(
        extra_script_head=script + CDN.render_js() + CDN.render_css(),
        body_pre="<h2>Do selections in 2d (bokeh)<h2>" + div + "<h2>And see the selection in ipyvolume<h2>",
    )
    ipyvolume.embed.embed_html(
        "tmp/bokeh.html", [p3.gcc(), ipyvolume.bokeh.wmh], all_states=True, template_options=template_options
    ) 
Example #5
Source File: bokeh.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, waveform=np.zeros(1), fig=None):
        """
        Waveform display that utilises the bokeh visualisation library

        Parameters
        ----------
        waveform : ndarray
            1D array containing the waveform samples
        fig : bokeh.plotting.figure
            Figure to store the bokeh plot onto (optional)
        """
        self._waveform = None
        self._fig = None
        self._active_time = 0

        self.span = None

        cdsource_d = dict(t=[], samples=[])
        self.cdsource = ColumnDataSource(data=cdsource_d)

        self.waveform = waveform
        self.fig = fig

        self.layout = self.fig 
Example #6
Source File: main.py    From bokeh with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def make_plot(source, title):
    plot = figure(x_axis_type="datetime", plot_width=800, tools="", toolbar_location=None)
    plot.title.text = title

    plot.quad(top='record_max_temp', bottom='record_min_temp', left='left', right='right',
              color=Blues4[2], source=source, legend="Record")
    plot.quad(top='average_max_temp', bottom='average_min_temp', left='left', right='right',
              color=Blues4[1], source=source, legend="Average")
    plot.quad(top='actual_max_temp', bottom='actual_min_temp', left='left', right='right',
              color=Blues4[0], alpha=0.5, line_color="black", source=source, legend="Actual")

    # fixed attributes
    plot.xaxis.axis_label = None
    plot.yaxis.axis_label = "Temperature (F)"
    plot.axis.axis_label_text_font_style = "bold"
    plot.x_range = DataRange1d(range_padding=0.0)
    plot.grid.grid_line_alpha = 0.3

    return plot 
Example #7
Source File: stock.py    From osqf2015 with MIT License 6 votes vote down vote up
def create(clz):
        """One-time creation of app's objects.

        This function is called once, and is responsible for
        creating all objects (plots, datasources, etc)
        """
        self = clz()
        n_vals = 1000
        self.source = ColumnDataSource(
            data=dict(
                top=[],
                bottom=0,
                left=[],
                right=[],
                x= np.arange(n_vals),
                values= np.random.randn(n_vals)
                ))

        # Generate a figure container
        self.stock_plot = clz.create_stock(self.source)
        self.update_data()
        self.children.append(self.stock_plot) 
Example #8
Source File: test_all.py    From ipyvolume with MIT License 6 votes vote down vote up
def test_context():
    f1 = ipv.figure(1)
    f2 = ipv.figure(2)
    f3 = ipv.figure(2)

    assert ipv.gcf() is f3
    with f2:  # pylint: disable=not-context-manager
        assert ipv.gcf() is f2
    assert ipv.gcf() is f3
    # test nested
    with f2:  # pylint: disable=not-context-manager
        assert ipv.gcf() is f2
        with f1:  # pylint: disable=not-context-manager
            assert ipv.gcf() is f1
        assert ipv.gcf() is f2
    assert ipv.gcf() is f3 
Example #9
Source File: air.py    From bigquery-bokeh-dashboard with Apache License 2.0 6 votes vote down vote up
def make_plot(self, dataframe):
        self.source = ColumnDataSource(data=dataframe)
        palette = all_palettes['Set2'][6]
        hover_tool = HoverTool(tooltips=[
            ("Value", "$y"),
            ("Year", "@year"),
        ])
        self.plot = figure(
            plot_width=600, plot_height=300, tools=[hover_tool],
            toolbar_location=None)
        columns = {
            'pm10': 'PM10 Mass (µg/m³)',
            'pm25_frm': 'PM2.5 FRM (µg/m³)',
            'pm25_nonfrm': 'PM2.5 non FRM (µg/m³)',
            'lead': 'Lead (¹/₁₀₀ µg/m³)',
        }
        for i, (code, label) in enumerate(columns.items()):
            self.plot.line(
                x='year', y=code, source=self.source, line_width=3,
                line_alpha=0.6, line_color=palette[i], legend=label)

        self.title = Paragraph(text=TITLE)
        return column(self.title, self.plot)
# [END make_plot] 
Example #10
Source File: test_image.py    From PyBloqs with GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_bokehplot():
    fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
    years = ['2015', '2016', '2017']

    data = {'fruits': fruits,
            '2015': [2, 1, 4, 3, 2, 4],
            '2016': [5, 3, 3, 2, 4, 6],
            '2017': [3, 2, 4, 4, 5, 3]}

    x = [(fruit, year) for fruit in fruits for year in years]
    counts = sum(zip(data['2015'], data['2016'], data['2017']), ())  # like an hstack

    source = ColumnDataSource(data=dict(x=x, counts=counts))

    fig = figure(x_range=FactorRange(*x), plot_height=350, title="Fruit Counts by Year",
                 toolbar_location=None, tools="")
    fig.vbar(x='x', top='counts', width=0.9, source=source)
    return BokehPlotBlock(fig) 
Example #11
Source File: plot.py    From umap with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def show(plot_to_show):
    """Display a plot, either interactive or static.

    Parameters
    ----------
    plot_to_show: Output of a plotting command (matplotlib axis or bokeh figure)
        The plot to show

    Returns
    -------
    None
    """
    if isinstance(plot_to_show, plt.Axes):
        show_static()
    elif isinstance(plot_to_show, bpl.Figure):
        show_interactive(plot_to_show)
    else:
        raise ValueError(
            "The type of ``plot_to_show`` was not valid, or not understood."
        ) 
Example #12
Source File: utilities.py    From estimagic with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_standard_figure(title, tooltips=None):
    """Return a styled, empty figure of predetermined height and width.

    Args:
        title (str): Title of the figure.
        tooltips (list): List of bokeh tooltips to add to the figure.

    Returns:
        fig (bokeh Figure)

    """
    fig = figure(plot_height=350, plot_width=700, title=title, tooltips=tooltips)
    fig.title.text_font_size = "15pt"
    fig.min_border_left = 50
    fig.min_border_right = 50
    fig.min_border_top = 20
    fig.min_border_bottom = 50
    fig.toolbar_location = None
    return fig 
Example #13
Source File: bokeh.py    From thingflow-python with Apache License 2.0 6 votes vote down vote up
def run(self):
        print("In thread.run")
        self.p = figure(plot_height=500, tools=TOOLS, y_axis_location='left', title=self.title)
        self.p.x_range.follow = "end"
        self.p.xaxis.axis_label = "Timestamp"
        self.p.x_range.follow_interval = 100
        self.p.x_range.range_padding = 0 
        self.p.line(x="timestamp", y="value", color="blue", source=self.source)
        self.p.circle(x="timestamp", y="value", color="red", source=self.source)

        self.session = push_session(curdoc())
        curdoc().add_periodic_callback(self.update, 100) #period in ms

        self.session.show(column(self.p)) 
        curdoc().title = 'Sensor' 
        self.session.loop_until_closed()

    # def register(self, d, sourceq):
    #     source = ColumnDataSource(dict(d))
    #     self.p.line(x=d[0], y=d[1], color="orange", source=source)
    #     curdoc().add_periodic_callback(self.update, 100) #period in ms 
Example #14
Source File: tornado_bokeh_embed.py    From stock with Apache License 2.0 6 votes vote down vote up
def modify_doc(doc):
    df = sea_surface_temperature.copy()
    source = ColumnDataSource(data=df)

    plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)',
                  title="Sea Surface Temperature at 43.18, -70.43")
    plot.line('time', 'temperature', source=source)

    def callback(attr, old, new):
        if new == 0:
            data = df
        else:
            data = df.rolling('{0}D'.format(new)).mean()
        source.data = ColumnDataSource(data=data).data

    slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days")
    slider.on_change('value', callback)

    doc.add_root(column(slider, plot))

    # doc.theme = Theme(filename="theme.yaml") 
Example #15
Source File: visualize_utils.py    From embedding with MIT License 6 votes vote down vote up
def visualize_sentences(vecs, sentences, palette="Viridis256", filename="/notebooks/embedding/sentences.png",
                        use_notebook=False):
    tsne = TSNE(n_components=2)
    tsne_results = tsne.fit_transform(vecs)
    df = pd.DataFrame(columns=['x', 'y', 'sentence'])
    df['x'], df['y'], df['sentence'] = tsne_results[:, 0], tsne_results[:, 1], sentences
    source = ColumnDataSource(ColumnDataSource.from_df(df))
    labels = LabelSet(x="x", y="y", text="sentence", y_offset=8,
                      text_font_size="12pt", text_color="#555555",
                      source=source, text_align='center')
    color_mapper = LinearColorMapper(palette=palette, low=min(tsne_results[:, 1]), high=max(tsne_results[:, 1]))
    plot = figure(plot_width=900, plot_height=900)
    plot.scatter("x", "y", size=12, source=source, color={'field': 'y', 'transform': color_mapper}, line_color=None, fill_alpha=0.8)
    plot.add_layout(labels)
    if use_notebook:
        output_notebook()
        show(plot)
    else:
        export_png(plot, filename)
        print("save @ " + filename) 
Example #16
Source File: viz2.py    From scipy2015-blaze-bokeh with MIT License 6 votes vote down vote up
def title():
    # Data 
    year = 1850
    month = 1

    years = [str(x) for x in np.arange(1850, 2015, 1)]

    months = [str(x) for x in np.arange(1, 13, 1)]
    months_str = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

    month_str = months_str[month-1]

    title = figure(width=1200, height=100, x_range=(0, 1200), y_range=(0, 100), toolbar_location=None,
            x_axis_type=None, y_axis_type=None, outline_line_color="#FFFFFF", tools="", min_border=0)

    title.text(x=500, y=5, text=[month_str], text_font_size='36pt', text_color='black', 
        name="month", text_font="Georgia")
    title.text(x=350, y=5, text=[str(year)], text_font_size='36pt', text_color='black', 
        name="year",text_font="Georgia")

    return title 
Example #17
Source File: bk_sliders.py    From parambokeh with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def app(doc):

    x,y = SineWave()
    source = ColumnDataSource(data=dict(x=x, y=y))

    import numpy as np # see TODO below about ranges
    plot = figure(plot_height=400, plot_width=400,
                  tools="crosshair,pan,reset,save,wheel_zoom",
                  x_range=[0, 4*np.pi], y_range=[-2.5, 2.5])
    plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

    def update_sinewave(sw,**kw):
        x,y = sw()
        source.data = dict(x=x, y=y)
        # TODO couldn't figure out how to update ranges
        #plot.x_range.start,plot.x_range.end=pobj.x_range
        #plot.y_range.start,plot.y_range.end=pobj.y_range
    
    parambokeh.Widgets(SineWave, mode='server', doc=doc, callback=update_sinewave)
    doc.add_root(row(plot, width=800)) 
Example #18
Source File: visualize_utils.py    From embedding with MIT License 6 votes vote down vote up
def visualize_words(words, vecs, palette="Viridis256", filename="/notebooks/embedding/words.png",
                    use_notebook=False):
    tsne = TSNE(n_components=2)
    tsne_results = tsne.fit_transform(vecs)
    df = pd.DataFrame(columns=['x', 'y', 'word'])
    df['x'], df['y'], df['word'] = tsne_results[:, 0], tsne_results[:, 1], list(words)
    source = ColumnDataSource(ColumnDataSource.from_df(df))
    labels = LabelSet(x="x", y="y", text="word", y_offset=8,
                      text_font_size="15pt", text_color="#555555",
                      source=source, text_align='center')
    color_mapper = LinearColorMapper(palette=palette, low=min(tsne_results[:, 1]), high=max(tsne_results[:, 1]))
    plot = figure(plot_width=900, plot_height=900)
    plot.scatter("x", "y", size=12, source=source, color={'field': 'y', 'transform': color_mapper}, line_color=None,
                 fill_alpha=0.8)
    plot.add_layout(labels)
    if use_notebook:
        output_notebook()
        show(plot)
    else:
        export_png(plot, filename)
        print("save @ " + filename) 
Example #19
Source File: viz.py    From scipy2015-blaze-bokeh with MIT License 6 votes vote down vote up
def climate_map():
    data = netCDF4.Dataset('data/Land_and_Ocean_LatLong1.nc')
    t = data.variables['temperature']
    image = get_slice(t, 1950, 1)

    world_countries = wc.data.copy()

    worldmap = pd.DataFrame.from_dict(world_countries, orient='index')

    # Create your plot
    p =  figure(width=900, height=500, x_axis_type=None, y_axis_type=None,
            x_range=[-180,180], y_range=[-90,90], toolbar_location="left")

    p.image_rgba(
        image=[image],
        x=[-180], y=[-90],
        dw=[360], dh=[180], name='image'
    )

    p.patches(xs=worldmap['lons'], ys=worldmap['lats'], fill_color="white", fill_alpha=0,
        line_color="black", line_width=0.5)

    return p 
Example #20
Source File: viz2.py    From scipy2015-blaze-bokeh with MIT License 6 votes vote down vote up
def title():
    # Data 
    year = 1850
    month = 1

    years = [str(x) for x in np.arange(1850, 2015, 1)]

    months = [str(x) for x in np.arange(1, 13, 1)]
    months_str = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

    month_str = months_str[month-1]

    title = figure(width=1200, height=100, x_range=(0, 1200), y_range=(0, 100), toolbar_location=None,
            x_axis_type=None, y_axis_type=None, outline_line_color="#FFFFFF", tools="", min_border=0)

    title.text(x=500, y=5, text=[month_str], text_font_size='36pt', text_color='black', 
        name="month", text_font="Georgia")
    title.text(x=350, y=5, text=[str(year)], text_font_size='36pt', text_color='black', 
        name="year",text_font="Georgia")

    return title 
Example #21
Source File: viz2.py    From scipy2015-blaze-bokeh with MIT License 6 votes vote down vote up
def climate_map():
    data = netCDF4.Dataset('data/Land_and_Ocean_LatLong1.nc')
    t = data.variables['temperature']
    image = get_slice(t, 1950, 1)

    world_countries = wc.data.copy()

    worldmap = pd.DataFrame.from_dict(world_countries, orient='index')

    # Create your plot
    p =  figure(width=900, height=500, x_axis_type=None, y_axis_type=None,
            x_range=[-180,180], y_range=[-90,90], toolbar_location="left")

    p.image_rgba(
        image=[image],
        x=[-180], y=[-90],
        dw=[360], dh=[180], name='image'
    )

    p.patches(xs=worldmap['lons'], ys=worldmap['lats'], fill_color="white", fill_alpha=0,
        line_color="black", line_width=0.5)

    return p 
Example #22
Source File: precipitation.py    From bigquery-bokeh-dashboard with Apache License 2.0 6 votes vote down vote up
def make_plot(self, dataframe):
        self.source = ColumnDataSource(data=dataframe)
        self.plot = figure(
            x_axis_type="datetime", plot_width=400, plot_height=300,
            tools='', toolbar_location=None)

        vbar = self.plot.vbar(
            x='date', top='prcp', width=1, color='#fdae61', source=self.source)
        hover_tool = HoverTool(tooltips=[
            ('Value', '$y'),
            ('Date', '@date_readable'),
        ], renderers=[vbar])
        self.plot.tools.append(hover_tool)

        self.plot.xaxis.axis_label = None
        self.plot.yaxis.axis_label = None
        self.plot.axis.axis_label_text_font_style = 'bold'
        self.plot.x_range = DataRange1d(range_padding=0.0)
        self.plot.grid.grid_line_alpha = 0.3

        self.title = Paragraph(text=TITLE)
        return column(self.title, self.plot) 
Example #23
Source File: bokeh.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fig(self, val):
        if val is None:
            val = figure(plot_width=700, plot_height=180, **PLOTARGS)
        self._fig = val

        self._draw_waveform() 
Example #24
Source File: figureenvelope.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def apply_hovertips(self, figures: List['FigureEnvelope']) -> None:
        """Add hovers to to all figures from the figures list"""
        for f in figures:
            for t in f.figure.tools:
                if not isinstance(t, HoverTool):
                    continue

                self._apply_to_figure(f, t)
                break 
Example #25
Source File: stock.py    From osqf2015 with MIT License 5 votes vote down vote up
def create_stock(cls, source):

        # xdr1 = DataRange1d(sources=[source.columns("x")])
        # ydr1 = DataRange1d(sources=[source.columns("y")])

        # plot1 = figure(title="Outliers", x_range=xdr1, y_range=ydr1, plot_width=650, plot_height=400)
        stock_plot = figure(title="", plot_width=650, plot_height=400)
        # stock_plot.tools.append(TapTool(plot=stock_plot))
        # stock_plot.line(x="x", y="values", size=12, color="blue", line_dash=[2, 4], source=source)
        return stock_plot
        # plot1.scatter(x="x", y="y", size="size", fill_color="red", source=source) 
Example #26
Source File: figureenvelope.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def _apply_to_figure(self, fig, hovertool):
        # provide ordering by two groups
        tooltips_top = []
        tooltips_bottom = []
        for label, tmpl, src_obj in self._hover_tooltips:
            apply: bool = src_obj is fig.master  # apply to own
            foreign = False
            if not apply and (isinstance(src_obj, bt.Observer) or isinstance(src_obj, bt.Indicator)) and src_obj.plotinfo.subplot is False:
                # add objects that are on the same figure cause subplot is False (for Indicators and Observers)
                # if plotmaster is set then it will decide where to add, otherwise clock is used
                if src_obj.plotinfo.plotmaster is not None:
                    apply = src_obj.plotinfo.plotmaster is fig.master
                else:
                    apply = src_obj._clock is fig.master
            if not apply:
                for c in self._config:
                    if isinstance(src_obj, c[0]) and isinstance(fig.master, c[1]):
                        apply = True
                        foreign = True
                        break

            if apply:
                prefix = ''
                top = True
                # prefix with data name if we got multiple datas
                if self.p.is_multidata and foreign:
                    if isinstance(src_obj, bt.Indicator):
                        prefix = label_resolver.datatarget2label(src_obj.datas) + " - "
                    elif isinstance(src_obj, bt.AbstractDataBase):
                        prefix = label_resolver.datatarget2label([src_obj]) + " - "
                    top = False

                item = (prefix + label, tmpl)
                if top:
                    tooltips_top.append(item)
                else:
                    tooltips_bottom.append(item)

        # first apply all top hover then all bottoms
        for t in itertools.chain(tooltips_top, tooltips_bottom):
            hovertool.tooltips.append(t) 
Example #27
Source File: dataIndicatorsHandler.py    From stock with Apache License 2.0 5 votes vote down vote up
def add_plot(stockStat, conf):
    p_list = []
    logging.info("############################", type(conf["dic"]))
    # 循环 多个line 信息。
    for key, val in enumerate(conf["dic"]):
        logging.info(key)
        logging.info(val)

        p1 = figure(width=1000, height=150, x_axis_type="datetime")
        # add renderers
        stockStat["date"] = pd.to_datetime(stockStat.index.values)
        # ["volume","volume_delta"]
        # 设置20个颜色循环,显示0 2 4 6 号序列。
        p1.line(stockStat["date"], stockStat[val], color=Category20[20][key * 2])

        # Set date format for x axis 格式化。
        p1.xaxis.formatter = DatetimeTickFormatter(
            hours=["%Y-%m-%d"], days=["%Y-%m-%d"],
            months=["%Y-%m-%d"], years=["%Y-%m-%d"])
        # p1.xaxis.major_label_orientation = radians(30) #可以旋转一个角度。

        p_list.append([p1])

    gp = gridplot(p_list)
    script, div = components(gp)
    return {
        "script": script,
        "div": div,
        "title": conf["title"],
        "desc": conf["desc"]
    } 
Example #28
Source File: bokeh.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, x_pix, y_pix, pix_size):
        """
        A fast and simple version of the bokeh camera plotter that does not
        allow for geometry changes

        Parameters
        ----------
        x_pix : ndarray
            Pixel x positions
        y_pix : ndarray
            Pixel y positions
        pix_size : ndarray
            Pixel sizes
        """
        self._image = None
        n_pix = x_pix.size

        cdsource_d = dict(image=np.empty(n_pix, dtype="<U8"), x=x_pix, y=y_pix)
        self.cdsource = ColumnDataSource(cdsource_d)
        self.fig = figure(plot_width=400, plot_height=400, **PLOTARGS)
        self.fig.grid.grid_line_color = None
        self.fig.rect(
            "x",
            "y",
            color="image",
            source=self.cdsource,
            width=pix_size[0],
            height=pix_size[0],
        )

        self.layout = self.fig 
Example #29
Source File: plot.py    From arlpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def figsize(x, y):
    """Set the default figure size in pixels.

    :param x: figure width
    :param y: figure height
    """
    global _figsize
    _figsize = (x, y) 
Example #30
Source File: plot.py    From arlpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _new_figure(title, width, height, xlabel, ylabel, xlim, ylim, xtype, ytype, interactive):
    global _color
    if width is None:
        width = _figsize[0]
    if height is None:
        height = _figsize[1]
    _color = 0
    tools = []
    if interactive is None:
        interactive = _interactive
    if interactive:
        tools = 'pan,box_zoom,wheel_zoom,reset,save'
    f = _bplt.figure(title=title, plot_width=width, plot_height=height, x_range=xlim, y_range=ylim, x_axis_label=xlabel, y_axis_label=ylabel, x_axis_type=xtype, y_axis_type=ytype, tools=tools)
    f.toolbar.logo = None
    return f