def plot(self,filename=None,plot_skip=None): """Plot density plot of the saved configurations in states[].""" if len(self.states) == 0: raise ValueError("No configurations computed yet. Execute 'run()' first.") import pylab if plot_skip is None: plot_skip = self.runparameters['Nskip'] plot_step = int(plot_skip/self.runparameters['Nskip']) or 1 if plot_step == 1: plot_skip = self.runparameters['Nskip'] site_states = self.states[:,self.firstsiteindex:] # ignore 0 (bulk) maxsite = numpy.max([self.maxstate[site] for site in self.graph \ if site <> SITELABEL['bulk']]) # pylab.clf() img = pylab.imshow(site_states[::plot_step].transpose(), interpolation='nearest',cmap=pylab.cm.hot) img.axes.set_aspect('auto') pylab.colorbar(ticks=range(maxsite+1),shrink=0.75) pylab.title('Number of water molecules per site') pylab.xlabel('MCMC iteration/%d' % plot_skip) pylab.ylabel('site (sequentially enumerated)') pylab.draw_if_interactive() if filename: pylab.savefig(filename)
def plot_compare(t, u, v, fig_title='', file_name=''): """ Compare two signals and plot the difference between them. Parameters ---------- t : ndarray of floats Times (s) at which the signal is defined. u, v : ndarrays of floats Signal samples. fig_title : string Plot title. file_name : string File in which to save the plot. """ p.clf() p.gcf().canvas.set_window_title(fig_title) p.subplot(211) p.plot(t, u, 'b', t, v, 'r') p.xlabel('t (s)') p.ylabel('u(t)') p.title(fig_title) p.gca().set_xlim(min(t), max(t)) p.subplot(212) p.plot(t, 20 * np.log10(abs(u - v))) p.xlabel('t (s)') p.ylabel('error (dB)') p.gca().set_xlim(min(t), max(t)) p.draw_if_interactive() if file_name: p.savefig(file_name)
def fill_ait(self, fignum=11, axes=None, show_kw={}, source_kw={}, figwidth=12, margin=0.15, **kwargs): if axes is None: # set up a figure for 2x1 image with equal margins plt.close(fignum) figheight = figwidth * (1. + 2 * margin) / (1 + margin) / 2. fig = plt.figure(fignum, figsize=(figwidth, figheight)) axes = plt.gca() plt.subplots_adjust(left=0.05, right=0.95) #gives reasonable equal margins pixelsize = kwargs.pop('pixelsize', 0.25) ait = image.AIT(self.get_pyskyfun(), axes=axes, pixelsize=pixelsize, **kwargs) self.imgplot = ait.imshow(**show_kw) ait.axes.set_autoscale_on(False) if self.sources is not None: sdirs = map(SkyDir, self.sources.ra, self.sources.dec) ait.plot(sdirs, **source_kw) print 'found %d sources to plot' % len(sdirs) plt.draw_if_interactive() return ait
def add_edges(self, img, color='r'): """ Plot the edges of a 3D map in all the views. Parameters ----------- map: 3D ndarray The 3D map to be plotted. If it is a masked array, only the non-masked part will be plotted. affine: 4x4 ndarray The affine matrix giving the transformation from voxel indices to world space. color: matplotlib color: string or (r, g, b) value The color used to display the edge map """ img = reorder_img(img) data = img.get_data() affine = img.get_affine() single_color_cmap = colors.ListedColormap([color]) data_bounds = get_bounds(data.shape, img.get_affine()) # For each ax, cut the data and plot it for display_ax in self.axes.itervalues(): try: data_2d = display_ax.transform_to_2d(data, affine) edge_mask = _edge_map(data_2d) except IndexError: # We are cutting outside the indices of the data continue display_ax.draw_2d(edge_mask, data_bounds, data_bounds, type='imshow', cmap=single_color_cmap) pl.draw_if_interactive()
def plot_signal(t, u, fig_title='', file_name=''): """ Plot a signal. Parameters ---------- t : ndarray of floats Times (in s) at which the signal is defined. u : ndarray of floats Signal samples. fig_title : string Plot title. file_name : string File in which to save the plot. """ p.clf() # Set the plot window title: p.gcf().canvas.set_window_title(fig_title) p.plot(t, u) p.xlabel('t (s)') p.ylabel('u(t)') p.title(fig_title) # Make the x axis exactly correspond to the plotted signal's time range: p.gca().set_xlim(min(t), max(t)) p.draw_if_interactive() if file_name: p.savefig(file_name)
def update(self): """ Updates the current plot, if necessary """ if not self.replot: return xr = list(self.Axes.get_xlim()) yr = list(self.Axes.get_ylim()) for i in range(self.nbLines): self.Lines[i].set_data(self.indexList[i], self.dataList[i]) if self.autoscale > 1.0: if self.indexList[i][0] < xr[0]: xr[0] = self.indexList[i][0] ymn = min(self.dataList[i]) if ymn < yr[0]: yr[0] = ymn while self.indexList[i][-1] > xr[1]: xr[1] = (xr[1]-xr[0])*self.autoscale + xr[0] ymx = max(self.dataList[i]) while ymx > yr[1]: yr[1] = (yr[1]-yr[0])*self.autoscale + yr[0] if self.autoscale > 1.0: self.Axes.set_xlim( tuple(xr) ) self.Axes.set_ylim( tuple(yr) ) #self.Axes.draw() #pylab.show() draw_if_interactive() self.replot = False
def update(self): """ Updates the current plot, if necessary """ if not self.replot: return xr = list(self.Axes.get_xlim()) yr = list(self.Axes.get_ylim()) for i in range(self.nbLines): self.Lines[i].set_data(self.indexList[i], self.dataList[i]) if self.autoscale > 1.0: if self.indexList[i][0] < xr[0]: xr[0] = self.indexList[i][0] ymn = min(self.dataList[i]) if ymn < yr[0]: yr[0] = ymn while self.indexList[i][-1] > xr[1]: xr[1] = (xr[1] - xr[0]) * self.autoscale + xr[0] ymx = max(self.dataList[i]) while ymx > yr[1]: yr[1] = (yr[1] - yr[0]) * self.autoscale + yr[0] if self.autoscale > 1.0: self.Axes.set_xlim(tuple(xr)) self.Axes.set_ylim(tuple(yr)) #self.Axes.draw() #pylab.show() draw_if_interactive() self.replot = False
def plot(self, filename=None, plot_skip=None): """Plot density plot of the saved configurations in states[].""" if len(self.states) == 0: raise ValueError( "No configurations computed yet. Execute 'run()' first.") import pylab if plot_skip is None: plot_skip = self.runparameters['Nskip'] plot_step = int(plot_skip / self.runparameters['Nskip']) or 1 if plot_step == 1: plot_skip = self.runparameters['Nskip'] site_states = self.states[:, self.firstsiteindex:] # ignore 0 (bulk) maxsite = numpy.max([self.maxstate[site] for site in self.graph \ if site <> SITELABEL['bulk']]) # pylab.clf() img = pylab.imshow(site_states[::plot_step].transpose(), interpolation='nearest', cmap=pylab.cm.hot) img.axes.set_aspect('auto') pylab.colorbar(ticks=range(maxsite + 1), shrink=0.75) pylab.title('Number of water molecules per site') pylab.xlabel('MCMC iteration/%d' % plot_skip) pylab.ylabel('site (sequentially enumerated)') pylab.draw_if_interactive() if filename: pylab.savefig(filename)
def secondaxes(ax=None, position=True, sharedside='x'): """ Make a new axes overlay ax (or the current axes if ax is None) sharing the specified axis. The ticks for axn will be placed on the specified side, and the axn instance is returned. ax = axes to overlay position = 'top' or 'bottom' for ticks sharedside = 'x' or 'y' for shared axis of graph (forces agreement along this axis) """ if ax is None: ax = pylab.gca() if sharedside == 'x': axn = pylab.gcf().add_axes(ax.get_position(), sharex=ax, frameon=False) elif sharedside == 'y': axn = pylab.gcf().add_axes(ax.get_position(), sharey=ax, frameon=False) pylab.draw_if_interactive() if sharedside == 'x': choose_axes(axn, position=position, side='y') if sharedside == 'y': choose_axes(axn, position=position, side='x') return axn
def plotSignalAndRecoveredSignalAndDenoised(t, u, v, denoised, fig_title): """ Compare two signals and plot the difference between them. Parameters ---------- t : ndarray of floats Times (s) at which the signal is defined. u, v : ndarrays of floats Signal samples. """ p.figure(figsize=(15, 10)) p.clf() p.gcf().canvas.set_window_title(fig_title) p.plot(t, u, 'b', label='u(t)') p.plot(t, v, 'r', label='u_rec(t)') p.plot(t, denoised, 'g', label='denoised u(t)') p.xlabel('t (s)') p.ylabel('u(t)') p.legend() p.title(fig_title) p.gca().set_xlim(min(t), max(t)) p.draw_if_interactive()
def plot_compare(t, u, v, fig_title='', file_name=''): """ Compare two signals and plot the difference between them. Parameters ---------- t : ndarray of floats Times (s) at which the signal is defined. u, v : ndarrays of floats Signal samples. fig_title : string Plot title. file_name : string File in which to save the plot. """ p.clf() p.gcf().canvas.set_window_title(fig_title) p.subplot(211) p.plot(t, u, 'b', t, v, 'r') p.xlabel('t (s)') p.ylabel('u(t)') p.title(fig_title) p.gca().set_xlim(min(t), max(t)) p.subplot(212) p.plot(t, 20*np.log10(abs(u-v))) p.xlabel('t (s)') p.ylabel('error (dB)') p.gca().set_xlim(min(t), max(t)) p.draw_if_interactive() if file_name: p.savefig(file_name)
def plot_raster(ts_list, plot_stems=True, plot_axes=True, marker='.', markersize=5, fig_title='', file_name=''): """ Plot several time sequences as a raster. Parameters ---------- ts_list : list of ndarrays Time sequences to plot. plot_stems : bool Show stems for all events. plot_axes : bool Show horizontal axes for all sequences. marker : char Marker symbol. markersize : int Marker symbol size. fig_title : string Plot title. file_name : string File in which to save the plot. """ M = len(ts_list) p.clf() p.gcf().canvas.set_window_title(fig_title) max_ts = max([max(ts) if len(ts) > 1 else 0 for ts in ts_list]) ax = p.gca() ax.axis([0, max_ts, -0.5, M - 0.5]) p.yticks(xrange(M)) for (ts, y) in zip(ts_list, xrange(M)): if plot_axes: p.axhline(y, 0, 1, color='b', hold=True) p.plot(ts, y * np.ones(len(ts)), marker + 'b', hold=True, markersize=markersize, scalex=False, scaley=False) if plot_stems: for t in ts: ax.add_line( mp.lines.Line2D([t, t], [-0.5, y], color='r', linestyle=':')) ax.xaxis.set_major_locator( mp.ticker.MultipleLocator(10.0**np.ceil(np.log10(max_ts / 10)))) p.xlabel('t (s)') p.title(fig_title) p.draw_if_interactive() if file_name: p.savefig(file_name)
def plot_sigma(sigma): """Plot the singular values, normalized by the first""" P.figure() P.plot(sigma / sigma[0]) P.title('Normalized singular values') P.grid() P.draw_if_interactive()
def plot_sigma(sigma): """Plot the singular values, normalized by the first""" P.figure() P.plot(sigma/sigma[0]) P.title('Normalized singular values') P.grid() P.draw_if_interactive()
def create_common_legend(labels, colors, markers='s', mec=None, linestyles='None', linewidths=None, fig=None, **kwargs): """ Create a legend from the symbols without the actual plot Parameters ---------- labels: seq sequence of label strings colors: seq or Colormap sequence of colors or Colormap instance from which deriving a sequence of colors to encode each group if Colormap instance, a cmap attribute will be generated after a plot and will refer to the updated instance markers: seq sequence of markers (will cycle through) default is `s`, i.e., a square mec: seq marker edge colors linestyles: seq sequence of linestyles (will cycle through) linewidths: seq sequence of linewidths (will cycle through) fig: plt.Figure figure to add a legend (default: `plt.gcf()`) kwargs: dict any other keyword will go to :func:`plt.legend` Returns ------- lgd: plt.Legend instance the newly created legend """ from matplotlib.lines import Line2D from itertools import cycle if fig is None: fig = plt.gcf() defaults = dict(numpoints=1, frameon=False) defaults.update(kwargs) if not hasattr(mec, '__iter__'): mec = [mec] if not hasattr(linewidths, '__iter__'): linewidths = [linewidths] lines = [] for lbl, color, m, ls, me, lw in zip(labels, colors, cycle(markers), cycle(linestyles), cycle(mec), cycle(linewidths)): l = Line2D(range(2), range(2), marker=m, mec=me, linestyle=ls, color=color, lw=lw) lines.append(l) lgd = fig.legend(lines, labels, **defaults) plt.draw_if_interactive() return lgd
def legend(*args, **kwargs): """ Overwrites the pylab legend function. It adds another location identfier 'outer right' which locates the legend on the right side of the plot The args and kwargs are forwarded to the pylab legend function from http://www.mail-archive.com/[email protected]/msg04256.html """ import pylab if kwargs.has_key("loc"): loc = kwargs["loc"] loc = loc.split() if loc[0] == "outer": # make a legend with out the location # remove the location setting from the kwargs kwargs.pop("loc") leg = pylab.legend(loc=(0, 0), *args, **kwargs) frame = leg.get_frame() currentAxes = pylab.gca() currentAxesPos = numpy.array(currentAxes.get_position()).flatten() # scale plot by the part which is taken by the legend plotScaling = frame.get_width() / currentAxesPos[2] if loc[1] == "right": # scale the plot currentAxes.set_position( ( currentAxesPos[0], currentAxesPos[1] - 0.05, currentAxesPos[2] * (1 - plotScaling), currentAxesPos[3] - 0.05, ) ) # set x and y coordinates of legend # leg._loc = (1 + leg.axespad, 1 - frame.get_height()) leg._loc = (1 + leg.axespad, 0) # doesn't work # if loc[1] == 'left': # # scale the plot # currentAxes.set_position((currentAxesPos[0] +frame.get_width(), # currentAxesPos[1], # currentAxesPos[2] *(1-plotScaling), # currentAxesPos[3])) # # set x and y coordinates of legend # leg._loc = (1 -.05 - leg.axespad - frame.get_width(), 1 -frame.get_height()) pylab.draw_if_interactive() return leg return pylab.legend(*args, **kwargs)
def plot_from_url(url, ax=None, suffix='.png', plotflag=True): if ax is None: ax = pylab.gca() fname = tempfile.mktemp(suffix) im = urllib.urlretrieve(url, fname) d = pylab.imread(fname) if plotflag: ax.imshow(d) ax.set_axis_off() pylab.draw_if_interactive() return d
def plot_raster(self, show_stems=True, show_axes=True, show_y_ticks=True, marker='.', markersize=5, fig_title='', file_name=''): """ This function is based on the homework 2 solution given by Lev Givon. """ p.clf() p.gcf().canvas.set_window_title(fig_title) ax = p.gca() ax.axis([0, self.dur, -0.5, self.neu_num - 0.5]) if show_y_ticks: neu_name = [[] for i in xrange(self.neu_num)] for name, idx in self.neu_name.items(): neu_name[idx] = name p.yticks(xrange(self.neu_num), tuple(neu_name), fontsize=4) else: for tick_label in ax.get_yticklabels(): tick_label.set_visible(False) for y in xrange(self.neu_num): spk_time = self.spk_list[:, y].nonzero()[0] * self.dt if show_axes: p.axhline(y, 0, 1, color='b', hold=True) p.plot(spk_time, y * np.ones(len(spk_time)), marker, hold=True, color=(1 - 1. / self.neu_num * y, 0.5, 1. / self.neu_num * y), markersize=markersize, scalex=False, scaley=False) if show_stems: for t in spk_time: ax.add_line( mp.lines.Line2D([t, t], [-0.5, y], color='r', linestyle=':')) ax.xaxis.set_major_locator( mp.ticker.MultipleLocator(10.0**np.ceil(np.log10(self.dur / 10)))) p.xlabel('time, sec') #p.ylabel('Neuron') if fig_title: p.title(fig_title) p.draw_if_interactive() if file_name: p.savefig(file_name)
def wireframe(X, Y, Z, *args): # For some reason, this is necessary to prevent clf() from raising # an exception: try: p.clf() except ValueError: p.clf() ax = p.gca(projection='3d') ax.plot_wireframe(X, Y, Z, *args) p.draw_if_interactive()
def _zoom_on_click(self, ev): try: ax = ev.inaxes lon, lat = ax.get_lonlat(ev.xdata, ev.ydata) if np.isnan(lon) or np.isnan(lat): raise ValueError('invalid position') val = ax.get_value(ev.xdata, ev.ydata) self.lastval = val self._move_zoom_center(lon, lat) self.draw_gnom(lon, lat) except Exception, s: self._move_zoom_center(0, 0, False) pylab.draw_if_interactive()
def _zoom_on_click(self, ev): try: ax = ev.inaxes lon,lat = ax.get_lonlat(ev.xdata,ev.ydata) if npy.isnan(lon) or npy.isnan(lat): raise ValueError('invalid position') val = ax.get_value(ev.xdata,ev.ydata) self.lastval = val self._move_zoom_center(lon,lat) self.draw_gnom(lon,lat) except Exception,s: self._move_zoom_center(0,0,False) pylab.draw_if_interactive()
def legend(*args, **kwargs): """ Overwrites the pylab legend function. It adds another location identfier 'outer right' which locates the legend on the right side of the plot The args and kwargs are forwarded to the pylab legend function from http://www.mail-archive.com/[email protected]/msg04256.html """ import pylab if kwargs.has_key('loc'): loc = kwargs['loc'] loc = loc.split() if loc[0] == 'outer': # make a legend with out the location # remove the location setting from the kwargs kwargs.pop('loc') leg = pylab.legend(loc=(0, 0), *args, **kwargs) frame = leg.get_frame() currentAxes = pylab.gca() currentAxesPos = numpy.array(currentAxes.get_position()).flatten() # scale plot by the part which is taken by the legend plotScaling = frame.get_width() / currentAxesPos[2] if loc[1] == 'right': # scale the plot currentAxes.set_position( (currentAxesPos[0], currentAxesPos[1] - 0.05, currentAxesPos[2] * (1 - plotScaling), currentAxesPos[3] - 0.05)) # set x and y coordinates of legend #leg._loc = (1 + leg.axespad, 1 - frame.get_height()) leg._loc = (1 + leg.axespad, 0) # doesn't work #if loc[1] == 'left': # # scale the plot # currentAxes.set_position((currentAxesPos[0] +frame.get_width(), # currentAxesPos[1], # currentAxesPos[2] *(1-plotScaling), # currentAxesPos[3])) # # set x and y coordinates of legend # leg._loc = (1 -.05 - leg.axespad - frame.get_width(), 1 -frame.get_height()) pylab.draw_if_interactive() return leg return pylab.legend(*args, **kwargs)
def format_dateaxis(subplot, freq, index): """ Pretty-formats the date axis (x-axis). Major and minor ticks are automatically set for the frequency of the current underlying series. As the dynamic mode is activated by default, changing the limits of the x axis will intelligently change the positions of the ticks. """ from pandas import PeriodIndex, TimedeltaIndex # handle index specific formatting # Note: DatetimeIndex does not use this # interface. DatetimeIndex uses matplotlib.date directly if isinstance(index, PeriodIndex): majlocator = TimeSeries_DateLocator(freq, dynamic_mode=True, minor_locator=False, plot_obj=subplot) minlocator = TimeSeries_DateLocator(freq, dynamic_mode=True, minor_locator=True, plot_obj=subplot) subplot.xaxis.set_major_locator(majlocator) subplot.xaxis.set_minor_locator(minlocator) majformatter = TimeSeries_DateFormatter(freq, dynamic_mode=True, minor_locator=False, plot_obj=subplot) minformatter = TimeSeries_DateFormatter(freq, dynamic_mode=True, minor_locator=True, plot_obj=subplot) subplot.xaxis.set_major_formatter(majformatter) subplot.xaxis.set_minor_formatter(minformatter) # x and y coord info subplot.format_coord = lambda t, y: ( "t = {0} y = {1:8f}".format( Period(ordinal=int(t), freq=freq), y)) elif isinstance(index, TimedeltaIndex): subplot.xaxis.set_major_formatter( TimeSeries_TimedeltaFormatter()) else: raise TypeError('index type not supported') pylab.draw_if_interactive()
def fill_zea(self, index, fignum=12, axes=None, show_kw=None, **kwargs): """ index: integer, or a SkyDir the HP12 index if integer figmun: integer used if axes is None show_kw : dict override imshow keywords kwargs size pixelsize galactic """ if axes is None: plt.close(fignum) fig = plt.figure(fignum, figsize=(6, 6)) axes = fig.gca() if type(index) == types.IntType: sdir = Band(12).dir(index) title = 'HP12_%4d' % index else: sdir = index title = 'l = %.1f, b=%.1f' % (sdir.l(), sdir.b()) title = kwargs.pop('title', title) kw = self.ZEA_kw kw.update(kwargs) zea = image.ZEA(sdir, **kw) zea.grid() zea.fill(self.get_pyskyfun()) zea.imshow(**(show_kw if show_kw is not None else self.imshow_kw)) zea.colorbar() if title is not None: axes.set_title(title) if self.sources is not None: count = 0 for s in self.sources: sdir = SkyDir(s.ra, s.dec) if not zea.inside(sdir): continue count += 1 inside = self.band.index(sdir) == index zea.plot_source(s.name, sdir, symbol='*' if inside else 'd', markersize=14 if inside else 8, color='w') print 'found %d sources to plot' % count if self.map_path is not None: fout = os.path.join(self.map_path, hpname(index) + '.png') plt.savefig(fout, bbox_inches='tight') print 'saved figure to %s' % fout plt.draw_if_interactive() return zea
def twiny(ax=None): """ Make a second axes overlay ax (or the current axes if ax is None) sharing the xaxis. The ticks for ax2 will be placed on the right, and the ax2 instance is returned. See examples/two_scales.py """ if ax is None: ax = py.gca() ax2 = py.gcf().add_axes(ax.get_position(), sharey=ax, frameon=False) ax2.xaxis.tick_top() ax2.xaxis.set_label_position('top') ax.xaxis.tick_bottom() py.draw_if_interactive() return ax2
def adjust_axis(axn=None, c='r', step=0, side='x', position=True): ''' adjusts position and color of x or y ticks axn = selected axis c = new color for ticks step = layer of offset side = x or y position = True or False True = top or right ''' if axn is None: axn = pylab.gca() pylab.axes(axn) #locator = ticker.AutoLocator() #locator.autoscale() #eval('axn.' + side + 'axis.set_major_locator(locator)') #formatter = ticker.FixedFormatter() #reval('axn.' + side + 'axis.set_major_formatter(formatter)') choose_axes(axn, position=position, side=side) yt = pylab.getp(axn, side + 'ticklabels') ticklabels = pylab.getp(axn, side + 'ticklabels') pylab.setp(ticklabels, 'color', c) pylab.setp(eval('axn.' + side + 'axis.label'), color=c) yt = pylab.getp(axn, side + 'ticklines') pylab.setp(yt, color=c) if step > 0: dpad = 0 dlen = 25 * step if side == 'x' and position: drot = 90 ddir = 1 elif side == 'x': drot = -90 ddir = -1 elif side == 'y' and position: drot = 0 ddir = 1 else: ddir = -1 drot = 180 dpad = -5 eval('axn.' + side + 'axis.get_major_ticks()') ticklabels = pylab.getp(axn, side + 'ticklabels') pylab.setp(ticklabels, dashdirection=ddir, dashlength=dlen, dashrotation=drot, dashpad=dpad) eval('pylab.setp(axn.get_' + side + 'gridlines(),c=\'' + c + '\')') pylab.draw_if_interactive()
def twiny(ay=None): """ Make a second axes overlay ay (or the current axes if ay is None) sharing the yaxis. The ticks for ay2 will be placed on the top, and the ay2 instance is returned. See examples/two_scales.py """ if ay is None: ay = gca() ay2 = gcf().add_axes(ay.get_position(), sharey=ay, frameon=False) ay2.xaxis.tick_top() ay2.xaxis.set_label_position('top') ay.xaxis.tick_bottom() draw_if_interactive() return ay2
def plot_encoded(t, u, s, fig_title='', file_name=''): """ Plot a time-encoded signal. Parameters ---------- t : ndarray of floats Times (in s) at which the original signal was sampled. u : ndarray of floats Signal samples. s : ndarray of floats Intervals between encoded signal spikes. fig_title : string Plot title. file_name : string File in which to save the plot. Notes ----- The spike times (i.e., the cumulative sum of the interspike intervals) must all occur within the interval `t-min(t)`. """ dt = t[1] - t[0] cs = np.cumsum(s) if cs[-1] >= max(t) - min(t): raise ValueError('some spike times occur outside of signal' 's support') p.clf() p.gcf().canvas.set_window_title(fig_title) p.axes([0.125, 0.3, 0.775, 0.6]) p.vlines(cs + min(t), np.zeros(len(cs)), u[np.asarray(cs / dt, int)], 'b') p.hlines(0, 0, max(t), 'r') p.plot(t, u, hold=True) p.xlabel('t (s)') p.ylabel('u(t)') p.title(fig_title) p.gca().set_xlim(min(t), max(t)) a = p.axes([0.125, 0.1, 0.775, 0.1]) p.plot(cs + min(t), np.zeros(len(s)), 'ro') a.set_yticklabels([]) p.xlabel('%d spikes' % len(s)) p.gca().set_xlim(min(t), max(t)) p.draw_if_interactive() if file_name: p.savefig(file_name)
def _redraw(self, db, tofile=0, eta=None): """ redraw the updated grid interactively """ import pylab as p if len(db) <= 3 or not self.plotflag: return begin_level = round(max(map(lambda (x): x[2], db))) - 3 step_size = 0.25 nContours = 25 suffix = "" if eta is not None: suffix = " (ETA: %5.2f min)" % eta def cmp(x, y): if x[0] < y[0]: return -1 if x[0] > y[0]: return 1 if x[1] > y[1]: return -1 if x[1] < y[1]: return 1 return 0 db.sort(cmp) dbarr = p.asarray(db) # reconstruct grid: array is ordered along first and second dimension x = dbarr[:, 0] dimy = len(x[x == x[0]]) dimx = x.size / dimy print "plotting: ", dimx, dimy x = x.reshape(dimx, dimy) y = dbarr[:, 1] y = y.reshape(dimx, dimy) z = dbarr[:, 2].reshape(dimx, dimy) # plot using manual double buffer p.ioff() p.clf() p.contourf(x, y, z, nContours) p.hsv() p.colorbar() p.xlim(self.usermin[0], self.usermax[0]) p.ylim(self.usermin[1], self.usermax[1]) p.xlabel(r"$\rm{log}_2(C)$") p.ylabel(r"$\rm{log}_2(\gamma)$") p.ion() p.draw_if_interactive()
def setMargins(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None): """ Tune the subplot layout via the meanings (and suggested defaults) are:: left = 0.125 # the left side of the subplots of the figure right = 0.9 # the right side of the subplots of the figure bottom = 0.1 # the bottom of the subplots of the figure top = 0.9 # the top of the subplots of the figure wspace = 0.2 # the amount of width reserved for blank space between subplots hspace = 0.2 # the amount of height reserved for white space between subplots The actual defaults are controlled by the rc file """ plt.subplots_adjust(left, bottom, right, top, wspace, hspace) plt.draw_if_interactive()
def plot_encoded(t, u, s, fig_title='', file_name=''): """ Plot a time-encoded signal. Parameters ---------- t : ndarray of floats Times (in s) at which the original signal was sampled. u : ndarray of floats Signal samples. s : ndarray of floats Intervals between encoded signal spikes. fig_title : string Plot title. file_name : string File in which to save the plot. Notes ----- The spike times (i.e., the cumulative sum of the interspike intervals) must all occur within the interval `t-min(t)`. """ dt = t[1]-t[0] cs = np.cumsum(s) if cs[-1] >= max(t)-min(t): raise ValueError('some spike times occur outside of signal''s support') p.clf() p.gcf().canvas.set_window_title(fig_title) p.axes([0.125, 0.3, 0.775, 0.6]) p.vlines(cs+min(t), np.zeros(len(cs)), u[np.asarray(cs/dt, int)], 'b') p.hlines(0, 0, max(t), 'r') p.plot(t, u, hold=True) p.xlabel('t (s)') p.ylabel('u(t)') p.title(fig_title) p.gca().set_xlim(min(t), max(t)) a = p.axes([0.125, 0.1, 0.775, 0.1]) p.plot(cs+min(t), np.zeros(len(s)), 'ro') a.set_yticklabels([]) p.xlabel('%d spikes' % len(s)) p.gca().set_xlim(min(t), max(t)) p.draw_if_interactive() if file_name: p.savefig(file_name)
def add_overlay(self, img, threshold=1e-6, colorbar=False, **kwargs): """ Plot a 3D map in all the views. Parameters ----------- img: Niimg-like object See http://nilearn.github.io/building_blocks/manipulating_mr_images.html#niimg. If it is a masked array, only the non-masked part will be plotted. threshold : a number, None If None is given, the maps are not thresholded. If a number is given, it is used to threshold the maps: values below the threshold (in absolute value) are plotted as transparent. colorbar: boolean, optional If True, display a colorbar on the right of the plots. kwargs: Extra keyword arguments are passed to imshow. """ if colorbar and self._colorbar: raise ValueError("This figure already has an overlay with a " "colorbar.") else: self._colorbar = colorbar img = _utils.check_niimg(img, ensure_3d=True) if threshold is not None: data = img.get_data() if threshold == 0: data = np.ma.masked_equal(data, 0, copy=False) else: data = np.ma.masked_inside(data, -threshold, threshold, copy=False) img = nibabel.Nifti1Image(data, img.get_affine()) # To make sure that add_overlay has a consistant default behavior # with plot_stat_map kwargs.setdefault('interpolation', 'nearest') ims = self._map_show(img, type='imshow', **kwargs) if colorbar: self._colorbar_show(ims[0], threshold) pl.draw_if_interactive()
def imshow2(m1,m2,labels=(None,None)): """Display two images side by side. Returns the created figure instance.""" fig = P.figure() ax1 = [0.025,0.1,0.45,0.775] ax2 = [0.525,0.1,0.45,0.775] for m,ax_coord,label in [(m1,ax1,labels[0]),(m2,ax2,labels[1])]: ax = fig.add_axes(ax_coord) ax.imshow(m,cmap=P.cm.gray) if label: ax.set_xlabel(label) P.xticks([],[]) P.yticks([],[]) P.draw_if_interactive() return fig
def plot_raster(ts_list, plot_stems=True, plot_axes=True, marker='.', markersize=5, fig_title='', file_name=''): """ Plot several time sequences as a raster. Parameters ---------- ts_list : list of ndarrays Time sequences to plot. plot_stems : bool Show stems for all events. plot_axes : bool Show horizontal axes for all sequences. marker : char Marker symbol. markersize : int Marker symbol size. fig_title : string Plot title. file_name : string File in which to save the plot. """ M = len(ts_list) p.clf() p.gcf().canvas.set_window_title(fig_title) max_ts = max([max(ts) if len(ts) > 1 else 0 for ts in ts_list]) ax = p.gca() ax.axis([0, max_ts, -0.5, M-0.5]) p.yticks(xrange(M)) for (ts,y) in zip(ts_list,xrange(M)): if plot_axes: p.axhline(y, 0, 1, color='b', hold=True) p.plot(ts, y*np.ones(len(ts)), marker+'b', hold=True, markersize=markersize, scalex=False, scaley=False) if plot_stems: for t in ts: ax.add_line(mp.lines.Line2D([t,t], [-0.5, y], color='r', linestyle=':')) ax.xaxis.set_major_locator(mp.ticker.MultipleLocator(10.0**np.ceil(np.log10(max_ts/10)))) p.xlabel('t (s)') p.title(fig_title) p.draw_if_interactive() if file_name: p.savefig(file_name)
def add_overlay(self, img, threshold=1e-6, colorbar=False, **kwargs): """ Plot a 3D map in all the views. Parameters ----------- img: Niimg-like object See http://nilearn.github.io/building_blocks/manipulating_mr_images.html#niimg. The nifti-image-like. If it is a masked array, only the non-masked part will be plotted. threshold : a number, None If None is given, the maps are not thresholded. If a number is given, it is used to threshold the maps: values below the threshold (in absolute value) are plotted as transparent. colorbar: boolean, optional If True, display a colorbar on the right of the plots. kwargs: Extra keyword arguments are passed to imshow. """ if colorbar and self._colorbar: raise ValueError("This figure already has an overlay with a " "colorbar.") else: self._colorbar = colorbar img = _utils.check_niimg(img, ensure_3d=True) if threshold is not None: data = img.get_data() if threshold == 0: data = np.ma.masked_equal(data, 0, copy=False) else: data = np.ma.masked_inside(data, -threshold, threshold, copy=False) img = nibabel.Nifti1Image(data, img.get_affine()) # To make sure that add_overlay has a consistant default behavior # with plot_stat_map kwargs.setdefault('interpolation', 'nearest') ims = self._map_show(img, type='imshow', **kwargs) if colorbar: self._colorbar_show(ims[0], threshold) pl.draw_if_interactive()
def shift_axis(which, delta, where='outward', ax=None): ax = ax or plt.gca() if type(which) == str: _w = [which] else: _w = which scales = (ax.xaxis.get_scale(), ax.yaxis.get_scale()) lbls = (ax.xaxis.get_label(), ax.yaxis.get_label()) for wk in _w: ax.spines[wk].set_position((where, delta)) ax.xaxis.set_scale(scales[0]) ax.yaxis.set_scale(scales[1]) ax.xaxis.set_label(lbls[0]) ax.yaxis.set_label(lbls[1]) plt.draw_if_interactive()
def add_contours(self, img, **kwargs): """ Contour a 3D map in all the views. Parameters ----------- img: Niimg-like object See http://nilearn.github.io/building_blocks/manipulating_mr_images.html#niimg. The Nifti-Image like object to plot kwargs: Extra keyword arguments are passed to contour, see the documentation of pylab.contour Useful, arguments are typical "levels", which is a list of values to use for plotting a contour, and "colors", which is one color or a list of colors for these contours. """ self._map_show(img, type='contour', **kwargs) pl.draw_if_interactive()
def setNmajors(xval=None, yval=None, ax=None, mode='auto', **kwargs): """ setNmajors - set major tick number see figure.MaxNLocator for kwargs """ if ax is None: ax = plt.gca() if (mode == 'fixed'): if xval is not None: ax.xaxis.set_major_locator(MaxNLocator(xval, **kwargs)) if yval is not None: ax.yaxis.set_major_locator(MaxNLocator(yval, **kwargs)) elif (mode == 'auto'): if xval is not None: ax.xaxis.set_major_locator(AutoLocator(xval, **kwargs)) if yval is not None: ax.yaxis.set_major_locator(AutoLocator(yval, **kwargs)) plt.draw_if_interactive()
def _redraw(self, db, tofile=0, eta=None): """ redraw the updated grid interactively """ import pylab as p if len(db) <= 3 or not self.plotflag: return begin_level = round(max(map(lambda (x): x[2], db))) - 3 step_size = 0.25 nContours = 25 suffix = '' if eta is not None: suffix = " (ETA: %5.2f min)" % eta def cmp(x, y): if x[0] < y[0]: return -1 if x[0] > y[0]: return 1 if x[1] > y[1]: return -1 if x[1] < y[1]: return 1 return 0 db.sort(cmp) dbarr = p.asarray(db) # reconstruct grid: array is ordered along first and second dimension x = dbarr[:, 0] dimy = len(x[x == x[0]]) dimx = x.size / dimy print 'plotting: ', dimx, dimy x = x.reshape(dimx, dimy) y = dbarr[:, 1] y = y.reshape(dimx, dimy) z = dbarr[:, 2].reshape(dimx, dimy) # plot using manual double buffer p.ioff() p.clf() p.contourf(x, y, z, nContours) p.hsv() p.colorbar() p.xlim(self.usermin[0], self.usermax[0]) p.ylim(self.usermin[1], self.usermax[1]) p.xlabel(r'$\rm{log}_2(C)$') p.ylabel(r'$\rm{log}_2(\gamma)$') p.ion() p.draw_if_interactive()
def legend(*args, **kwargs): r""" Overwrites the pylab legend function. It adds another location identfier 'outer right' which locates the legend on the right side of the plot The args and kwargs are forwarded to the pylab legend function """ if kwargs.has_key('loc'): loc = kwargs['loc'] if loc == "outer right": kwargs.pop('loc') axes = pylab.gca() bbox = axes.get_position().get_points() x = bbox[0][0] y = bbox[0][1] w = bbox[1][0] h = bbox[1][1] axes.set_position([x,y,0.5,0.5]) #legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) leg = pylab.legend(loc=(0,0), *args, **kwargs) frame = leg.get_frame() lw = frame.get_width() lh = frame.get_height() scale = lw / (1.0*w) leg._loc = (x+w,y+h-lh) axes.set_position([x,y,0.7*((w)/scale),0.9*h]) pylab.draw_if_interactive() return leg return pylab.legend(*args, **kwargs)
def legend(*args, **kwargs): """Overwrites the pylab legend function. It adds another location identfier 'outer right' which locates the legend on the right side of the plot The args and kwargs are forwarded to the pylab legend function """ if kwargs.has_key('loc'): loc = kwargs['loc'] if loc == "outer right": kwargs.pop('loc') axes = pylab.gca() bbox = axes.get_position().get_points() x = bbox[0][0] y = bbox[0][1] w = bbox[1][0] h = bbox[1][1] axes.set_position([x, y, 0.5, 0.5]) #legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) leg = pylab.legend(loc=(0, 0), *args, **kwargs) frame = leg.get_frame() lw = frame.get_width() lh = frame.get_height() scale = lw / (1.0 * w) leg._loc = (x + w, y + h - lh) axes.set_position([x, y, 0.7 * ((w) / scale), 0.9 * h]) pylab.draw_if_interactive() return leg return pylab.legend(*args, **kwargs)
def fill_zea(self, index, fignum=12, axes=None, **kwargs): """ sources is a recarray with name, ra, dec """ if axes is None: plt.close(fignum) fig = plt.figure(fignum, figsize=(6, 6)) axes = fig.gca() size = kwargs.pop('size', 10) pixelsize = kwargs.pop('pixelsize', 0.1) title = kwargs.pop('title', hpname(index)) label = kwargs.pop('label', '') zea = image.ZEA(self.band.dir(index), size=size, pixelsize=pixelsize, **self.ZEA_kw) zea.grid() zea.fill(self.get_pyskyfun()) imshow_kw = self.imshow_kw # imshow_kw.update(kwargs) zea.imshow(**imshow_kw) zea.colorbar(label=label) axes.set_title(title) if self.sources is not None: count = 0 for s in self.sources: sdir = s.skydir if not zea.inside(sdir): continue count += 1 inside = self.band.index(sdir) == index zea.plot_source(s.name, sdir, symbol='*' if inside else 'd', markersize=14 if inside else 8, color='w') print 'found %d sources to plot' % count if self.map_path is not None: fout = os.path.join(self.map_path, hpname(index) + '.png') plt.savefig(fout) print 'saved figure to %s' % fout plt.draw_if_interactive()
def legend(*args, **kwargs): """Overwrites the pylab legend function. It adds another location identfier 'outer right' which locates the legend on the right side of the plot The args and kwargs are forwarded to the pylab legend function """ if "loc" in kwargs: loc = kwargs["loc"] if loc == "outer right": kwargs.pop("loc") axes = pylab.gca() bbox = axes.get_position().get_points() x = bbox[0][0] y = bbox[0][1] w = bbox[1][0] h = bbox[1][1] axes.set_position([x, y, 0.5, 0.5]) leg = pylab.legend(loc=(0, 0), *args, **kwargs) frame = leg.get_frame() lw = frame.get_width() lh = frame.get_height() scale = lw / (1.0 * w) leg._loc = (x + w, y + h - lh) axes.set_position([x, y, 0.7 * (w / scale), 0.9 * h]) pylab.draw_if_interactive() return leg return pylab.legend(*args, **kwargs)
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 hide_axis(where, ax=None): ax = ax or plt.gca() if type(where) == str: _w = [where] else: _w = where [sk.set_color('None') for k, sk in ax.spines.items() if k in _w ] if 'top' in _w and 'bottom' in _w: ax.xaxis.set_ticks_position('none') elif 'top' in _w: ax.xaxis.set_ticks_position('bottom') elif 'bottom' in _w: ax.xaxis.set_ticks_position('top') if 'left' in _w and 'right' in _w: ax.yaxis.set_ticks_position('none') elif 'left' in _w: ax.yaxis.set_ticks_position('right') elif 'right' in _w: ax.yaxis.set_ticks_position('left') plt.draw_if_interactive()
def show_image(self,number,fignum=None,interpolation=None): """Show a single image, by its index. Inputs: - number: index (0-offset) of the image to display. Optional inputs: - fignum(None): a matplotlib figure number, to reuse for display. If not given, a new figure is automatically created. - interpolation: interpolation mode for display. If not given, the instance .interpolation attribute is used. Outputs: The number of the created figure window, so it can be reused.""" if interpolation is None: interpolation = self.interpolation image = self.images[number] name = self.names[number] if fignum is None: # make a new figure from scratch fig = P.matshow(image,cmap=P.cm.gray,interpolation=interpolation) else: # draw into an existing figure directly fig = P.figure(fignum) ax_im = fig.axes[0].images[0] ax_im.set_data(image) P.draw() P.title('Image [%d]: %s - (%d/%d)' % (number,name,number+1,self.num_images)) P.draw_if_interactive() return fig.number
def plotfile(fname, cols=(0,), plotfuncs=None, facecolor=None, width=8, height=6, xLabel=None, showXLabel=False, yLabel=None, showYLabel=False, showLegend=False, separateCharts=False, comments='#', skiprows=0, checkrows=5, delimiter=',', names=None, subplots=True, newfig=True, **kwargs): """ Plot the data in *fname* *cols* is a sequence of column identifiers to plot. An identifier is either an int or a string. If it is an int, it indicates the column number. If it is a string, it indicates the column header. matplotlib will make column headers lower case, replace spaces with underscores, and remove all illegal characters; so ``'Adj Close*'`` will have name ``'adj_close'``. - If len(*cols*) == 1, only that column will be plotted on the *y* axis. - If len(*cols*) > 1, the first element will be an identifier for data for the *x* axis and the remaining elements will be the column indexes for multiple subplots if *subplots* is *True* (the default), or for lines in a single subplot if *subplots* is *False*. *plotfuncs*, if not *None*, is a dictionary mapping identifier to an :class:`~matplotlib.axes.Axes` plotting function as a string. Default is 'plot', other choices are 'semilogy', 'fill', 'bar', etc. You must use the same type of identifier in the *cols* vector as you use in the *plotfuncs* dictionary, eg., integer column numbers in both or column names in both. If *subplots* is *False*, then including any function such as 'semilogy' that changes the axis scaling will set the scaling for all columns. *comments*, *skiprows*, *checkrows*, *delimiter*, and *names* are all passed on to :func:`matplotlib.pylab.csv2rec` to load the data into a record array. If *newfig* is *True*, the plot always will be made in a new figure; if *False*, it will be made in the current figure if one exists, else in a new figure. kwargs are passed on to plotting functions. Example usage:: # plot the 2nd and 4th column against the 1st in two subplots plotfile(fname, (0,1,3)) # plot using column names; specify an alternate plot type for volume plotfile(fname, ('date', 'volume', 'adj_close'), plotfuncs={'volume': 'semilogy'}) Note: plotfile is intended as a convenience for quickly plotting data from flat files; it is not intended as an alternative interface to general plotting with pyplot or matplotlib. """ if newfig: # fig = figure(figsize=(width, height), dpi=100) # if facecolor is None: # fig.patch.set_facecolor('w'); # fig.patch.set_alpha(0); # else: # fig.patch.set_facecolor(facecolor) fig = figure() else: fig = gcf() if len(cols)<1: raise ValueError('must have at least one column of data') if plotfuncs is None: plotfuncs = dict() r = mlab.csv2rec(fname, comments=comments, skiprows=skiprows, checkrows=checkrows, delimiter=delimiter, names=names) delete = set("""~!@#$%^&*()-=+~\|]}[{';: /?.>,<""") delete.add('"') def getname_val(identifier): 'return the name and column data for identifier' if is_string_like(identifier): print "Identifier " + identifier + " is a string" col_name = identifier.strip().lower().replace(' ', '_') col_name = ''.join([c for c in col_name if c not in delete]) return identifier, r[col_name] elif is_numlike(identifier): name = r.dtype.names[int(identifier)] return name, r[name] else: raise TypeError('identifier must be a string or integer') xname, x = getname_val(cols[0]) ynamelist = [] if len(cols)==1: ax1 = fig.add_subplot(1,1,1) funcname = plotfuncs.get(cols[0], 'plot') func = getattr(ax1, funcname) func(x, **kwargs) if showYLabel: if not yLabel == None: if verbose: print 'Setting y label to supplied value ' + yLabel ax1.set_ylabel(yLabel) else: if verbose: print 'Setting y label to derived value ' + xname ax1.set_ylabel(xname) else: N = len(cols) for i in range(1,N): if subplots: if i==1: ax = ax1 = fig.add_subplot(N-1,1,i) else: ax = fig.add_subplot(N-1,1,i, sharex=ax1) elif i==1: ax = fig.add_subplot(1,1,1) ax.grid(True) yname, y = getname_val(cols[i]) ynamelist.append(yname) funcname = plotfuncs.get(cols[i], 'plot') func = getattr(ax, funcname) func(x, y, **kwargs) if subplots: # if not yLabel == None: # if verbose: # print 'Setting y label to supplied value ' + yLabel # ax.set_ylabel(yLabel) # elif subplots: if verbose: print 'Setting y label to derived value ' + yname ax.set_ylabel(yname) else: if showYLabel: if not yLabel: if verbose: print 'Setting y label to derived value ' + yname ax.set_ylabel(yname) else: if verbose: print 'Setting y label to supplied value ' + yLabel ax.set_ylabel(yLabel) if showXLabel: if ax.is_last_row(): if not xLabel == None: if verbose: print 'Setting x label to supplied value ' + xLabel ax.set_xlabel(xLabel) else: if verbose: print 'Setting x label to ' + xname ax.set_xlabel(xname) else: if verbose: print 'Skipping x label until end' ax.set_xlabel('') if showLegend: # and not subplots: if verbose: print 'Creating legend as requested' ax.legend(ynamelist, loc='best') if xname=='date': fig.autofmt_xdate() draw_if_interactive()
def multi_plot(plist,plottype='whisker',Nequil=Nequil_default,funcname='occupancy_mean_correl',**kwargs): """Display a collection of functions. multi_plot(plist,plottype='whisker',Nequil=10000,funcname='occupancy_mean_correl',**kwargs) The function is obtained from a method call on the objects in plist. The assumption is that these are functions of Ntotal (if not, set Nequil=0; Nequil is added to x). Each object is a different realization, e.g. multiple MCMC runs. plottype 'whisker' (whisker plot), 'standard' (average and standard deviations) Nequil correction, added to x funcname string; a method of the objects in plist that does EXACTLY the following: x,y = obj.funcname() where x and y are numpy arrays of equal length **kwargs color, boxcolor, mediancolor, capsize """ import pylab plottypes = ('whisker','standard') # sanity checks if plottype not in plottypes: raise ValueError("Only plottypes from %(plottypes)r, not %(plottype)s." % locals()) try: plist[0].__getattribute__(funcname)() # How do I handle old-style classes? Check __getattr__? except: raise ValueError("funcname='%(funcname)r' has the wrong signature or is not a method " "of the objects in plist." % locals()) def xy_from(obj): return obj.__getattribute__(funcname)() def x_from(obj): return xy_from(obj)[0] def y_from(obj): return xy_from(obj)[1] kwargs.setdefault('color','b') # main color kwargs.setdefault('capsize',0) x = x_from(plist[0]) + Nequil all_y = numpy.array([y_from(p) for p in plist]) ymean = all_y.mean(axis=0) yerr = all_y.std(axis=0) ax = pylab.axes(frameon=False) if plottype == 'standard': lines = pylab.errorbar(x,ymean,yerr=yerr,fmt='o',linestyle='-',**kwargs) for p in plist: px,py = xy_from(p) px += Nequil components = pylab.semilogx(px,py,'o',color=kwargs['color'],ms=3) elif plottype == 'whisker': # widths that look the same in a log plot def logwidth(x,delta): """Return linear widths at x that, logarithmically scaled, appear to be delta wide.""" q = numpy.exp(delta) return x * (1 - q)/(1 + q) kwargs.setdefault('mediancolor','k') # for median in whiskerplot kwargs.setdefault('boxcolor','darkgray') pylab.semilogx(x,ymean,'o-',color=kwargs['color'],ms=3) components = pylab.boxplot(all_y,positions=x, widths=logwidth(x,kwargs.setdefault('widths',0.15))) ax = pylab.gca() ax.set_xscale('log') ax.set_yscale('linear') # must modify components for customisation for l in components['boxes']: l.set_color(kwargs['boxcolor']) for l in components['whiskers']: l.set_color(kwargs['color']) l.set_linestyle('-') for l in components['caps']: l.set_color(kwargs['color']) for l in components['medians']: l.set_color(kwargs['mediancolor']) l.set_linewidth(3.0) for l in components['fliers']: l.set_color(kwargs['color']) pylab.draw_if_interactive() pylab.xlabel('total MCMC steps') pylab.ylabel('correlation coefficient with MD') pylab.title('convergence of occupancy correlation with MD')
def violinplot(data, ax=None, labels=None, positions=None, side='both', show_boxplot=True, plot_opts={}): """Make a violin plot of each dataset in the `data` sequence. A violin plot is a boxplot combined with a kernel density estimate of the probability density function per point. Parameters ---------- data : sequence of ndarrays Data arrays, one array per value in `positions`. ax : Matplotlib AxesSubplot instance, optional If given, this subplot is used to plot in instead of a new figure being created. labels : list of str, optional Tick labels for the horizontal axis. If not given, integers ``1..len(data)`` are used. positions : array_like, optional Position array, used as the horizontal axis of the plot. If not given, spacing of the violins will be equidistant. side : {'both', 'left', 'right'}, optional How to plot the violin. Default is 'both'. The 'left', 'right' options can be used to create asymmetric violin plots. show_boxplot : bool, optional Whether or not to show normal box plots on top of the violins. Default is True. plot_opts : dict, optional A dictionary with plotting options. Any of the following can be provided, if not present in `plot_opts` the defaults will be used:: - 'violin_fc', MPL color. Fill color for violins. Default is 'y'. - 'violin_ec', MPL color. Edge color for violins. Default is 'k'. - 'violin_lw', scalar. Edge linewidth for violins. Default is 1. - 'violin_alpha', float. Transparancy of violins. Default is 0.5. - 'cutoff', bool. If True, limit violin range to data range. Default is False. - 'cutoff_val', scalar. Where to cut off violins if `cutoff` is True. Default is 1.5 standard deviations. - 'cutoff_type', {'std', 'abs'}. Whether cutoff value is absolute, or in standard deviations. Default is 'std'. - 'violin_width' : float. Relative width of violins. Max available space is 1, default is 0.8. - 'label_fontsize', MPL fontsize. Adjusts fontsize only if given. - 'label_rotation', scalar. Adjusts label rotation only if given. Specify in degrees. Returns ------- fig : Matplotlib figure instance If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. See Also -------- beanplot : Bean plot, builds on `violinplot`. matplotlib.pyplot.boxplot : Standard boxplot. Notes ----- The appearance of violins can be customized with `plot_opts`. If customization of boxplot elements is required, set `show_boxplot` to False and plot it on top of the violins by calling the Matplotlib `boxplot` function directly. For example:: violinplot(data, ax=ax, show_boxplot=False) ax.boxplot(data, sym='cv', whis=2.5) It can happen that the axis labels or tick labels fall outside the plot area, especially with rotated labels on the horizontal axis. With Matplotlib 1.1 or higher, this can easily be fixed by calling ``ax.tight_layout()``. With older Matplotlib one has to use ``plt.rc`` or ``plt.rcParams`` to fix this, for example:: plt.rc('figure.subplot', bottom=0.25) violinplot(data, ax=ax) References ---------- J.L. Hintze and R.D. Nelson, "Violin Plots: A Box Plot-Density Trace Synergism", The American Statistician, Vol. 52, pp.181-84, 1998. """ if ax is None: ax = plt.gca() if positions is None: positions = np.arange(len(data)) + 1 # Determine available horizontal space for each individual violin. pos_span = np.max(positions) - np.min(positions) width = np.min([0.15 * np.max([pos_span, 1.]), plot_opts.get('violin_width', 0.8) / 2.]) # Plot violins. for pos_data, pos in zip(data, positions): xvals, violin = _single_violin(ax, pos, pos_data, width, side, plot_opts) if show_boxplot: ax.boxplot(data, notch=1, positions=positions, vert=1) # Set ticks and tick labels of horizontal axis. _set_ticks_labels(ax, data, labels, positions, plot_opts) plt.draw_if_interactive() return ax
# All rights reserved. # Distributed under the terms of the BSD license: # http://www.opensource.org/licenses/bsd-license import numpy as np import bionet.utils.trig_poly as tp # Set matplotlib backend so that plots can be generated without a # display: import matplotlib matplotlib.use('AGG') import pylab as p output_name = '2d_demo_' output_count = 0 output_ext = '.png' if __name__ == '__main__': Sx = Sy = 1.0 dx = dy = 1/64.0 Mx = My = 4 S = tp.gen_trig_poly_2d(Sx, Sy, dx, dy, (Mx, My)) S/np.max(np.abs(S)) p.imshow(S) p.colorbar() p.draw_if_interactive() p.savefig(output_name + str(output_count) + output_ext)
def beanplot(data, ax=None, labels=None, positions=None, side='both', jitter=False, plot_opts={}): """Make a bean plot of each dataset in the `data` sequence. A bean plot is a combination of a `violinplot` (kernel density estimate of the probability density function per point) with a line-scatter plot of all individual data points. Parameters ---------- data : sequence of ndarrays Data arrays, one array per value in `positions`. ax : Matplotlib AxesSubplot instance, optional If given, this subplot is used to plot in instead of a new figure being created. labels : list of str, optional Tick labels for the horizontal axis. If not given, integers ``1..len(data)`` are used. positions : array_like, optional Position array, used as the horizontal axis of the plot. If not given, spacing of the violins will be equidistant. side : {'both', 'left', 'right'}, optional How to plot the violin. Default is 'both'. The 'left', 'right' options can be used to create asymmetric violin plots. jitter : bool, optional If True, jitter markers within violin instead of plotting regular lines around the center. This can be useful if the data is very dense. plot_opts : dict, optional A dictionary with plotting options. All the options for `violinplot` can be specified, they will simply be passed to `violinplot`. Options specific to `beanplot` are: - 'bean_color', MPL color. Color of bean plot lines. Default is 'k'. Also used for jitter marker edge color if `jitter` is True. - 'bean_size', scalar. Line length as a fraction of maximum length. Default is 0.5. - 'bean_lw', scalar. Linewidth, default is 0.5. - 'bean_show_mean', bool. If True (default), show mean as a line. - 'bean_show_median', bool. If True (default), show median as a marker. - 'bean_mean_color', MPL color. Color of mean line. Default is 'b'. - 'bean_mean_lw', scalar. Linewidth of mean line, default is 2. - 'bean_median_color', MPL color. Color of median marker. Default is 'r'. - 'bean_median_marker', MPL marker. Marker type, default is '+'. - 'jitter_marker', MPL marker. Marker type for ``jitter=True``. Default is 'o'. - 'jitter_marker_size', int. Marker size. Default is 4. - 'jitter_fc', MPL color. Jitter marker face color. Default is None. - 'bean_legend_text', str. If given, add a legend with given text. Returns ------- fig : Matplotlib figure instance If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. See Also -------- violinplot : Violin plot, also used internally in `beanplot`. matplotlib.pyplot.boxplot : Standard boxplot. References ---------- P. Kampstra, "Beanplot: A Boxplot Alternative for Visual Comparison of Distributions", J. Stat. Soft., Vol. 28, pp. 1-9, 2008. """ if ax is None: ax = plt.gca() if positions is None: positions = np.arange(len(data)) + 1 # Determine available horizontal space for each individual violin. pos_span = np.max(positions) - np.min(positions) width = np.min([0.15 * np.max([pos_span, 1.]), plot_opts.get('bean_size', 0.5) / 2.]) legend_txt = plot_opts.get('bean_legend_text', None) for pos_data, pos in zip(data, positions): # Draw violins. xvals, violin = _single_violin(ax, pos, pos_data, width, side, plot_opts) if jitter: # Draw data points at random coordinates within violin envelope. jitter_coord = pos + _jitter_envelope(pos_data, xvals, violin, side) ax.plot(jitter_coord, pos_data, ls='', marker=plot_opts.get('jitter_marker', 'o'), ms=plot_opts.get('jitter_marker_size', 4), mec=plot_opts.get('bean_color', 'k'), mew=1, mfc=plot_opts.get('jitter_fc', 'none'), label=legend_txt) else: # Draw bean lines. ax.hlines(pos_data, pos - width, pos + width, lw=plot_opts.get('bean_lw', 0.5), color=plot_opts.get('bean_color', 'k'), label=legend_txt) # Show legend if required. if legend_txt is not None: _show_legend(ax) legend_txt = None # ensure we get one entry per call to beanplot # Draw mean line. if plot_opts.get('bean_show_mean', True): ax.hlines(np.mean(pos_data), pos - width, pos + width, lw=plot_opts.get('bean_mean_lw', 2.), color=plot_opts.get('bean_mean_color', 'b')) # Draw median marker. if plot_opts.get('bean_show_median', True): ax.plot(pos, np.median(pos_data), marker=plot_opts.get('bean_median_marker', '+'), color=plot_opts.get('bean_median_color', 'r')) # Set ticks and tick labels of horizontal axis. _set_ticks_labels(ax, data, labels, positions, plot_opts) plt.draw_if_interactive() return ax
def kde_plot(x, ax=None, orientation='horizontal', cutoff=False, log=False, cutoff_type='std', cutoff_val=1.5, pos=100, pos_marker='line', pos_width=0.05, pos_kwargs={}, **kwargs): """""" if ax is None: ax = plt.gca() # Massage '_data' for processing. _data = np.asarray(x) # Create violin for pos, scaled to the available space. s = 0.0 if cutoff: if cutoff_type == 'std': s = cutoff_val * np.std(_data) else: s = cutoff_val x_lower = x.min() - s x_upper = x.max() + s # Kernel density estimate for data at this position. violin, e = fastkde.fastkde1D(_data, pos, extents=[x_lower, x_upper]) xvals = np.linspace(e[0], e[1], len(violin)) #violin /= violin.max() # Draw the violin. if ('facecolor' not in kwargs.keys()) | ('fc' not in kwargs.keys()): kwargs['facecolor'] = 'y' if ('edgecolor' not in kwargs.keys()) | ('ec' not in kwargs.keys()): kwargs['edgecolor'] = 'k' if ('alpha' not in kwargs.keys()): kwargs['alpha'] = 0.5 #draw the positions if not 'marker' in pos_kwargs: if pos_marker != 'line': pos_kwargs['marker'] = pos_marker else: pos_kwargs['marker'] = 's' else: pos_marker = pos_kwargs['marker'] if ('facecolor' not in pos_kwargs.keys()) | ('fc' not in pos_kwargs.keys()) | \ ('markerfacecolor' not in pos_kwargs.keys()) | ('mfc' not in pos_kwargs.keys()): pos_kwargs['markerfacecolor'] = 'None' if ('edgecolor' not in kwargs.keys()) | ('ec' not in pos_kwargs.keys()) | \ ('markeredgecolor' not in kwargs.keys()) | ('mec' not in pos_kwargs.keys()): pos_kwargs['markeredgecolor'] = 'k' if ('linestyle' not in pos_kwargs.keys()) | ('ls' not in pos_kwargs.keys()): pos_kwargs['linestyle'] = 'None' if ('size' not in kwargs.keys()) | ('markersize' not in pos_kwargs.keys()): pos_kwargs['markersize'] = 3 if orientation == 'horizontal': ax.fill(xvals, violin, **kwargs) mv = np.max(violin) #Draw the lines if pos_marker is not None: if (pos_marker == 'line') | (pos_marker == 'lines'): pos_kwargs.pop('marker') ax.plot(x, - 0.5 * pos_width * mv * np.ones(len(x)), marker='|', **pos_kwargs) else: ax.plot(x, np.random.uniform(low=-pos_width * mv, high=0., size=len(x)), **pos_kwargs) ax.set_ylim(-pos_width * mv, ax.get_ylim()[1]) plt.draw_if_interactive() elif orientation == 'vertical': ax.fill_betweenx(xvals, 0, violin, **kwargs) #Draw the lines if pos_marker is not None: if (pos_marker == 'line') | (pos_marker == 'lines'): pos_kwargs.pop('marker') ax.plot(-0.5 * pos_width * mv * np.ones(len(x)), x, marker='_', **pos_kwargs) else: ax.plot(np.random.uniform(low=-pos_width * mv, high=0., size=len(x)), x, **pos_kwargs) ax.set_xlim(-pos_width * mv, ax.get_xlim()[1]) plt.draw_if_interactive() return xvals, violin