我们从Python开源项目中,提取了以下11个代码示例,用于说明如何使用bokeh.plotting.Figure()。
def add_geom(fig: Figure, geom: BaseGeometry, **kwargs): """Add Shapely geom into Bokeh plot. Args: fig (Figure): geom (BaseGeometry): """ if isinstance(geom, Point): fig.circle(*geom.xy, **kwargs) elif isinstance(geom, LineString): fig.line(*geom.xy, **kwargs) elif isinstance(geom, Polygon): fig.patch(*geom.exterior.xy, **kwargs) elif isinstance(geom, BaseMultipartGeometry): for item in geom: add_geom(fig, item, **kwargs) else: raise TypeError('Object geom {geom} no instance of {types}.'.format( geom=geom, types=BaseGeometry))
def add_direction_map(fig: Figure, mgrid, direction_map, freq=2, **kwargs): """Quiver plot of direction map http://bokeh.pydata.org/en/latest/docs/gallery/quiver.html Args: fig: mgrid: direction_map: **kwargs: """ X, Y = mgrid.values U, V = direction_map x0 = X[::freq, ::freq].flatten() y0 = Y[::freq, ::freq].flatten() x1 = x0 + 0.9 * freq * mgrid.step * U[::freq, ::freq].flatten() y1 = y0 + 0.9 * freq * mgrid.step * V[::freq, ::freq].flatten() fig.segment(x0, y0, x1, y1, **kwargs) fig.triangle(x1, y1, size=4.0, angle=np.arctan2(V[::freq, ::freq].flatten(), U[::freq, ::freq].flatten()) - np.pi / 2)
def make_correlation_figure(correlation_values, title): """ Creates a correlation function plot with confidence intervals for determining the ARIMA ordering :param correlation_values: The computed correlation function values :param title: Tile for the plot :return: A Bokeh figure populated with traces for the correlation function display """ count = len(correlation_values) figure = Figure(title=title) figure.line(x=[0, count], y=-1.96/np.sqrt(len(temperatures)), color='black') figure.line(x=[0, count], y=1.96/np.sqrt(len(temperatures)), color='black') figure.line(x=list(range(count)), y=correlation_values) figure.scatter(x=list(range(count)), y=correlation_values, size=6) return figure
def plot_sensor_data(df_sensor: pd.DataFrame): """ Creates a line plot for the temperature data of the given sensor with a reference line for the aerial temperature. :param df_sensor: Data frame for the sensor to be plotted """ figure = Figure( title='Temperature Data for Sensor #{}'.format( int(df_sensor.ix[0]['sensor_index']) ), x_axis_label='Time of Day (Hours)', y_axis_label='Temperature (Celsius)' ) figure.line(df_aerial['time'], df_aerial['temperature']) figure.line(df_sensor['time'], df_sensor['temperature'], color='red') cd.display.bokeh(figure, scale=0.3)
def make_plots(linesources, pointsources): plots = [] i=0 for linesource, pointsource in zip(linesources, pointsources): fig = Figure(title=None, toolbar_location=None, tools=[], x_axis_type="datetime", width=300, height=70) fig.xaxis.visible = False if i in [0, 9] : fig.xaxis.visible = True fig.height = 90 fig.yaxis.visible = False fig.xgrid.visible = True fig.ygrid.visible = False fig.min_border_left = 10 fig.min_border_right = 10 fig.min_border_top = 5 fig.min_border_bottom = 5 if not i in [0, 9]: fig.xaxis.major_label_text_font_size = "0pt" #fig.yaxis.major_label_text_font_size = "0pt" fig.xaxis.major_tick_line_color = None fig.yaxis.major_tick_line_color = None fig.xaxis.minor_tick_line_color = None fig.yaxis.minor_tick_line_color = None fig.background_fill_color = "whitesmoke" fig.line(x='date', y="y", source=linesource) fig.circle(x='date', y='y', size=5, source=pointsource) fig.text(x='date', y='y', text='text', x_offset=5, y_offset=10, text_font_size='7pt', source=pointsource) fig.title.align = 'left' fig.title.text_font_style = 'normal' plots.append(fig) i+=1 return plots
def set_aspect(fig, x, y, aspect=1, margin=0.1): """Set the plot ranges to achieve a given aspect ratio. https://stackoverflow.com/questions/26674779/bokeh-plot-with-equal-axes Args: fig (bokeh Figure): The figure object to modify. x (iterable): The x-coordinates of the displayed data. y (iterable): The y-coordinates of the displayed data. aspect (float, optional): The desired aspect ratio. Defaults to 1. Values larger than 1 mean the plot is squeezed horizontally. margin (float, optional): The margin to add for glyphs (as a fraction of the total plot range). Defaults to 0.1 """ xmin, xmax = min(x), max(x) ymin, ymax = min(y), max(y) width = (xmax - xmin) * (1 + 2 * margin) width = 1.0 if width <= 0 else width height = (ymax - ymin) * (1 + 2 * margin) height = 1.0 if height <= 0 else height r = aspect * (fig.plot_width / fig.plot_height) if width < r * height: width = r * height else: height = width / r xcenter = 0.5 * (xmax + xmin) ycenter = 0.5 * (ymax + ymin) fig.x_range = Range1d(xcenter - 0.5 * width, xcenter + 0.5 * width) fig.y_range = Range1d(ycenter - 0.5 * height, ycenter + 0.5 * height)
def figure(filename, show=False, save=False, **kwargs): """Context manager for using :class:`bokeh.plotting.figure`. Args: filename (str): show (bool): save (bool): Yields: Figure: Examples: >>> with figure('figure.html', show=True, save=False) as p: >>> p.patch(...) """ base, ext = os.path.splitext(filename) _, name = os.path.split(base) if ext != '.html': filename += '.html' bokeh.io.output_file(filename, name) fig = bokeh.plotting.Figure(**kwargs) yield fig if show: bokeh.io.show(fig) if save: bokeh.io.save(fig)
def add_to_arima_plot( figure: Figure, order, values, legend: str, color: str ): year = 0.01 * order.values delta = len(order) - len(values) figure.line(year[delta:], values, legend=legend, color=color) return figure.scatter(year[delta:], values, legend=legend, color=color)
def process(df: pd.DataFrame) -> dict: """ Compute aggregate results for a given data frame and return a dictionary containing those results to be an entry in the results data frame. """ sensor_index = df.ix[0]['sensor_index'] swing = int(0.5 * len(df)) rmse_offsets = np.array(range(-swing, swing + 1)) rmse_values = np.array([mean_offset_rmse(df, n) for n in rmse_offsets]) lag = 0.25 * rmse_offsets[rmse_values.argmin()] figure = Figure( title='Mean RMSE Values for Sensor #{}'.format(int(sensor_index)), x_axis_label='Time Difference (Hours)', y_axis_label='Mean RMSE Value' ) figure.line(0.25 * rmse_offsets, rmse_values) cd.display.bokeh(figure, 0.3) return dict( sensor_index=sensor_index, mean_temperature=df['temperature'].mean(), minimzed_mean_rmse=min(rmse_values), lag=lag )
def plot_field(field, step=0.02, radius=0.3, strength=0.3, **kwargs): bokeh.io.output_file(field.name + '.html', field.name) p = bokeh.plotting.Figure(**kwargs) if field.domain: minx, miny, maxx, maxy = field.domain.bounds else: minx, miny, maxx, maxy = field.convex_hull().bounds set_aspect(p, (minx, maxx), (miny, maxy)) p.grid.minor_grid_line_color = 'navy' p.grid.minor_grid_line_alpha = 0.05 # indices = chain(range(len(self.targets)), ('closest',)) # for index in indices: # mgrid, distance_map, direction_map = \ # self.navigation_to_target(index, step, radius, strength) mgrid, distance_map, direction_map = field.navigation_to_target( 'closest', step, radius, strength) # TODO: masked values on distance map add_distance_map(p, mgrid, distance_map.filled(1.0), legend='distance_map') add_direction_map(p, mgrid, direction_map, legend='direction_map') add_geom(p, field.domain, legend='domain', alpha=0.05) for i, spawn in enumerate(field.spawns): add_geom(p, spawn, legend='spawn_{}'.format(i), alpha=0.5, line_width=0, color='green',) for i, target in enumerate(field.targets): add_geom(p, target, legend='target_{}'.format(i), alpha=0.8, line_width=3.0, line_dash='dashed', color='olive',) add_geom(p, field.obstacles, legend='obstacles', line_width=3.0, alpha=0.8, ) p.legend.location = "top_left" p.legend.click_policy = "hide" bokeh.io.show(p) # Anytree
def create_arima_plot( df_history: pd.DataFrame, model_data: arima.MODEL_DATA ) -> Figure: """ Plot the fitting data for the specified model :param df_history: The historical data that was fitted by the ARIMA model :param model_data: The MODEL_DATA instance to plot """ results = model_data.results figure = Figure() figure.xaxis.axis_label = 'Year' figure.yaxis.axis_label = 'Temperature (Celsius)' df = df_history.sort_values(by='order') order = df['order'] add_to_arima_plot( figure, order, df['temperature'].values, 'Data', 'blue' ) add_to_arima_plot( figure, order, results.fittedvalues, 'Model', 'red' ) figure.title = '({p}, {d}, {q}) RMSE: {rmse:0.4f}'.format( **model_data._asdict() ) figure.legend.location = 'bottom_left' return figure