def plot_paths(results, which_to_label=None): import matplotlib import matplotlib.pyplot as plt plt.clf() interactive_state = plt.isinteractive() xvalues = -np.log(results.lambdas[1:]) for index, path in enumerate(results.coefficients): if which_to_label and results.indices[index] in which_to_label: if which_to_label[results.indices[index]] is None: label = "$x_{%d}$" % results.indices[index] else: label = which_to_label[results.indices[index]] else: label = None if which_to_label and label is None: plt.plot(xvalues, path[1:], ':') else: plt.plot(xvalues, path[1:], label=label) plt.xlim(np.amin(xvalues), np.amax(xvalues)) if which_to_label is not None: plt.legend(loc='upper left') plt.title('Regularization paths ($\\rho$ = %.2f)' % results.balance) plt.xlabel('$-\log(\lambda)$') plt.ylabel('Value of regression coefficient $\hat{\\beta}_i$') plt.show() plt.interactive(interactive_state)
def plot_data_dict(data_dict, plots = None, mode = 'static', hang = True, figure = None, size = None, **plot_preference_kwargs): """ Make a plot of data in the format defined in data_dict :param data_dict: dict<str: plottable_data> :param plots: Optionally, a dict of <key: IPlot> identifying the plot objects to use (keys should be the same as those in data_dict). :return: The plots (same ones you provided if you provided them) """ assert mode in ('live', 'static') if isinstance(data_dict, list): assert all(len(d) == 2 for d in data_dict), "You can provide data as a list of 2 tuples of (plot_name, plot_data)" data_dict = OrderedDict(data_dict) if plots is None: plots = {k: get_plot_from_data(v, mode = mode, **plot_preference_kwargs) for k, v in data_dict.items()} if figure is None: if size is not None: from pylab import rcParams rcParams['figure.figsize'] = size figure = plt.figure() n_rows, n_cols = vector_length_to_tile_dims(len(data_dict)) for i, (k, v) in enumerate(data_dict.items()): plt.subplot(n_rows, n_cols, i + 1) plots[k].update(v) plots[k].plot() plt.title(k, fontdict = {'fontsize': 8}) oldhang = plt.isinteractive() plt.interactive(not hang) plt.show() plt.interactive(oldhang) return figure, plots
def ToSVGString(graph): """ Convert as SVG file. Parameters ---------- graph : object A Graph or Drawable object. Returns a SVG representation as string """ # save interactive mode state ision = plt.isinteractive() plt.ioff() view = View(graph) output = io.BytesIO() view.save(output, format='svg') view.close() # restore interactive mode state if ision: plt.ion() svgBytes = output.getvalue() return svgBytes.decode('utf-8')
def ToSVGString(graph): """ Convert as SVG file. Parameters ---------- graph : object A Graph or Drawable object. Returns a SVG representation as string """ if sys.version_info[0] >= 3: output = io.StringIO() else: output = io.BytesIO() # save interactive mode state ision = plt.isinteractive() plt.ioff() view = View(graph) view.save(output, format='svg') view.close() # restore interactive mode state if ision: plt.ion() return output.getvalue()
def print_all(fnames, freq, spec1, spec2, rms1, rms2, bw=(0,1600)): ''' Print all power spectra to PDF files ''' # Construct path for saving figures and notify base_dir = os.path.join(os.getcwd(), 'figures') if not os.path.exists(base_dir): os.mkdir(base_dir) print('\nsaving figures to {s} ... '.format(s=base_dir), flush=True) # Plot and save figures for each channel's spectrum on = plt.isinteractive() plt.ioff() for chan in range(spec1.shape[-1]): fig = comp_spectra(freq, spec1, spec2, channel=chan, bw=bw) plt.title('Channel {0:d}'.format(chan)) plt.xlabel('Frequency (Hz)') plt.ylabel('Power') plt.legend(('Before', 'After')) print('figure {:02d}'.format(chan), flush=True) plt.savefig(os.path.join(base_dir, 'channel{0:02d}.png'.format(chan)), format='png') plt.close(fig) # Plot and save figure showing RMS ratio fig = plt.figure() plt.plot(rms2 / rms1, 'o') plt.title('RMS ratio (after / before)') plt.xlabel('Channel') plt.savefig(os.path.join(base_dir, 'rms_ratio.png'), format='png') plt.close(fig) # Notify plt.interactive(on) print('done.')
def plot(self, *nodes): """ Plot the distribution of the given nodes (or all nodes) """ if len(nodes) == 0: nodes = self.model if not plt.isinteractive(): plt.ion() redisable = True else: redisable = False for node in nodes: node = self[node] if node.has_plotter(): try: plt.figure(self._figures[node]) except: f = plt.figure() self._figures[node] = f.number plt.clf() node.plot() plt.suptitle('q(%s)' % node.name) plt.draw() plt.show() if redisable: plt.ioff()
def render(self, fig = None, show = True, **kwargs): # {{{ wason = pyl.isinteractive() if wason: pyl.ioff() if not isinstance(fig, mpl.figure.Figure): figparm = dict(figsize = self.size) figparm.update(kwargs) if not fig is None: figparm['num'] = fig fig = pyl.figure(**figparm) fig.clf() self._build_axes(fig, self) self._do_plots(fig) if wason: pyl.ion() if show: pyl.show() pyl.draw() return fig
def _before(self, args, kwargs): import matplotlib.pyplot as pyplot if 'figurefunc' in kwargs and pyplot.isinteractive(): kwargs['figurefunc'] = pyplot.figure if 'ax' in kwargs and self.default_axes is None: if kwargs['ax'] is None: kwargs['ax'] = pyplot.gca()
def lvmTwoDPlot(X, lbl=None, symbol=None): """Helper function for plotting the labels in 2-D. Description: lvmTwoDPlot(X, lbl, symbol) helper function for plotting an embedding in 2-D with symbols. Arguments: X - the data to plot. lbl - the labels of the data point. symbol - the symbols to use for the different labels. See also lvmScatterPlot, lvmVisualise Copyright (c) 2004, 2005, 2006, 2008, 2009 Neil D. Lawrence """ if lbl=='connect': connect = True lbl = None else: connect = False if symbol is None: if lbl is None: symbol = ndlutil.getSymbols(1) else: symbol = ndlutil.getSymbols(lbl.shape[1]) axisHand = pp.gca() returnVal = [] holdState = axisHand.ishold() intState = pp.isinteractive() pp.interactive(False) for i in range(X.shape[0]): if i == 1: axisHand.hold(True) if lbl is not None: labelNo = np.flatnonzero(lbl[i]) else: labelNo = 0 try: returnVal.append(axisHand.plot([X[i, 0]], [X[i, 1]], symbol[labelNo], markersize=10, linewidth=2)) if connect: if i>0: axisHand.plot([X[i-1, 0], X[i, 0]], [X[i-1, 1], X[i, 1]], 'r') except(NotImplementedError): raise NotImplementedError('Only '+ str(len(symbol)) + ' labels supported (it''s easy to add more!)') axisHand.hold(holdState) if intState: pp.show() pp.interactive(intState) return returnVal
def plot(self, ax=None, unit="", maxval=None): """Scatter plot of estimates vs observations Parameters ---------- ax : a matplotlib axes object to plot on if None, a new axes object will be created unit : string measurement unit of the observations / estimates maxval : maximum value for plot range, defaults to max(obs, est) """ if self.n == 0: print("No valid data, no plot.") return None doplot = False if ax is None: fig = pl.figure() ax = fig.add_subplot(111, aspect=1.) doplot = True ax.plot(self.obs, self.est, mfc="None", mec="black", marker="o", lw=0) if maxval is None: maxval = np.max(np.append(self.obs, self.est)) pl.xlim(xmin=0., xmax=maxval) pl.ylim(ymin=0., ymax=maxval) ax.plot([0, maxval], [0, maxval], "-", color="grey") pl.xlabel("Observations (%s)" % unit) pl.ylabel("Estimates (%s)" % unit) if (not pl.isinteractive()) and doplot: pl.show() return ax
def report(self, metrics=None, ax=None, unit="", maxval=None): """Pretty prints selected error metrics over a scatter plot Parameters ---------- metrics : sequence of strings names of the metrics which should be included in the report defaults to ["rmse","r2","meanerr"] ax : a matplotlib axes object to plot on if None, a new axes object will be created unit : string measurement unit of the observations / estimates """ if self.n == 0: print("No valid data, no report.") return None if metrics is None: metrics = ["rmse", "nash", "pbias"] doplot = False if ax is None: fig = pl.figure() ax = fig.add_subplot(111, aspect=1.) doplot = True ax = self.plot(ax=ax, unit=unit, maxval=maxval) if maxval is None: maxval = np.max(np.append(self.obs, self.est)) xtext = 0.6 * maxval ytext = (0.1 + np.arange(0, len(metrics), 0.1)) * maxval mymetrics = self.all() for i, metric in enumerate(metrics): pl.text(xtext, ytext[i], "%s: %s" % (metric, mymetrics[metric])) if not pl.isinteractive() and doplot: pl.show()
def five_by_four(resonators, title="", xlabel='frequency [MHz]', ylabel='$|S_{21}|$ [dB]', sort=False, **kwds): if sort: resonators.sort(key = lambda r: r.f_0) interactive = plt.isinteractive() plt.ioff() fig = plt.figure(figsize=(4, 3)) for n, r in enumerate(resonators): e = extract(r, **kwds) axis = fig.add_subplot(4, 5, n+1) _plot_on_axis(e, axis) axis.set_xlabel("") axis.set_ylabel("") axis.tick_params(right=False, top=False, direction='out', pad=1) xticks = [e['f_0']] axis.set_xticks(xticks) axis.set_xticklabels(['{:.3f}'.format(tick) for tick in xticks]) yticks = [20*np.log10(np.abs(e['model_0'])), 20*np.log10(np.mean((np.abs(e['data'][0]), np.abs(e['data'][-1]))))] axis.set_yticks(yticks) axis.set_yticklabels(['{:.0f}'.format(tick) for tick in yticks]) fig.text(0.3, 0.94, title, fontsize='medium', color='black') fig.text(0.02, 0.94, ylabel, fontsize='medium', color='black') fig.text(0.05, 0.04, xlabel, fontsize='medium', color='black') fig.text(0.4, 0.04, 'data', fontsize='medium', color='blue') fig.text(0.55, 0.04, 'masked', fontsize='medium', color='gray') fig.text(0.75, 0.04, 'fit and f_0', fontsize='medium', color='brown') fig.set_tight_layout({'pad': 0.5, 'h_pad': 0.2, 'w_pad': 0.3, 'rect': (0, 0.08, 1, 0.94)}) if interactive: plt.ion() plt.show() return fig
def hide_box(ax=None): """ Hide right and top parts of plot box in one line :Call: >>> hide_box(ax) :Parameters: *ax*: :class:`matplotlib.axes.AxesSubplot` Handle to axes to be modified :Returns: ``None`` """ #Default input if ax is None: ax = plt.gca() # Delete the right and top edges of the plot. ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') # Turn off the extra ticks. ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # Update. if plt.isinteractive(): plt.draw()
def hinton2(W, maxWeight=None, ax=None): """ Draws a Hinton diagram for visualizing a weight matrix. """ reenable = False if plt.isinteractive(): plt.ioff() if not ax: fig = plt.figure() ax = fig.add_subplot(1, 1, 1) if not maxWeight: maxWeight = 2 ** ceil(log(abs(W).max()) / log(2)) # plt.clf() ax.cla() ax.patch.set_facecolor("gray") ax.set_aspect("equal", "box") ax.xaxis.set_major_locator(NullLocator()) ax.yaxis.set_major_locator(NullLocator()) for (x, y), w in ndenumerate(W): color = "white" if w > 0 else "black" size = sqrt(abs(w)) rect = Rectangle([x - size / 2, y - size / 2], size, size, facecolor=color, edgecolor=color) ax.add_patch(rect) ax.autoscale_view() ax.set_ylim(*ax.get_ylim()[::-1]) if reenable: plt.ion()
def plotPioneer(self,number,y = 1): """ Plotting regions and obstacles with matplotlib.pyplot number: figure number (see on top) y = 0 : plot self.map_work instead of self.map """ if not plt.isinteractive(): plt.ion() plt.hold(True) if y == 0: BoundPolyPoints = asarray(pointList(self.map_work)) plt.plot(BoundPolyPoints[:,0],BoundPolyPoints[:,1],'k') else: BoundPolyPoints = asarray(pointList(self.map)) plt.plot(BoundPolyPoints[:,0],BoundPolyPoints[:,1],'k') if self.system == 1: if bool(self.robocomm.getObsPoly()): BoundPolyPoints = asarray(pointList(self.robocomm.getObsPoly())) plt.plot(BoundPolyPoints[:,0],BoundPolyPoints[:,1],'k') plt.xlabel('x') plt.ylabel('y') plt.figure(number).canvas.draw()
def toggle_pylab(fn): """ A decorator to prevent functions from opening matplotlib windows unexpectedly when sunpy is run in interactive shells like ipython --pylab. Toggles the value of matplotlib.pyplot.isinteractive() to preserve the users' expectations of pylab's behaviour in general. Parameters ---------- fn : function object ? Returns ------ ? : ? ? .. todo:: improve documentation """ if pyplot.isinteractive(): def fn_itoggle(*args, **kwargs): pyplot.ioff() ret = fn(*args, **kwargs) pyplot.ion() return ret return fn_itoggle else: return fn
def _hinton(W, error=None, vmax=None, square=True): """ Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. Originally copied from http://wiki.scipy.org/Cookbook/Matplotlib/HintonDiagrams """ reenable = False if plt.isinteractive(): plt.ioff() reenable = True #P.clf() W = misc.atleast_nd(W, 2) (height, width) = W.shape if not vmax: #vmax = 2**np.ceil(np.log(np.max(np.abs(W)))/np.log(2)) if error is not None: vmax = np.max(np.abs(W) + error) else: vmax = np.max(np.abs(W)) plt.fill(0.5+np.array([0,width,width,0]), 0.5+np.array([0,0,height,height]), 'gray') plt.axis('off') if square: plt.axis('equal') plt.gca().invert_yaxis() for x in range(width): for y in range(height): _x = x+1 _y = y+1 w = W[y,x] _w = np.abs(w) if w > 0: _c = 'white' else: _c = 'black' if error is not None: e = error[y,x] if e < 0: print(e, _w, vmax) raise Exception("BUG? Negative error") if _w + e > vmax: print(e, _w, vmax) raise Exception("BUG? Value+error greater than max") _rectangle(_x, _y, min(1, np.sqrt((_w+e)/vmax)), min(1, np.sqrt((_w+e)/vmax)), edgecolor=_c, fill=False) _blob(_x, _y, min(1, _w/vmax), _c) if reenable: plt.ion()
def showslice2(thedata, thelabel, minval, maxval, colormap): # initialize and show a 2D slice from a dataset in greyscale plt.figure(figsize=plt.figaspect(1.0)) theshape = thedata.shape numslices = theshape[0] ysize = theshape[1] xsize = theshape[2] slicesqrt = int(np.ceil(np.sqrt(numslices))) theslice = np.zeros((ysize * slicesqrt, xsize * slicesqrt)) for i in range(numslices): ypos = int(i / slicesqrt) * ysize xpos = int(i % slicesqrt) * xsize theslice[ypos:ypos + ysize, xpos:xpos + xsize] = thedata[i, :, :] if plt.isinteractive(): plt.ioff() plt.axis('off') plt.axis('equal') plt.subplots_adjust(hspace=0.0) plt.axes([0, 0, 1, 1], frameon=False) if colormap == 0: thecmap = cm.gray else: mycmdata1 = { 'red': ((0., 0., 0.), (0.5, 1.0, 0.0), (1., 1., 1.)), 'green': ((0., 0., 0.), (0.5, 1.0, 1.0), (1., 0., 0.)), 'blue': ((0., 0., 0.), (0.5, 1.0, 0.0), (1., 0., 0.)) } thecmap = colors.LinearSegmentedColormap('mycm', mycmdata1) plt.imshow(theslice, vmin=minval, vmax=maxval, interpolation='nearest', label=thelabel, aspect='equal', cmap=thecmap)
def main(argv=None): # Permit interactive use if argv is None: argv = sys.argv # Parse and check incoming command line arguments outsuffix = None try: try: opts, args = getopt.getopt(argv[1:], "h", ["help"]) except getopt.error as msg: raise Usage(msg) for o, a in opts: if o in ("-h", "--help"): print(__doc__) return 0 elif o == "-o": outsuffix = a except Usage as err: print(err.msg, file=sys.stderr) return 2 # Push interactive mode off (in case we get used from IPython) was_interactive = plt.isinteractive() plt.interactive(False) # If not saving, then display. if not outsuffix: plt.show() # Pop interactive mode plt.interactive(was_interactive)
def plot_patches(patches, fignum=None, low=0, high=0): """ Given a stack of 2D patches indexed by the first dimension, plot the patches in subplots. 'low' and 'high' are optional arguments to control which patches actually get plotted. 'fignum' chooses the figure to plot in. """ try: istate = plt.isinteractive() plt.ioff() if fignum is None: fig = plt.gcf() else: fig = plt.figure(fignum) if high == 0: high = len(patches) pmin, pmax = patches.min(), patches.max() dims = np.ceil(np.sqrt(high - low)) for idx in xrange(high - low): spl = plt.subplot(dims, dims, idx + 1) ax = plt.axis('off') im = plt.imshow(patches[idx], cmap=matplotlib.cm.gray) cl = plt.clim(pmin, pmax) plt.show() finally: plt.interactive(istate)
def test16(self): '''test that makes a real time graph resembling a sine graph ''' # note that by using list comprehension the first 20 points are auto plotted fig = plt.figure(1) import math my = [] t = range(-50, 50) for item in t: b = math.sin(item) my.append(b) mylist = array(my) plt.cla() plt.plot(my[-20:], '-r') #analyzing the plot components a = plt.get_backend() c = plt.isinteractive() # analyzing the axis commands z = plt.axis() v = plt.get_plot_commands() #plt.draw() fig.canvas.draw() self.logger.debug("PLT.GET_NEXT_COMMANDS OUTPUT RESPONS: " + repr(v) ) self.logger.debug("PLT.GET_BACKEND OUTPUT: " + repr(a) ) #self.logger.debug("PLT.GET_NEXT_COMMANDS OUTPUT RESPONS: " + repr(d) ) self.logger.debug("PLT.AXIS COMMAND OUTPUTANSWER TO PLT.AXIS: " + repr(z) )
def hinton(W, maxWeight=None): """ Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. """ reenable = False if plt.isinteractive(): plt.ioff() plt.clf() height, width = W.shape if not maxWeight: maxWeight = 2**np.ceil(np.log(np.max(np.abs(W)))/np.log(2)) plt.fill(np.array([0, width, width, 0]), np.array([0, 0, height, height]), 'gray') plt.axis('off') plt.axis('equal') for x in xrange(width): for y in xrange(height): _x = x+1 _y = y+1 w = W[y, x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, min(1, w/maxWeight), 'white') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, min(1, -w/maxWeight), 'black') if reenable: plt.ion() plt.show()
def interactive(b): b_prev = plt.isinteractive() plt.interactive(b) try: yield finally: plt.interactive(b_prev)
def plot_server(): rospy.init_node('plotter') s = rospy.Service('plot', Plot, handle_plot) plt.ion() print "Ready to plot things!", plt.isinteractive() rospy.spin()
def hinton(W, max_weight=None): """ Draws a Hinton diagram for visualizing a weight matrix. """ if max_weight is None: max_weight = 2 ** np.ceil(np.log2(np.max(np.abs(W)))) # Temporarily disable matplotlib interactive mode if it is on, # otherwise this takes forever. isinteractive = plt.isinteractive() if isinteractive: plt.ioff() height, width = W.shape plt.clf() plt.fill(np.array([0, width, width, 0]), np.array([0, 0, height, height]), "gray") plt.axis("off") plt.axis("equal") for (y, x), w in np.ndenumerate(W): if w != 0: color = "white" if w > 0 else "black" area = min(1, np.abs(w) / max_weight) _blob(x + 0.5, height - y - 0.5, area, color) if isinteractive: plt.ion()
def draw_2D_slice_interactive(self, p_vals, x_variable, y_variable, range_x, range_y, slider_ranges, **kwargs): previous = plt.isinteractive() plt.ioff() number_of_sliders = len(slider_ranges) slider_block = 0.03*number_of_sliders fig = plt.figure() plt.clf() ax = plt.axes([0.1, 0.2+slider_block, 0.8, 0.7-slider_block]) c_axs = list() cdict = dict() if 'color_dict' in kwargs: cdict.update(kwargs['color_dict']) j = 0 sliders = dict() for i in slider_ranges: slider_ax = plt.axes([0.1, 0.1+j*0.03, 0.8, 0.02]) slider = Slider(slider_ax, i, log10(slider_ranges[i][0]), log10(slider_ranges[i][1]), valinit=log10(p_vals[i]), color='#AAAAAA' ) j += 1 sliders[i] = slider update = SliderCallback(self, sliders, c_axs, cdict, ax, p_vals, x_variable, y_variable, range_x, range_y, **kwargs) update(1) for i in sliders: sliders[i].on_changed(update) plt.show() plt.interactive(previous)
def add_plot(self, *args, **kwargs): """ Add plot using supplied parameters and existing instance parameters Creates new Figure and Axes object if 'fig' and 'ax' parameters not supplied. Stores references to all Line2D objects plotted in self.line_list. Arguments ========= *args : Supports format plot(y), plot(x, y), plot(x, y, 'b-'). x, y and format string are passed through for plotting **kwargs : Plot parameters. Refer to __init__ docstring for details """ self._update(*args, **kwargs) # Create figure and axes if needed if self.kwargs['fig'] is None: if not self.isnewargs: return # Don't create fig, ax yet if no x, y data provided self.kwargs['fig'] = plt.figure(figsize=self.kwargs['figsize'], dpi=self.kwargs['dpi']) self.kwargs['ax'] = self.kwargs['fig'].gca() self.kwargs['fig'].add_axes(self.kwargs['ax']) ax, fig = self.kwargs['ax'], self.kwargs['fig'] ax.ticklabel_format(useOffset=False) # Prevent offset notation in plots # Apply axes functions if present in kwargs for kwarg in self.kwargs: if kwarg in self._ax_funcs: # eg: f = getattr(ax,'set_title'); f('new title') func = getattr(ax, self._ax_funcs[kwarg]) func(self.kwargs[kwarg]) # Add plot only if new args passed to this instance if self.isnewargs: # Create updated name, value dict to pass to plot method plot_kwargs = {kwarg: self.kwargs[kwarg] for kwarg in self._plot_kwargs if kwarg in self.kwargs} line, = ax.plot(*self.args, **plot_kwargs) self.line_list.append(line) # Display legend if required if self.kwargs['showlegend']: legend_kwargs = {kwarg: self.kwargs[kwarg] for kwarg in self._legend_kwargs if kwarg in self.kwargs} leg = ax.legend(**legend_kwargs) if leg is not None: leg.draggable(state=True) if 'fontsize' in self.kwargs: self.set_fontsize(self.kwargs['fontsize']) self._delete_uniqueparams() # Clear unique parameters from kwargs list if plt.isinteractive(): # Only redraw canvas in interactive mode self.redraw()
def __init__(self, *args, **kwargs): import matplotlib as mpl import matplotlib.pyplot as plt from collections import deque kwargs["gui"] = True super(tqdm_gui, self).__init__(*args, **kwargs) # Initialize the GUI display if self.disable or not kwargs["gui"]: return self.fp.write("Warning: GUI is experimental/alpha\n") self.mpl = mpl self.plt = plt self.sp = None # Remember if external environment uses toolbars self.toolbar = self.mpl.rcParams["toolbar"] self.mpl.rcParams["toolbar"] = "None" self.mininterval = max(self.mininterval, 0.5) self.fig, ax = plt.subplots(figsize=(9, 2.2)) # self.fig.subplots_adjust(bottom=0.2) if self.total: self.xdata = [] self.ydata = [] self.zdata = [] else: self.xdata = deque([]) self.ydata = deque([]) self.zdata = deque([]) self.line1, = ax.plot(self.xdata, self.ydata, color="b") self.line2, = ax.plot(self.xdata, self.zdata, color="k") ax.set_ylim(0, 0.001) if self.total: ax.set_xlim(0, 100) ax.set_xlabel("percent") self.fig.legend((self.line1, self.line2), ("cur", "est"), loc="center right") # progressbar self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color="g") else: # ax.set_xlim(-60, 0) ax.set_xlim(0, 60) ax.invert_xaxis() ax.set_xlabel("seconds") ax.legend(("cur", "est"), loc="lower left") ax.grid() # ax.set_xlabel('seconds') ax.set_ylabel((self.unit if self.unit else "it") + "/s") if self.unit_scale: plt.ticklabel_format(style="sci", axis="y", scilimits=(0, 0)) ax.yaxis.get_offset_text().set_x(-0.15) # Remember if external environment is interactive self.wasion = plt.isinteractive() plt.ion() self.ax = ax
def _redraw(self): if plt.isinteractive(): fig = self.kwargs["fig"] if not plt.fignum_exists(fig.number): fig.show() fig.canvas.draw() else: print("Redraw() is unsupported in non-interactive plotting mode!")
def view(data, enc=None, start_pos=None, delimiter=None, hdr_rows=None, idx_cols=None, sheet_index=0, transpose=False, wait=None, recycle=None, detach=None, metavar=None, title=None): global WAIT, RECYCLE, DETACH, VIEW # if data is a file/path, read it if isinstance(data, basestring) or isinstance(data, (io.IOBase, file)): data = read_table(data, enc, delimiter, hdr_rows, sheet_index) if hdr_rows is None: hdr_rows = 1 if len(data) > 1 else 0 # only assume an header when loading from a file if hdr_rows is None: hdr_rows = 0 if idx_cols is None: idx_cols = 0 model = as_model(data, hdr_rows=hdr_rows, idx_cols=idx_cols, transpose=transpose) if model is None: warnings.warn("cannot visualize the supplied data type: {}".format(type(data)), category=RuntimeWarning) return None # setup defaults if wait is None: wait = WAIT if recycle is None: recycle = RECYCLE if detach is None: detach = DETACH if wait is None: if 'matplotlib' not in sys.modules: wait = not bool(detach) else: import matplotlib.pyplot as plt wait = not plt.isinteractive() # try to fetch the variable name in the upper stack if metavar is None: if isinstance(data, basestring): metavar = data else: metavar = _varname_in_stack(data, 1) # create a view controller if VIEW is None: if not detach: VIEW = ViewController() else: VIEW = DetachedViewController() VIEW.setDaemon(True) VIEW.start() if VIEW.is_detached(): atexit.register(VIEW.exit) else: VIEW = None return None # actually show the data view_kwargs = {'hdr_rows': hdr_rows, 'idx_cols': idx_cols, 'start_pos': start_pos, 'metavar': metavar, 'title': title} VIEW.view(model, view_kwargs, wait=wait, recycle=recycle) return VIEW
def save_plot(self, filename, a, title="", xlabel="", ylabel="", color=plt.cm.jet): """Create and save a plot of the data or weights map; see make_plot() for usage.""" interactive = plt.isinteractive() self.make_plot(a, title=title, xlabel=xlabel, ylabel=ylabel, color=color) plt.savefig(filename) if interactive: plt.ion() else: plt.close()
def _ToImageString(graph): """ Convert as image string. Parameters ---------- graph : object A Graph, Drawable or GridLayout object. Returns ------- image_str : str An image representation as string Examples -------- >>> import openturns as ot >>> import openturns.viewer as otv >>> n = ot.Normal() >>> graph = n.drawPDF() >>> imageString = otv._ToImageString(graph) """ # save interactive mode state ision = plt.isinteractive() plt.ioff() view = View(graph) output = io.BytesIO() fmt = ot.ResourceMap.Get('View-ImageFormat') view.save(output, format=fmt, dpi=100) view.close() # restore interactive mode state if ision: plt.ion() image_bytes = output.getvalue() if fmt == 'svg': image_string = image_bytes.decode('utf-8') else: # raw bytes image_string = image_bytes return image_string
def save_contour(self, filename, a, contours=None, title="", xlabel="", ylabel="", color=plt.cm.jet): """ Save a contour plot of the given array; see make_plot() for usage. """ interactive = plt.isinteractive() fig = self.make_contour(a, contours, title, xlabel, ylabel, color) plt.savefig(filename) if interactive: plt.ion() return fig else: plt.close()
def histo(a, fmt='b', bins=10, ax=None, lw=2, log=False, **kwargs): """ Plot a histogram, without all the unnecessary stuff matplotlib's hist() function does.""" if ax is None: pl.figure() ax = pl.gca() a = np.asarray(a).ravel() a = a[~np.isnan(a)] vals, bins = np.histogram(a, bins=bins) if log: vals = np.where(vals > 0, np.log10(vals), vals) b = np.repeat(bins, 2) V = np.concatenate([[0], np.repeat(vals, 2), [0]]) ax.plot(b, V, fmt, lw=lw, **kwargs) if pl.isinteractive(): pl.show() return vals, bins
def toggle_pylab(fn): """ A decorator to prevent functions from opening matplotlib windows unexpectedly when sunpy is run in interactive shells like ipython --pylab. Toggles the value of matplotlib.pyplot.isinteractive() to preserve the users' expections of pylab's behaviour in general. """ if pyplot.isinteractive(): def fn_itoggle(*args, **kwargs): pyplot.ioff() ret = fn(*args, **kwargs) pyplot.ion() return ret return fn_itoggle else: return fn
def geom_to_picture(geom, filename, xrange=None, yrange=None, axis_visible=True, pixratio=150, patchkws={'color':'#000000'}): """ Save a geometry as a picture geom: a geometry filename: the filename of the picture. The extension determines the format xrange, yrange: use it to save a selection of the picture. None => select the entire geometry xsize pixratio = --------- pixels If your image is 10x10 and pixratio=100, the resulting image will be 1000x1000 pixels NB: when saving to raster files (png, jpg, etc.) the size in pixels of the image will be (xsize * (dpi/2), ysize * (dpi/2)) Returns ======= a matplotlib figure """ isinteractive = pyplot.isinteractive() if isinteractive: pyplot.ioff() fig = geom_to_fig(geom, xrange=xrange, yrange=yrange, axis_visible=axis_visible, patchkws=patchkws) ax = fig.gca() x0, y0, x1, y1 = util.geom_getbounds(geom, xrange, yrange) xsize = (x1 - x0) * pixratio if dpi is None: dpi = 200 * xsize / 1128. if not axis_visible: fig.tight_layout() fig.savefig(filename, dpi=dpi, bbox_inches='tight', pad_inches=0) else: fig.savefig(filename, dpi=dpi, bbox_inches='tight') if isinteractive: pyplot.ion() return fig
def mpl_context(show=None,clf=False,savefn=None): """ Used for with statements containing matplotlib plots. Usage:: with _mpl_context() as plt: plt.plot(x,y,...) plt.scatter(xs,ys,...) :param bool show: If True,:func:`pyplot.show` will be called when plotting is completed. This blocks execution until the user closes the plotting window. :param bool clf: If True, the figure will be cleared before plotting. :param savefn: A string to save the figure to via the :func:`matplotlib.pyplot.savefig` function, or None to not save the figure. """ import matplotlib.pyplot as plt if show is None: show = _mpl_show_default isinter = plt.isinteractive() try: if isinter: #TODO: figure out why this is necessary (probably an mpl/ipython problem) plt.gcf() plt.interactive(False) if clf: plt.clf() yield plt finally: plt.interactive(isinter) if savefn: plt.savefig(savefn) if show: plt.draw() plt.show() else: plt.draw_if_interactive()
def __init__(self, input_channel, refresh_rate=2, title='Scipy Simulator Dynamic Plot', own_fig=False, xlabel=None, ylabel=None): super(Stemmer, self).__init__(input_channel=input_channel) import matplotlib.pyplot as plt import matplotlib.lines as lines self.x_axis_data = [] self.y_axis_data = [] assert refresh_rate != 0 self.refresh_rate = refresh_rate self.min_refresh_time = 1.0 / self.refresh_rate plt.ioff() # Only draw when we say assert plt.isinteractive() == False # stem() doesn't seem to like empty datasets, so we'll defer creating # the plot until there's actually data. For now just create an # empty canvas self.fig_num = self.additional_figures self.__class__.additional_figures += 1 with GUI_LOCK: fig = self.myfig = plt.figure() self.ax = fig.add_subplot(1, 1, 1) self.title = self.ax.set_title(title) self.markerline = None self.stemlines = None self.baseline = None if xlabel is not None: self.ax.set_xlabel(xlabel) if ylabel is not None: self.ax.set_ylabel(ylabel) self.refreshs = 0 self.last_update = 0 self.__class__.firstPlot = False
def hinton(m, maxweight=None): """Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. Note ---- Because the values of the matrix are assumed to be *weights*, NaN values are replaced by zero (otherwise the plot doesn't come good). """ W = m.copy() W[np.isnan(W)] = 0 reenable = False if plt.isinteractive(): plt.ioff() #plt.clf() height, width = W.shape if not maxweight: maxweight = 2**np.ceil(np.log(np.max(np.abs(W))) / np.log(2)) plt.fill(np.array([0, width, width, 0]), np.array([0, 0, height, height]), 'gray') plt.axis('off') plt.axis('equal') for x in xrange(width): for y in xrange(height): _x = x + 1 _y = y + 1 w = W[y, x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, min(1, w / maxweight), 'white') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, min(1, -w / maxweight), 'black') if reenable: plt.ion()
def IQ_circle(r, title="", xlabel=r"Re $S_{21}$", ylabel=r"Im $S_{21}$", plot_masked=True, **kwds): interactive = plt.isinteractive() plt.ioff() fig, ax = plt.subplots() extracted = extract(r, **kwds) ax.plot(extracted['data'].real, extracted['data'].imag, linestyle='None', marker='.', color='blue', label='data') if plot_masked and extracted['masked'].size: ax.plot(extracted['masked'].real, extracted['masked'].imag, linestyle='None', marker='.', color='gray', label='masked') ax.plot(extracted['model'].real, extracted['model'].imag, linestyle='-', linewidth=0.5, color='brown', label='fit') ax.plot(extracted['model_0'].real, extracted['model_0'].imag, linestyle='None', marker='.', color='brown', label='$f_0$') ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) fig.suptitle(title) if interactive: plt.ion() plt.show() return fig
def save_plot(self, filename, a, title="", xlabel="", ylabel="", color=plt.cm.hot, vmin=None, vmax=None): """ Save a plot of the given array; see make_plot() for usage. """ interactive = plt.isinteractive() fig = self.make_plot(a, title, xlabel, ylabel, color, vmin, vmax) plt.savefig(filename) if interactive: plt.ion() return fig else: plt.close()
def run(self): # print 'optics run' self.ont = self.t self.xaxis = getattr(self.ont, self.x) is_ion = _p.isinteractive() _p.interactive(False) self.lines = [] self.legends = [] # self.figure.lines=[] # self.figure.patches=[] # self.figure.texts=[] # self.figure.images = [] self.figure.legends = [] if self.lattice: self.lattice.patches = [] self._lattice(['k0l', 'kn0l', 'angle'], "#a0ffa0", 'Bend h') self._lattice(['ks0l'], "#ffa0a0", 'Bend v') self._lattice(['kn1l', 'k1l'], "#a0a0ff", 'Quad') self._lattice(['hkick'], "#e0a0e0", 'Kick h') self._lattice(['vkick'], "#a0e0e0", 'Kick v') self._lattice(['kn2l', 'k2l'], "#e0e0a0", 'Sext') if self.left: self.left.lines = [] for i in self.yl: self._column(i, self.left, self.color[i]) if self.right: self.right.lines = [] for i in self.yr: self._column(i, self.right, self.color[i]) ca = self.figure.gca() ca.set_xlabel(_mylbl(self.axlabel, self.x)) ca.set_xlim(min(self.xaxis[self.idx]), max(self.xaxis[self.idx])) self.figure.legend(self.lines, self.legends, 'upper right') ca.grid(True) # self.figure.canvas.mpl_connect('button_release_event',self.button_press) self.figure.canvas.mpl_connect('pick_event', self.pick) _p.interactive(is_ion) self.figure.canvas.draw() if hasattr(self, 'on_run'): self.on_run(self)
def plotPioneer(self, number, y=1): """ Plotting regions and obstacles with matplotlib.pyplot number: figure number (see on top) y = 0 : plot self.map_work instead of self.map """ if self.operate_system == 1: if not plt.isinteractive(): plt.ion() plt.hold(True) for regionName, regionPoly in self.map.iteritems(): self.plotPoly(regionPoly, 'k') if self.system == 1: if bool(self.robocomm.getObsPoly()): self.plotPoly(self.robocomm.getObsPoly(), 'k') if self.operate_system == 1: plt.figure(number).canvas.draw()
def show_patcher(show_func): """ patch the plt.show() if interactive is enabled to display and then close the plot after 1 second so plt.show() will not block the script and the figure is still visible to the user :param show_func: :return: """ def new_show_func(*args, **kwargs): stuff = show_func(*args, **kwargs) # wait 1 second for the image to show on screen figManager = plt.gcf() if figManager is not None: canvas = figManager.canvas # if canvas.figure.stale: # canvas.draw() # show(block=False) canvas.start_event_loop(1) # wait time = 1 plt.close() return stuff return new_show_func if plt.isinteractive() else show_func
def plot(self, effic=False, atmos=False, ymax=None, **kwargs): """ Plots the passband. We plot the non-normalised transmission. This may or may not include ccd efficiency, losses from the atmosphere and telescope optics. """ tr = self.tr if ymax is not None: tr = self.tr / self.tr.max() * ymax pl.plot(self.wa, tr, **kwargs) if self.effic is not None and effic: pl.plot(self.wa, self.effic, label='applied ccd efficiency', **kwargs) if self.atmos is not None and atmos: pl.plot(self.wa, self.atmos, label='applied atmospheric extinction', **kwargs) pl.xlabel("Wavelength ($\AA$)") pl.ylabel("Transmission") if atmos or effic: pl.legend() if pl.isinteractive(): pl.show()
def _gen_svg_thumbnail(self): import matplotlib.pyplot as plt # Store some previous states prev_level = logger.getEffectiveLevel() prev_pbar = config.pbar_hide prev_int = plt.isinteractive() plt.ioff() # turn off interactive mode logger.setLevel('WARNING') config.pbar_hide = True fig = plt.figure(figsize=(2, 2)) ax = fig.add_subplot(111) fig, ax = self.plot2d(connectors=False, ax=ax) output = StringIO() fig.savefig(output, format='svg') if prev_int: plt.ion() # turn on interactive mode logger.setLevel(prev_level) config.pbar_hide = prev_pbar _ = plt.clf() return output.getvalue()
def __init__(self, cmap: str = "gray"): """Parameters ---------- cmap Colormap to use for displaying images. """ if plt.isinteractive(): warnings.warn("Turning off matplotlib's interactive mode as it " "is not compatible with this.") plt.ioff() # General options self._algo_sel = ipywidgets.Dropdown( options=[A.name for A in algorithms], description="algorithm") self._loc_options = [A() for A in algorithms] for lo in self._loc_options: lo.observe(self._options_changed, "options") # The figure ax = plt.subplots()[1] self.image_display = ImageDisplay(ax, cmap=cmap) traitlets.directional_link((self, "input"), (self.image_display, "input")) # Display preview self._show_loc_check = ipywidgets.Checkbox( description="Show loc.", indent=False, value=True) self._scatter_artist = None left_box = ipywidgets.VBox([self._algo_sel, *self._loc_options, self._show_loc_check]) super().__init__([left_box, self.image_display]) traitlets.link((self._algo_sel, "value"), (self, "algorithm")) self.observe(self._update, "options") self.observe(self._options_trait_changed, "options") self._show_loc_check.observe(self._update, "value")
def hinton(W, maxweight=None): """ Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. """ reenable = False if plt.isinteractive(): plt.ioff() plt.clf() height, width = W.shape if not maxweight: maxweight = 2**np.ceil(np.log(np.max(np.abs(W)))/np.log(2)) plt.fill(np.array([0, width, width, 0]), np.array([0, 0, height, height]), 'gray') plt.axis('off') plt.axis('equal') for x in range(width): for y in range(height): _x = x+1 _y = y+1 w = W[y, x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, min(1, w/maxweight), 'white') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, min(1, -w/maxweight), 'black') if reenable: plt.ion()
def wait_fig(): ''' Function requires figure to remain open unitl all code has run and figure has shown all agent iterations. Returns ------- Animation sequence. ''' # Block the execution of the code until the figure is closed. # This works even with multiprocessing. if plt.isinteractive(): plt.ioff() # this is necessary in mutliprocessing #plt.show(block=True) plt.show(block=False) plt.ion() # restitute the interractive state else: #plt.show(block=True) plt.show(block=False) plt.pause(1) #closes figure automatically plt.close() return
def change_projection(self, owner): if owner.description == self.current_projection: owner.button_style = "info" return if self.current_projection is not None: self.buttons[self.current_projection].button_style = "" # Temporarily disable automatic plotting in notebook if plt.isinteractive(): plt.ioff() re_enable_interactive = True else: re_enable_interactive = False update_children = False if owner.description == "3D": self.projection_3d() self.do_update = self.update_colors_3d else: if self.current_projection == "3D" or \ self.current_projection is None: update_children = True self.projection_2d(owner.description, update_children) self.do_update = self.update_colors_2d self.update_colors({"new": self.slider.value}) self.current_projection = owner.description self.buttons[owner.description].button_style = "info" # Re-enable automatic plotting in notebook if re_enable_interactive: plt.ion() return
def data_mouse(): """Simple by-hand data generation using the GUI Opens a matplotlib plot window, and allows the user to specify points with the mouse. Each button is its own class (1,2,3); close the window when done creating data. Returns: X (arr): Mx2 array of data locations Y (arr): Mx1 array of labels (buttons) """ import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, xlim=(-1, 2), ylim=(-1, 2)) X = np.zeros((0, 2)) Y = np.zeros((0, )) col = ['bs', 'gx', 'ro'] def on_click(event): X.resize((X.shape[0] + 1, X.shape[1])) X[-1, :] = [event.xdata, event.ydata] Y.resize((Y.shape[0] + 1, )) Y[-1] = event.button ax.plot(event.xdata, event.ydata, col[event.button - 1]) fig.canvas.draw() fig.canvas.mpl_connect('button_press_event', on_click) inter = plt.isinteractive() hld = plt.ishold() plt.ioff() plt.hold(True) plt.show() if inter: plt.ion() if not hld: plt.hold(False) return X, Y
def show(block=True, equal_aspect=False, border_width=0, show_grid=False, close_esc=True): """Show the plot with possible additional settings. :type block: bool :type equal_aspect: bool :type border_width: float :type show_grid: bool :type close_esc: bool """ if equal_aspect: ax = plt.gca() ax.set_aspect('equal') if border_width > 0: set_border(border_width) if show_grid: plt.grid(show_grid) if close_esc: fig = plt.gcf() def on_key_pressed(event): if event.key == 'escape': plt.close(fig) fig.canvas.mpl_connect('key_press_event', on_key_pressed) if not plt.isinteractive(): plt.show(block=block)
def mpl_draw(graph, pos=None, ax=None, arrows=True, with_labels=False, **kwds): r"""Draw a graph with Matplotlib. .. note:: Matplotlib is an optional dependency and will not be installed with retworkx by default. If you intend to use this function make sure that you install matplotlib with either ``pip install matplotlib`` or ``pip install 'retworkx[mpl]'`` :param graph: A retworkx graph, either a :class:`~retworkx.PyGraph` or a :class:`~retworkx.PyDiGraph`. :param dict pos: An optional dictionary (or a :class:`~retworkx.Pos2DMapping` object) with nodes as keys and positions as values. If not specified a spring layout positioning will be computed. See `layout_functions` for functions that compute node positions. :param matplotlib.Axes ax: An optional Matplotlib Axes object to draw the graph in. :param bool arrows: For :class:`~retworkx.PyDiGraph` objects if ``True`` draw arrowheads. (defaults to ``True``) Note, that the Arrows will be the same color as edges. :param str arrowstyle: An optional string for directed graphs to choose the style of the arrowsheads. See :class:`matplotlib.patches.ArrowStyle` for more options. By default the value is set to ``'-\|>'``. :param int arrow_size: For directed graphs, choose the size of the arrow head's length and width. See :class:`matplotlib.patches.FancyArrowPatch` attribute and constructor kwarg ``mutation_scale`` for more info. Defaults to 10. :param bool with_labels: Set to ``True`` to draw labels on the nodes. Edge labels will only be drawn if the ``edge_labels`` parameter is set to a function. Defaults to ``False``. :param list node_list: An optional list of node indices in the graph to draw. If not specified all nodes will be drawn. :param list edge_list: An option list of edges in the graph to draw. If not specified all edges will be drawn :param int|list node_size: Optional size of nodes. If an array is specified it must be the same length as node_list. Defaults to 300 :param node_color: Optional node color. Can be a single color or a sequence of colors with the same length as node_list. Color can be string or rgb (or rgba) tuple of floats from 0-1. If numeric values are specified they will be mapped to colors using the ``cmap`` and ``vmin``,``vmax`` parameters. See :func:`matplotlib.scatter` for more details. Defaults to ``'#1f78b4'``) :param str node_shape: The optional shape node. The specification is the same as the :func:`matplotlib.pyplot.scatter` function's ``marker`` kwarg, valid options are one of ``['s', 'o', '^', '>', 'v', '<', 'd', 'p', 'h', '8']``. Defaults to ``'o'`` :param float alpha: Optional value for node and edge transparency :param matplotlib.colors.Colormap cmap: An optional Matplotlib colormap object for mapping intensities of nodes :param float vmin: Optional minimum value for node colormap scaling :param float vmax: Optional minimum value for node colormap scaling :param float|sequence linewidths: An optional line width for symbol borders. If a sequence is specified it must be the same length as node_list. Defaults to 1.0 :param float|sequence width: An optional width to use for edges. Can either be a float or sequence of floats. If a sequence is specified it must be the same length as node_list. Defaults to 1.0 :param str|sequence edge_color: color or array of colors (default='k') Edge color. Can be a single color or a sequence of colors with the same length as edge_list. Color can be string or rgb (or rgba) tuple of floats from 0-1. If numeric values are specified they will be mapped to colors using the ``edge_cmap`` and ``edge_vmin``, ``edge_vmax`` parameters. :param matplotlib.colors.Colormap edge_cmap: An optional Matplotlib colormap for mapping intensities of edges. :param float edge_vmin: Optional minimum value for edge colormap scaling :param float edge_vmax: Optional maximum value for node colormap scaling :param str style: An optional string to specify the edge line style. For example, ``'-'``, ``'--'``, ``'-.'``, ``':'`` or words like ``'solid'`` or ``'dashed'``. See the :class:`matplotlib.patches.FancyArrowPatch` attribute and kwarg ``linestyle`` for more details. Defaults to ``'solid'``. :param func labels: An optional callback function that will be passed a node payload and return a string label for the node. For example:: labels=str could be used to just return a string cast of the node's data payload. Or something like:: labels=lambda node: node['label'] could be used if the node payloads are dictionaries. :param func edge_labels: An optional callback function that will be passed an edge payload and return a string label for the edge. For example:: edge_labels=str could be used to just return a string cast of the edge's data payload. Or something like:: edge_labels=lambda edge: edge['label'] could be used if the edge payloads are dictionaries. If this is set edge labels will be drawn in the visualization. :param int font_size: An optional fontsize to use for text labels, By default a value of 12 is used for nodes and 10 for edges. :param str font_color: An optional font color for strings. By default ``'k'`` (ie black) is set. :param str font_weight: An optional string used to specify the font weight. By default a value of ``'normal'`` is used. :param str font_family: An optional font family to use for strings. By default ``'sans-serif'`` is used. :param str label: An optional string label to use for the graph legend. :param str connectionstyle: An optional value used to create a curved arc of rounding radius rad. For example, ``connectionstyle='arc3,rad=0.2'``. See :class:`matplotlib.patches.ConnectionStyle` and :class:`matplotlib.patches.FancyArrowPatch` for more info. By default this is set to ``"arc3"``. :returns: A matplotlib figure for the visualization if not running with an interactive backend (like in jupyter) or if ``ax`` is not set. :rtype: matplotlib.figure.Figure For Example: .. jupyter-execute:: import matplotlib.pyplot as plt import retworkx from retworkx.visualization import mpl_draw G = retworkx.generators.directed_path_graph(25) mpl_draw(G) plt.draw() """ try: import matplotlib.pyplot as plt except ImportError as e: raise ImportError("matplotlib needs to be installed prior to running " "retworkx.visualization.mpl_draw(). You can install " "matplotlib with:\n'pip install matplotlib'") from e if ax is None: cf = plt.gcf() else: cf = ax.get_figure() cf.set_facecolor("w") if ax is None: if cf._axstack() is None: ax = cf.add_axes((0, 0, 1, 1)) else: ax = cf.gca() draw_graph(graph, pos=pos, ax=ax, arrows=arrows, with_labels=with_labels, **kwds) ax.set_axis_off() plt.draw_if_interactive() if not plt.isinteractive() or ax is None: return cf
def annotate3d(centroids, image, **kwargs): """Annotates a 3D image and returns a scrollable stack for display in IPython. Parameters ---------- centroids : DataFrame including columns x and y image : image array (or string path to image file) circle_size : Deprecated. This will be removed in a future version of trackpy. Use `plot_style={'markersize': ...}` instead. color : single matplotlib color or a list of multiple colors default None invert : If you give a filepath as the image, specify whether to invert black and white. Default True. ax : matplotlib axes object, defaults to current axes split_category : string, parameter to use to split the data into sections default None split_thresh : single value or list of ints or floats to split particles into sections for plotting in multiple colors. List items should be ordered by increasing value. default None imshow_style : dictionary of keyword arguments passed through to the `Axes.imshow(...)` command the displays the image plot_style : dictionary of keyword arguments passed through to the `Axes.plot(...)` command that marks the features Returns ------- pims.Frame object containing a three-dimensional RGBA image See Also -------- annotate : annotation of 2D images """ if plots_to_frame is None: raise ImportError('annotate3d requires pims 0.3 or later. Please ' 'install/update pims') import matplotlib as mpl import matplotlib.pyplot as plt if image.ndim != 3 and not (image.ndim == 4 and image.shape[-1] in (3, 4)): raise ValueError("image has incorrect dimensions. Please input a 3D " "grayscale or RGB(A) image. For 2D image annotation, " "use annotate. Multichannel images can be " "converted to RGB using pims.display.to_rgb.") # We want to normalize on the full image and stop imshow from normalizing. normalized = (normalize(image) * 255).astype(np.uint8) imshow_style = dict(vmin=0, vmax=255) if '_imshow_style' in kwargs: kwargs['imshow_style'].update(imshow_style) else: kwargs['imshow_style'] = imshow_style max_open_warning = mpl.rcParams['figure.max_open_warning'] was_interactive = plt.isinteractive() try: # Suppress warning when many figures are opened mpl.rc('figure', max_open_warning=0) # Turn off interactive mode (else the closed plots leave emtpy space) plt.ioff() figures = [None] * len(normalized) for i, imageZ in enumerate(normalized): fig = plt.figure() kwargs['ax'] = fig.gca() centroidsZ = centroids[(centroids['z'] > i - 0.5) & (centroids['z'] < i + 0.5)] annotate(centroidsZ, imageZ, **kwargs) figures[i] = fig result = plots_to_frame(figures, width=512, close_fig=True, bbox_inches='tight') finally: # put matplotlib back in original state if was_interactive: plt.ion() mpl.rc('figure', max_open_warning=max_open_warning) return result
def __init__(self, *args, **kwargs): # try: # pragma: no cover import matplotlib as mpl import matplotlib.pyplot as plt from collections import deque # except ImportError: # gui not available # kwargs['gui'] = False # else: kwargs['gui'] = True super(tqdm_gui, self).__init__(*args, **kwargs) # Initialize the GUI display if self.disable or not kwargs['gui']: return self.fp.write('Warning: GUI is experimental/alpha\n') self.mpl = mpl self.plt = plt self.sp = None # Remember if external environment uses toolbars self.toolbar = self.mpl.rcParams['toolbar'] self.mpl.rcParams['toolbar'] = 'None' self.mininterval = max(self.mininterval, 0.5) self.fig, ax = plt.subplots(figsize=(9, 2.2)) # self.fig.subplots_adjust(bottom=0.2) if self.total: self.xdata = [] self.ydata = [] self.zdata = [] else: self.xdata = deque([]) self.ydata = deque([]) self.zdata = deque([]) self.line1, = ax.plot(self.xdata, self.ydata, color='b') self.line2, = ax.plot(self.xdata, self.zdata, color='k') ax.set_ylim(0, 0.001) if self.total: ax.set_xlim(0, 100) ax.set_xlabel('percent') self.fig.legend((self.line1, self.line2), ('cur', 'est'), loc='center right') # progressbar self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color='g') else: # ax.set_xlim(-60, 0) ax.set_xlim(0, 60) ax.invert_xaxis() ax.set_xlabel('seconds') ax.legend(('cur', 'est'), loc='lower left') ax.grid() # ax.set_xlabel('seconds') ax.set_ylabel((self.unit if self.unit else 'it') + '/s') if self.unit_scale: plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) ax.yaxis.get_offset_text().set_x(-0.15) # Remember if external environment is interactive self.wasion = plt.isinteractive() plt.ion() self.ax = ax
def __init__(self, *args, **kwargs): from collections import deque import matplotlib as mpl import matplotlib.pyplot as plt kwargs = kwargs.copy() kwargs['gui'] = True colour = kwargs.pop('colour', 'g') super(tqdm_gui, self).__init__(*args, **kwargs) if self.disable: return warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2) self.mpl = mpl self.plt = plt # Remember if external environment uses toolbars self.toolbar = self.mpl.rcParams['toolbar'] self.mpl.rcParams['toolbar'] = 'None' self.mininterval = max(self.mininterval, 0.5) self.fig, ax = plt.subplots(figsize=(9, 2.2)) # self.fig.subplots_adjust(bottom=0.2) total = self.__len__() # avoids TypeError on None #971 if total is not None: self.xdata = [] self.ydata = [] self.zdata = [] else: self.xdata = deque([]) self.ydata = deque([]) self.zdata = deque([]) self.line1, = ax.plot(self.xdata, self.ydata, color='b') self.line2, = ax.plot(self.xdata, self.zdata, color='k') ax.set_ylim(0, 0.001) if total is not None: ax.set_xlim(0, 100) ax.set_xlabel("percent") self.fig.legend((self.line1, self.line2), ("cur", "est"), loc='center right') # progressbar self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour) else: # ax.set_xlim(-60, 0) ax.set_xlim(0, 60) ax.invert_xaxis() ax.set_xlabel("seconds") ax.legend(("cur", "est"), loc='lower left') ax.grid() # ax.set_xlabel('seconds') ax.set_ylabel((self.unit if self.unit else "it") + "/s") if self.unit_scale: plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) ax.yaxis.get_offset_text().set_x(-0.15) # Remember if external environment is interactive self.wasion = plt.isinteractive() plt.ion() self.ax = ax
from scipy import ndimage as nd import astropy.units as u import matplotlib.pyplot as plt import seaborn as sb from radio_beam import Beam import pymc3 as pm import pandas as pd osjoin = os.path.join from turbustat.statistics import PowerSpectrum from turbustat.statistics.psds import make_radial_freq_arrays make_interactive = False if not plt.isinteractive() and make_interactive: plt.ion() else: plt.ioff() # Running on SegFault w/ data on bigdata data_path = os.path.expanduser("~/bigdata/ekoch/Utomo19_LGdust/") # Load model functions repo_path = os.path.expanduser("~/ownCloud/project_code/DustyPowerSpectra/") code_name = os.path.join(repo_path, "models.py") exec(compile(open(code_name, "rb").read(), code_name, 'exec')) # Load in fit settings # fitsetting_name = os.path.join(repo_path, "fit_settings.py") # exec(compile(open(code_name, "rb").read(), fitsetting_name, 'exec'))
recvbuf=[counts, MPI.INTEGER], root=MPI.ROOT) worker.Gatherv(sendbuf=None, recvbuf=[indices, (counts, None), MPI.INTEGER], root=MPI.ROOT) rowtype = MPI.INTEGER.Create_contiguous(w).Commit() worker.Gatherv(sendbuf=None, recvbuf=[result, (counts, None), rowtype], root=MPI.ROOT) rowtype.Free() # disconnect worker worker.Disconnect() # reconstruct result C = numpy.empty([h, w], dtype='i') C[indices, :] = result try: from matplotlib import pyplot as plt plt.imshow(C, aspect='equal') plt.spectral() if not plt.isinteractive(): import signal def action(*args): raise SystemExit signal.signal(signal.SIGALRM, action) signal.alarm(2) plt.show() except: pass
def show_discrete_data(values, grid, title=None, method='', force_show=False, fig=None, **kwargs): """Display a discrete 1d or 2d function. Parameters ---------- values : `numpy.ndarray` The values to visualize. grid : `RectGrid` or `RectPartition` Grid of the values. title : string, optional Set the title of the figure. method : string, optional 1d methods: 'plot' : graph plot 'scatter' : scattered 2d points (2nd axis <-> value) 2d methods: 'imshow' : image plot with coloring according to value, including a colorbar. 'scatter' : cloud of scattered 3d points (3rd axis <-> value) 'wireframe', 'plot_wireframe' : surface plot force_show : bool, optional Whether the plot should be forced to be shown now or deferred until later. Note that some backends always displays the plot, regardless of this value. fig : `matplotlib.figure.Figure`, optional The figure to show in. Expected to be of same "style", as the figure given by this function. The most common usecase is that fig is the return value from an earlier call to this function. Default: New figure interp : {'nearest', 'linear'}, optional Interpolation method to use. Default: 'nearest' axis_labels : string, optional Axis labels, default: ['x', 'y'] update_in_place : bool, optional Update the content of the figure in place. Intended for faster real time plotting, typically ~5 times faster. This is only performed for ``method == 'imshow'`` with real data and ``fig != None``. Otherwise this parameter is treated as False. Default: False axis_fontsize : int, optional Fontsize for the axes. Default: 16 kwargs : {'figsize', 'saveto', ...}, optional Extra keyword arguments passed on to display method See the Matplotlib functions for documentation of extra options. Returns ------- fig : `matplotlib.figure.Figure` The resulting figure. It is also shown to the user. See Also -------- matplotlib.pyplot.plot : Show graph plot matplotlib.pyplot.imshow : Show data as image matplotlib.pyplot.scatter : Show scattered 3d points """ # Importing pyplot takes ~2 sec, only import when needed. import matplotlib.pyplot as plt args_re = [] args_im = [] dsp_kwargs = {} sub_kwargs = {} arrange_subplots = (121, 122) # horzontal arrangement # Create axis labels which remember their original meaning axis_labels = kwargs.pop('axis_labels', ['x', 'y']) values_are_complex = not is_real_dtype(values.dtype) figsize = kwargs.pop('figsize', None) saveto = kwargs.pop('saveto', None) interp = kwargs.pop('interp', 'nearest') axis_fontsize = kwargs.pop('axis_fontsize', 16) # Check if we should and can update the plot in place update_in_place = kwargs.pop('update_in_place', False) if (update_in_place and (fig is None or values_are_complex or values.ndim != 2 or (values.ndim == 2 and method not in ('', 'imshow')))): update_in_place = False if values.ndim == 1: # TODO: maybe a plotter class would be better if not method: if interp == 'nearest': method = 'step' dsp_kwargs['where'] = 'mid' elif interp == 'linear': method = 'plot' else: method = 'plot' if method == 'plot' or method == 'step' or method == 'scatter': args_re += [grid.coord_vectors[0], values.real] args_im += [grid.coord_vectors[0], values.imag] else: raise ValueError('`method` {!r} not supported' ''.format(method)) elif values.ndim == 2: if not method: method = 'imshow' if method == 'imshow': args_re = [np.rot90(values.real)] args_im = [np.rot90(values.imag)] if values_are_complex else [] extent = [ grid.min()[0], grid.max()[0], grid.min()[1], grid.max()[1] ] if interp == 'nearest': interpolation = 'nearest' elif interp == 'linear': interpolation = 'bilinear' else: interpolation = 'none' dsp_kwargs.update({ 'interpolation': interpolation, 'cmap': 'bone', 'extent': extent, 'aspect': 'auto' }) elif method == 'scatter': pts = grid.points() args_re = [pts[:, 0], pts[:, 1], values.ravel().real] args_im = ([pts[:, 0], pts[:, 1], values.ravel().imag] if values_are_complex else []) sub_kwargs.update({'projection': '3d'}) elif method in ('wireframe', 'plot_wireframe'): method = 'plot_wireframe' x, y = grid.meshgrid args_re = [x, y, np.rot90(values.real)] args_im = ([x, y, np.rot90(values.imag)] if values_are_complex else []) sub_kwargs.update({'projection': '3d'}) else: raise ValueError('`method` {!r} not supported' ''.format(method)) else: raise NotImplementedError('no method for {}d display implemented' ''.format(values.ndim)) # Additional keyword args are passed on to the display method dsp_kwargs.update(**kwargs) if fig is not None: # Reuse figure if given as input if not isinstance(fig, plt.Figure): raise TypeError('`fig` {} not a matplotlib figure'.format(fig)) if not plt.fignum_exists(fig.number): # If figure does not exist, user either closed the figure or # is using IPython, in this case we need a new figure. fig = plt.figure(figsize=figsize) updatefig = False else: # Set current figure to given input fig = plt.figure(fig.number) updatefig = True if values.ndim > 1 and not update_in_place: # If the figure is larger than 1d, we can clear it since we # dont reuse anything. Keeping it causes performance problems. fig.clf() else: fig = plt.figure(figsize=figsize) updatefig = False if values_are_complex: # Real if len(fig.axes) == 0: # Create new axis if needed sub_re = plt.subplot(arrange_subplots[0], **sub_kwargs) sub_re.set_title('Real part') sub_re.set_xlabel(axis_labels[0], fontsize=axis_fontsize) if values.ndim == 2: sub_re.set_ylabel(axis_labels[1], fontsize=axis_fontsize) else: sub_re.set_ylabel('value') else: sub_re = fig.axes[0] display_re = getattr(sub_re, method) csub_re = display_re(*args_re, **dsp_kwargs) # Axis ticks if method == 'imshow' and not grid.is_uniform: (xpts, xlabels), (ypts, ylabels) = _axes_info(grid) plt.xticks(xpts, xlabels) plt.yticks(ypts, ylabels) if method == 'imshow' and len(fig.axes) < 2: # Create colorbar if none seems to exist # Use clim from kwargs if given if 'clim' not in kwargs: minval_re, maxval_re = _safe_minmax(values.real) else: minval_re, maxval_re = kwargs['clim'] ticks_re = _colorbar_ticks(minval_re, maxval_re) format_re = _colorbar_format(minval_re, maxval_re) plt.colorbar(csub_re, orientation='horizontal', ticks=ticks_re, format=format_re) # Imaginary if len(fig.axes) < 3: sub_im = plt.subplot(arrange_subplots[1], **sub_kwargs) sub_im.set_title('Imaginary part') sub_im.set_xlabel(axis_labels[0], fontsize=axis_fontsize) if values.ndim == 2: sub_im.set_ylabel(axis_labels[1], fontsize=axis_fontsize) else: sub_im.set_ylabel('value') else: sub_im = fig.axes[2] display_im = getattr(sub_im, method) csub_im = display_im(*args_im, **dsp_kwargs) # Axis ticks if method == 'imshow' and not grid.is_uniform: (xpts, xlabels), (ypts, ylabels) = _axes_info(grid) plt.xticks(xpts, xlabels) plt.yticks(ypts, ylabels) if method == 'imshow' and len(fig.axes) < 4: # Create colorbar if none seems to exist # Use clim from kwargs if given if 'clim' not in kwargs: minval_im, maxval_im = _safe_minmax(values.imag) else: minval_im, maxval_im = kwargs['clim'] ticks_im = _colorbar_ticks(minval_im, maxval_im) format_im = _colorbar_format(minval_im, maxval_im) plt.colorbar(csub_im, orientation='horizontal', ticks=ticks_im, format=format_im) else: if len(fig.axes) == 0: # Create new axis object if needed sub = plt.subplot(111, **sub_kwargs) sub.set_xlabel(axis_labels[0], fontsize=axis_fontsize) if values.ndim == 2: sub.set_ylabel(axis_labels[1], fontsize=axis_fontsize) else: sub.set_ylabel('value') try: # For 3d plots sub.set_zlabel('z') except AttributeError: pass else: sub = fig.axes[0] if update_in_place: import matplotlib as mpl imgs = [ obj for obj in sub.get_children() if isinstance(obj, mpl.image.AxesImage) ] if len(imgs) > 0 and updatefig: imgs[0].set_data(args_re[0]) csub = imgs[0] # Update min-max if 'clim' not in kwargs: minval, maxval = _safe_minmax(values) else: minval, maxval = kwargs['clim'] csub.set_clim(minval, maxval) else: display = getattr(sub, method) csub = display(*args_re, **dsp_kwargs) else: display = getattr(sub, method) csub = display(*args_re, **dsp_kwargs) # Axis ticks if method == 'imshow' and not grid.is_uniform: (xpts, xlabels), (ypts, ylabels) = _axes_info(grid) plt.xticks(xpts, xlabels) plt.yticks(ypts, ylabels) if method == 'imshow': # Add colorbar # Use clim from kwargs if given if 'clim' not in kwargs: minval, maxval = _safe_minmax(values) else: minval, maxval = kwargs['clim'] ticks = _colorbar_ticks(minval, maxval) format = _colorbar_format(minval, maxval) if len(fig.axes) < 2: # Create colorbar if none seems to exist plt.colorbar(mappable=csub, ticks=ticks, format=format) elif update_in_place: # If it exists and we should update it csub.colorbar.set_clim(minval, maxval) csub.colorbar.set_ticks(ticks) csub.colorbar.set_ticklabels([format % tick for tick in ticks]) csub.colorbar.draw_all() # Fixes overlapping stuff at the expense of potentially squashed subplots if not update_in_place: fig.tight_layout() if title is not None: if not values_are_complex: # Do not overwrite title for complex values plt.title(title) fig.canvas.manager.set_window_title(title) if updatefig or plt.isinteractive(): # If we are running in interactive mode, we can always show the fig # This causes an artifact, where users of `CallbackShow` without # interactive mode only shows the figure after the second iteration. plt.show(block=False) if not update_in_place: plt.draw() plt.pause(0.0001) else: try: sub.draw_artist(csub) fig.canvas.blit(fig.bbox) fig.canvas.update() fig.canvas.flush_events() except AttributeError: plt.draw() plt.pause(0.0001) if force_show: plt.show() if saveto is not None: fig.savefig(saveto) return fig
## """ run throught all images """ data_detection = {} time_str = time.strftime("%Y%m%d_%H%M%S") DIR_DETECTION_RESULT = './detection_result' if not (os.path.exists(DIR_DETECTION_RESULT)): os.mkdir(DIR_DETECTION_RESULT) path_cur_detection_result = os.path.join(DIR_DETECTION_RESULT, time_str) path_cur_detection_result_figs = os.path.join(path_cur_detection_result, 'figs') os.mkdir(path_cur_detection_result) os.mkdir(path_cur_detection_result_figs) flag_isinteractive = plt.isinteractive() plt.ioff() data_to_use_type = 'test_stage2' # or 'test' if data_to_use_type == 'train': data_to_use = data_train elif data_to_use_type == 'test': data_to_use = data_test elif data_to_use_type == 'test_stage2': data_to_use = data_test_stage2 # key_example = random.sample(list(data_to_use.keys()), 5) # data_to_use = {key: data_to_use[key] for key in key_example} for i_image, image_id in enumerate(data_to_use): image = data_to_use[image_id]['image']