我们从Python开源项目中,提取了以下9个代码示例,用于说明如何使用matplotlib.pyplot.isinteractive()。
def comparison_plot(self, **kwargs): """Plot the series of both the `sim` and (if available) the `obs` sequence.""" for (name, seq) in self.sequences: if pyplot.isinteractive(): name = ' '.join((self.name, name)) pyplot.plot(seq.series, label=name, **kwargs) pyplot.legend() variable = self.variable if variable == 'Q': variable = u'Q [m³/s]' pyplot.ylabel(variable) if not pyplot.isinteractive(): pyplot.show()
def _plot(self, subseqs, names, kwargs): if names is not None: subseqs = ((name, getattr(name)) for name in names) for seq in subseqs: if seq.NDIM == 0: label = kwargs.pop('label', ' '.join((self.name, seq.name))) pyplot.plot(seq.series, label=label, **kwargs) pyplot.legend() else: color = kwargs.pop('color', kwargs.pop('c', 'red')) pyplot.plot(seq.series, color=color, **kwargs) if not pyplot.isinteractive(): pyplot.show()
def hinton(W, bg='grey', facecolors=('w', 'k')): """Draw a hinton diagram of the matrix W on the current pylab axis Hinton diagrams are a way of visualizing numerical values in a matrix/vector, popular in the neural networks and machine learning literature. The area occupied by a square is proportional to a value's magnitude, and the colour indicates its sign (positive/negative). Example usage: R = np.random.normal(0, 1, (2,1000)) h, ex, ey = np.histogram2d(R[0], R[1], bins=15) hh = h - h.T hinton.hinton(hh) """ M, N = W.shape square_x = np.array([-.5, .5, .5, -.5]) square_y = np.array([-.5, -.5, .5, .5]) ioff = False if plt.isinteractive(): plt.ioff() ioff = True plt.fill([-.5, N - .5, N - .5, - .5], [-.5, -.5, M - .5, M - .5], bg) Wmax = np.abs(W).max() for m, Wrow in enumerate(W): for n, w in enumerate(Wrow): c = plt.signbit(w) and facecolors[1] or facecolors[0] plt.fill(square_x * w / Wmax + n, square_y * w / Wmax + m, c, edgecolor=c) plt.ylim(-0.5, M - 0.5) plt.xlim(-0.5, M - 0.5) if ioff is True: plt.ion() plt.draw_if_interactive()
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 interactive_matplotlib_context(on=True): old_mode = plt.isinteractive() plt.interactive(on) yield plt.interactive(old_mode)
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 mfista_plots(fdfin, ptable, filename=None, plotargs={'ms': 1., }): isinteractive = plt.isinteractive() backend = matplotlib.rcParams["backend"] if isinteractive: plt.ioff() matplotlib.use('Agg') nullfmt = NullFormatter() # Get model data modelptable = ptable.copy() modelptable.observe(fdfin) # Save fdf if filename is not None: util.matplotlibrc(nrows=4, ncols=2, width=400, height=150) else: matplotlib.rcdefaults() fig, axs = plt.subplots(nrows=4, ncols=2, sharex=False) fdfin.plot(axs=axs[:,0],color="red") ptable.plot(axs=axs[:,1],color="black", ploterror=True) modelptable.plot(axs=axs[:,1], color="red") if filename is not None: plt.savefig(filename) plt.close() else: plt.show() if isinteractive: plt.ion() matplotlib.use(backend)
def plot_tseries(dtimes, data, ax=None, labels=None, datefmt='%b %d, %H:%M', colors=None, ylabel="", title="", fontsize="medium", saveto="", **kwargs): """Plot time series data (e.g. gage recordings) Parameters ---------- dtimes : array of datetime objects (time steps) data : 2D array of shape ( num time steps, num data series ) labels : list of strings (names of data series) title : string kwargs : keyword arguments related to :func:`matplotlib.pyplot.plot` """ if ax is None: returnax = False fig = pl.figure() ax = fig.add_subplot(1, 1, 1, title=title) else: returnax = True # if labels==None: # labels = ["series%d"%i for i in range(1, data.shape[1]+1)] # for i, label in enumerate(labels): # ax.plot_date(mpl.dates.date2num(dtimes),data[:,i],label=label, # color=colors[i], **kwargs) ax.plot_date(mpl.dates.date2num(dtimes), data, **kwargs) ax.xaxis.set_major_formatter(mdates.DateFormatter(datefmt)) pl.setp(ax.get_xticklabels(), visible=True) pl.setp(ax.get_xticklabels(), rotation=-30, horizontalalignment='left') ax.set_ylabel(ylabel, size=fontsize) ax = set_ticklabel_size(ax, fontsize) ax.legend(loc='best') if returnax: return ax if saveto == "": # show plot pl.show() if not pl.isinteractive(): # close figure explicitely if pylab is not in interactive mode pl.close() else: # save plot to file if (path.exists(path.dirname(saveto))) or (path.dirname(saveto) == ''): pl.savefig(saveto) pl.close()