def plot_waveforms(waveforms, figTitle=''):
channels = waveforms.keys()
# plot
plots = []
for (ct, chan) in enumerate(channels):
fig = bk.figure(title=figTitle + repr(chan),
plot_width=800,
plot_height=350,
y_range=[-1.05, 1.05],
x_axis_label=u'Time (?s)')
fig.background_fill_color = config.plotBackground
if config.gridColor:
fig.xgrid.grid_line_color = config.gridColor
fig.ygrid.grid_line_color = config.gridColor
waveformToPlot = waveforms[chan]
xpts = np.linspace(0, len(waveformToPlot) / chan.phys_chan.sampling_rate
/ 1e-6, len(waveformToPlot))
fig.line(xpts, np.real(waveformToPlot), color='red')
fig.line(xpts, np.imag(waveformToPlot), color='blue')
plots.append(fig)
bk.show(column(*plots))
python类show()的实例源码
def show(seq):
waveforms = build_waveforms(seq)
plot_waveforms(waveforms)
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 show_mpl(**kwargs):
plt.show()
def show_mpld3(**kwargs):
if not _use_mpld3:
raise ImportError("failed to import mpld3: try 'sudo pip install mpld3' or choose another plotting backend")
# _mpld3.show(plt.gcf())
_mpld3.save_html(kwargs.get('ax', plt.gcf()), '_mpld3.html')
logger.info("opening mpld3 plot in browser")
webbrowser.open('_mpld3.html')
# TODO: needs to just be input for python3
# raw_input("press enter to continue...")
sleep(2)
os.remove('_mpld3.html')
def mpl2bokeh(ps, data, plot_inds, **kwargs):
"""
"""
if not conf.devel:
raise NotImplementedError("'mpld3' plotting backend not officially supported for this release. Enable developer mode to test.")
if not _use_bkh:
raise ImportError("failed to import bokeh: try 'sudo pip install bokeh' or choose another plotting backend")
if not _use_mpl:
raise ImportError("failed to import matplotlib: try 'sudo pip install matplotlib' or choose another plotting backend")
# mpl2bokeh compiles everything through matplotlib and tries to convert
# only when calling show
return mpl(ps, data, plot_inds, **kwargs)
def show_bokeh(**kwargs):
if not _use_bkh:
raise ImportError("failed to import bokeh: try 'sudo pip install bokeh' or choose another plotting backend")
bkh.show(kwargs['ax'])
# TODO: needs to just be input for python3
# raw_input("press enter to contisnue...")
sleep(2)
os.remove('_bkh.html')
def lightning(ps, data, plot_inds, **kwargs):
"""
"""
if not conf.devel:
raise NotImplementedError("'mpld3' plotting backend not officially supported for this release. Enable developer mode to test.")
try:
from lightning import Lightning
except ImportError:
raise ImportError("failed to import lightning: try 'sudo pip install lightning-python' or choose another plotting backend")
_use_lgn = False
else:
_use_lgn = True
# TODO: option to use server instead of local (for sharing links, etc)
lgn = Lightning(local=True)
logger.warning("lightning plotting backend is VERY EXPERIMENTAL (read: non-existant)")
# it looks like all calls for a single figure need to be made at once by giving lists
# TODO: look into streaming option to stream fits as fitting or as sampling???
series = np.random.randn(5, 50)
viz = lgn.line(series)
# TODO: return and accept viz and then write a .show() function?
viz.save_html('_lgn.html', overwrite=True)
return None, []
def db_plot(*args, **kwargs):
# plot utility for debugging
plt.plot(*args, **kwargs)
plt.show()
pause(1)
def setup_dashboard(self):
output_notebook()
x = [0, 1, 1, 2, 2, 3, 3, 4]
y = 8*[10 ** -7]
source = ColumnDataSource(data=dict(x=x, y=y))
plot = figure(plot_width=300, plot_height=150, y_axis_type="log", y_range=[0.0000000001, 1], x_range=[0, 4],
x_axis_label='Epoch', y_axis_label='Learning Rate')
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
learn_inputs = 4 * [3]
base_code = """
var data = source.data;
var f = cb_obj.value
x = data['x']
y = data['y']
y[{}] = Math.pow(10.0, -1.0 * (10-f))
y[{}] = Math.pow(10.0, -1.0 * (10-f))
source.trigger('change');
var command = 'dashboard.learn_inputs[{}] = ' + f;
var kernel = IPython.notebook.kernel;
kernel.execute(command)
"""
# set up figure
fig = figure(name="cost", y_axis_label="Cost", x_range=(0, 4),
x_axis_label="Epoch", plot_width=300, plot_height=300)
self.fig = fig
train_source = ColumnDataSource(data=dict(x=[], y=[]))
train_cost = fig.line('x', 'y', source=train_source)
self.train_source = train_source
val_source = ColumnDataSource(data=dict(x=[], y=[]))
val_cost = fig.line('x', 'y', source=val_source, color='red')
self.val_source = val_source
# set up sliders and callback
callbacks = [CustomJS(args=dict(source=source), code=base_code.format(k, k+1, k/2)) for k in [0, 2, 4, 6]]
slider = [Slider(start=0.1, end=10, value=3, step=.1, title=None, callback=C, orientation='vertical', width=80, height=50) for C in callbacks]
radio_group = RadioGroup(labels=[""], active=0, width=65)
def train_model_button(run=True):
train_model(slider, fig=fig, handle=fh, train_source=train_source, val_source=val_source)
sliders = row(radio_group, slider[0], slider[1], slider[2], slider[3])
settings = column(plot, sliders)
layout = gridplot([[settings, fig]], sizing_mode='fixed', merge_tools=True, toolbar_location=None)
self.fh = show(layout, notebook_handle=True)
def _process_batch(self, param, name):
if self.handle is None:
self.handle = show(self.fig, notebook_handle=True)
now = default_timer()
# print "{}_{}".format(param.nbatch, param.epoch)
if param.nbatch == 0:
self.epoch = self.epoch + 1
time = float(param.nbatch) / self.total + param.epoch
if param.eval_metric is not None:
name_value = param.eval_metric.get_name_value()
param.eval_metric.reset()
cost = name_value[0][1]
if name == 'train':
cost = self.get_average_cost(cost)
if math.isnan(cost) or cost > 4000:
cost = 4000
if name == 'train':
self.train_source.data['x'].append(time)
self.train_source.data['y'].append(cost)
elif name == 'eval':
self.val_source.data['x'].append(param.epoch+1)
self.val_source.data['y'].append(cost)
if (now - self.last_update > self.update_thresh_s):
self.last_update = now
if self.handle is not None:
push_notebook(handle=self.handle)
else:
push_notebook()
def __init__(self, linenames, sessionname=None, colors=None, xaxis='iterations', callevery=1):
"""
:type linenames: list or tuple
:param linenames: Names of the time series for the Bokeh server to plot. The call method must have the names
in the list as keyword arguments.
:type sessionname: str
:param sessionname: Name of the Bokeh session
:type xaxis: str
:param xaxis: What goes in the x axis ('iterations' or 'epochs')
"""
super(plotter, self).__init__(callevery=callevery)
# Meta
self.linenames = list(linenames)
self.sessionname = "PlotterID-{}".format(id(self)) if sessionname is None else sessionname
self.colors = colors if colors is not None else [None,] * len(self.linenames)
self.xaxis = xaxis
# Init plot server
bplt.output_server(self.sessionname)
# Build figure
self.figure = bplt.figure()
self.figure.xaxis.axis_label = self.xaxis
# Make lines in figure
for name, color in zip(self.linenames, self.colors):
if color is not None:
self.figure.line(x=[], y=[], name=name, color=color, legend=name)
else:
self.figure.line(x=[], y=[], name=name, legend=name)
bplt.show(self.figure)
# Make list of renderers and datasources
self.renderers = {name: self.figure.select(dict(name=name)) for name in self.linenames}
self.datasources = {name: self.renderers[name][0].data_source for name in self.linenames}
def __init__(self, simul, keys=None,
line_kwargs={},
fig_kwargs={},
default_fig_kwargs={"width": 600, "height": 400},
default_line_kwargs={},
notebook=True,
stack=False):
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)
keys = keys if keys else [
key for key in simul.fields.keys() if key != 'x']
self._datafunc = {'x': lambda t, fields, key: fields.x}
for key in keys:
if isinstance(key, str):
self._datafunc[key] = lambda t, fields, key: fields[key]
if isinstance(key, (tuple, list)):
self._datafunc[key[0]] = key[1]
self._datasource = ColumnDataSource({key:
func(simul.t,
simul.fields,
key)
for (key, func)
in self._datafunc.items()})
self.keys = list(self._datafunc.keys())
self.keys.remove("x")
if stack:
fig = figure(**default_fig_kwargs)
for key in self.keys:
line_config = default_line_kwargs.copy()
line_config.update(line_kwargs.get(key, {}))
fig.line('x', key, source=self._datasource,
**line_kwargs.get(key, {}))
self._handler = show(fig, notebook_handle=True)
return
else:
figs = {}
for key in self.keys:
fig_config = default_fig_kwargs.copy()
fig_config.update(fig_kwargs.get(key, {}))
line_config = default_line_kwargs.copy()
line_config.update(line_kwargs.get(key, {}))
figs[key] = figure(**fig_config, title=key)
figs[key].line('x', key, source=self._datasource,
**line_config)
self._handler = show(Column(*[figs[key]
for key
in self._datafunc.keys()
if key != 'x']),
notebook_handle=True)
def scatter_with_hover(x, y, in_notebook=True, show_plt=True,
fig=None, name=None, marker='o',
fig_width=500, fig_height=500, x_label=None,
y_label=None, title=None, color="blue"):
"""
Plots an interactive scatter plot of `x` vs `y` using bokeh, with automatic
tooltips showing columns from `df`. Modified from:
http://blog.rtwilson.com/bokeh-plots-with-dataframe-based-tooltips/
Args:
x (numpy.ndarray): The data for the x-axis.
y (numpy.ndarray): The data for the y-axis.
fig (bokeh.plotting.Figure, optional): Figure on which to plot
(if not given then a new figure will be created)
name (str, optional): Series name to give to the scattered data
marker (str, optional): Name of marker to use for scatter plot
Returns:
fig (bokeh.plotting.Figure): Figure (the same as given, or the newly created figure)
if show is False
"""
# Make it so it works for ipython.
if in_notebook: #pragma: no cover
output_notebook()
# insert the correct hover identifier.
hover = HoverTool(tooltips=[("entry#", "@label"),])
# If we haven't been given a Figure obj then create it with default
# size etc.
if fig is None:
# if title is None:
# fig = figure(width=fig_width, height=fig_height, tools=['box_zoom', 'reset',hover])
# else:
fig = figure(width=fig_width, height=fig_height,
tools=['box_zoom', 'reset',hover],title=title)
# We're getting data from the given dataframe
source = ColumnDataSource(data=dict(x=x,y=y,label=range(1,len(x)+1)))
# Actually do the scatter plot - the easy bit
# (other keyword arguments will be passed to this function)
fig.scatter('x', 'y', source=source, marker=marker,color=color,name=name)
if x_label is not None:
fig.xaxis.axis_label = x_label
if y_label is not None:
fig.yaxis.axis_label = y_label
if show_plt: # pragma: no cover
show(fig)
else:
return(fig)
def scatter(x,y,show_plt=True, x_label=None, y_label=None, label=None,
title=None,fig=None,ax=None):
"""Make a standard matplotlib style scatter plot.
Args:
x (numpy.ndarray): The data for the x-axis.
y (numpy.ndarray): The data for the y-axis.
show (bool, optional): True if plot is to be shown.
x_label (str, optional): The x-axis label.
y_label (str, optional): The y-axis label.
label (str, optional): The data trend label.
title (str, optional): The plot title.
fig (matplotlib.figure.Figure, optional): An initial figure to add points too.
ax (matplotlib.axes._subplots.AxesSubplot, optional): A subplot object to plot on.
Returns:
fig (matplotlib object): Returns the matplotlib object if show = False.
"""
if fig is None and ax is None:
fig = plt.figure()
elif ax is None:
fig = fig
else:
ax = ax
if not isinstance(x,np.ndarray): #pragma: no cover
x = np.array(x)
if not isinstance(y,np.ndarray): #pragma: no cover
y = np.array(y)
if ax is None:
if label is not None:
plt.scatter(x,y,label=label)
else:
plt.scatter(x,y)
if x_label is not None:
plt.xlabel(x_label)
if y_label is not None:
plt.ylabel(y_label)
if title is not None:
plt.title(title)
else:
if label is not None:
ax.scatter(x,y,label=label)
else:
ax.scatter(x,y)
if x_label is not None:
ax.set_xlabel(x_label)
if y_label is not None:
ax.set_ylabel(y_label)
if title is not None:
ax.set_title(title)
return ax
if show_plt is True: #pragma: no cover
plt.show()
else:
return fig