def dashboard_d():
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]
plot = figure(title="bokeh example", x_axis_label='x', y_axis_label='y')
plot.line(x, y, legend="Temp", line_width=2)
a = pd.DataFrame(np.random.randn(20, 20))
b = pd.DataFrame(np.random.randn(10, 10))
c = pd.DataFrame(np.random.randn(5, 5))
d = pd.DataFrame(np.random.randn(50, 50))
return Dashboard([plot, b, c, d], row_layout(2, 2))
python类figure()的实例源码
def matplot_fig():
plt.figure()
plt.plot([1, 2, 3, 4], 'ks-', mec='w', mew=5, ms=20)
return plt.gcf()
def matplot_b():
plt.figure()
plt.plot([5, 6, 7, 7], 'ks-', mec='w', mew=5, ms=20)
return plt.gcf()
def figure_a():
plt.figure()
plt.plot([3,1,4,1,20], 'ks-', mec='w', mew=5, ms=20)
return plt.gcf()
def figure_e():
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]
plot = figure(title="bokeh example", x_axis_label='x', y_axis_label='y')
plot.line(x, y, legend="Temp", line_width=2)
return plot
def matplot_fig():
plt.figure()
plt.plot([3,1,4,1,20], 'ks-', mec='w', mew=5, ms=20)
return plt.gcf()
def bokeh_fig():
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]
plot = figure(title="bokeh example", x_axis_label='x', y_axis_label='y')
plot.line(x, y, legend="Temp", line_width=2)
return plot
def bokeh_fig(a, b):
x = [1, 2, 3, 4, a]
y = [6, 7, 2, 4, b]
plot = figure(title="bokeh example", x_axis_label='x', y_axis_label='y')
plot.line(x, y, legend="Temp", line_width=2)
return plot
def figure_a():
plt.figure()
plt.plot([3,1,4,1,20], 'ks-', mec='w', mew=5, ms=20)
return plt.gcf()
def figure_e():
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]
plot = figure(title="bokeh example", x_axis_label='x', y_axis_label='y', sizing_mode='scale_width')
plot.line(x, y, legend="Temp", line_width=2)
return plot
def test_matplot(self):
plt.figure()
plt.plot([3,1,4,1,20], 'ks-', mec='w', mew=5, ms=20)
convert_to_html(plt.gcf())
def test_bokeh(self):
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]
plot = figure(title="bokeh example", x_axis_label='x', y_axis_label='y')
plot.line(x, y, legend="Temp", line_width=2)
convert_to_html(plot)
def update(self, model):
pos_c, neg_c = get_label_colors(PALETTE)
color_code = lambda arr: np.where(arr == 1, pos_c, neg_c)
self.train_fig = figure(plot_height=400, plot_width=400,
title=template_title('train', model.trainerr), tools='',
x_range=[0, 100], y_range=[-50, 50])
self.test_fig = figure(plot_height=400, plot_width=400,
title=template_title('test', model.testerr), tools='',
x_range=[0, 100], y_range=[-50, 50])
if model.surface is not None:
X1, X2, Z = model.surface
cm = RGBAColorMapper(Z.min(), Z.max(), standard_palettes[PALETTE])
Y = cm.color(Z, alpha=IMAGE_ALPHA)
self.train_fig.image_rgba(image=[Y], x=[0], y=[-50], dw=[100], dh=[100])
self.test_fig.image_rgba(image=[Y], x=[0], y=[-50], dw=[100], dh=[100])
sample_weight = model.sample_weight
if sample_weight is None:
sample_weight = np.ones(model.train.shape[0])
sample_weight = np.sqrt(sample_weight) * DEFAULT_SIZE
self.train_fig.circle(x=model.train[:, 0], y=model.train[:, 1],
color=color_code(model.train[:, 2]),
line_color="#7c7e71", size=sample_weight,
fill_alpha=FILL_ALPHA, line_alpha=LINE_ALPHA)
self.test_fig.circle(x=model.test[:, 0], y=model.test[:, 1],
color=color_code(model.test[:, 2]),
line_color="#7c7e71", size=DEFAULT_SIZE,
fill_alpha=FILL_ALPHA, line_alpha=LINE_ALPHA)
# yeah.. i dont like that either
self.layout.children[1].children[1].children[0] = row(self.train_fig, self.test_fig)
def __init__(self, simul, probes,
line_kwargs={},
fig_kwargs={},
default_fig_kwargs={"width": 600, "height": 400},
default_line_kwargs={},
notebook=True):
from bokeh.io import push_notebook, output_notebook
from bokeh.plotting import figure, show, ColumnDataSource
from bokeh.layouts import Column
if notebook:
output_notebook()
setattr(self, '_push', push_notebook)
self._datasource = ColumnDataSource(dict(t=[simul.t],
**{name: [probe(simul.t,
simul.fields)]
for name, probe
in probes.items()}))
figs = {}
for name, probe in probes.items():
fig_config = default_fig_kwargs.copy()
fig_config.update(fig_kwargs.get(name, {}))
line_config = default_line_kwargs.copy()
line_config.update(line_kwargs.get(name, {}))
figs[name] = figure(**fig_config, title=name)
figs[name].line('t', name, source=self._datasource,
**line_config)
self._handler = show(Column(*[figs[name] for name in probes]),
notebook_handle=True)
self._probes = probes
def image(self, *kargs, **kwargs):
fig = figure()
fig.image(*kargs, **kwargs)
self.figures.append(fig)
def _create_figure(histogram, **kwargs):
title = histogram.title or "Histogram"
axis_names = histogram.axis_names or ["x", "y"]
if len(axis_names) == 1:
axis_names = list(axis_names) + ["frequency"]
from bokeh.plotting import figure
return figure(tools="hover,save,pan,box_zoom,reset,wheel_zoom",
toolbar_location='above',
x_axis_label=axis_names[0], y_axis_label=axis_names[1],
title=title)
# All palette names that can be used in cmap argument
def _draw_contigNrPlot(self, scaffolder):
plot = figure(title='Number of contigs')
plot.circle(x='reads', y='contigs',
source=self.contig_read_src, size=10)
plot.line(x='reads', y='contigs', line_width=4, source=self.contig_read_src)
plot.xaxis.axis_label = '# Reads'
plot.yaxis.axis_label = 'Contigs'
plot.yaxis.axis_label_text_font_size = '14pt'
plot.xaxis.axis_label_text_font_size = '14pt'
plot.yaxis.major_label_text_font_size = '14pt'
plot.xaxis.major_label_text_font_size = '14pt'
plot.title.text_font_size = '16pt'
return plot
def _draw_n50Plot(self):
plot = figure(title='N50 Values')
plot.circle(x='reads', y='n50', source=self.contig_read_src,
size=10, color='red')
plot.line(x='reads', y='n50', line_width=4, source=self.contig_read_src, color='red')
plot.xaxis.axis_label = '# Reads'
plot.yaxis.axis_label = 'N50'
plot.yaxis.axis_label_text_font_size = '14pt'
plot.xaxis.axis_label_text_font_size = '14pt'
plot.yaxis.major_label_text_font_size = '14pt'
plot.xaxis.major_label_text_font_size = '14pt'
plot.yaxis[0].formatter = NumeralTickFormatter(format='0.00a')
plot.title.text_font_size = '16pt'
return plot
def _draw_contigCirclePlot(self):
hover = HoverTool(tooltips=[('Length', '@contigs')])
hover.point_policy = "follow_mouse"
plot = figure(x_axis_type=None, y_axis_type=None, tools=[hover], title='Contig lengths')
plot.annular_wedge(x=0, y=0, inner_radius=0.5, outer_radius=0.7,
start_angle='start', end_angle='stop',
color='colors', alpha=0.9, source=self.contig_dist_src)
plot.yaxis.axis_label_text_font_size = '14pt'
plot.xaxis.axis_label_text_font_size = '14pt'
plot.yaxis.major_label_text_font_size = '14pt'
plot.xaxis.major_label_text_font_size = '14pt'
plot.title.text_font_size = '16pt'
return plot
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