Plot the curve and the knee, if it exists
8425
def plot_knee(self, ):
        
        import matplotlib.pyplot as plt

        plt.figure(figsize=(8, 8))
        plt.plot(self.x, self.y)
        plt.vlines(self.knee, plt.ylim()[0], plt.ylim()[1])
560250
def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0):
    '''
    '''
    assert isinstance(P, list)
    assert len(P) > 0
    for p in P:
        assert isinstance(p, tuple)
        for i in p:
            assert len(p) > 1
            assert isinstance(i, float)
    assert isinstance(n_seg, int)
    assert n_seg >= 0
    
    return [pt_on_bezier_curve(P, float(i)/n_seg) for i in range(n_seg)] + [P[-1]]
576170
def plot(self):
        
        import pylab as p
        p.clf()
        fig = p.figure(1)
        nspw = len(self.gain[0])
        ext = n.ceil(n.sqrt(nspw))  # find best squre plot (simplest)
        for spw in range(len(self.gain[0])):
            ax = fig.add_subplot(ext, ext, spw+1)
            for pol in [0,1]:
                ax.scatter(range(len(self.gain)), n.abs(self.gain.data[:,spw,pol]), color=n.array(['k','y']).take(self.gain.mask[:,spw,pol]), marker=['x','.'][pol])

        fig.show()
211554
def _plot(self):
        """"""
        total = sum(map(sum, map(lambda x: x.values, self.series)))
        if total == 0:
            return
        if self.half_pie:
            current_angle = 3 * pi / 2
        else:
            current_angle = 0

        for index, serie in enumerate(self.series):
            angle = self.slice(serie, current_angle, total)
            current_angle += angle
411878
def plot_data(self, proj, ax):
        
        x, y = proj
        ax.scatter(self.ig.independent_data[x],
                   self.ig.dependent_data[y], c='b')
374002
def plot_fixed_y(self, y_values, x_derivative=0, steps=1000, smooth=0, simple='auto', xmin="auto", xmax="auto", format=True, clear=1):
        
        if simple=='auto': simple=self.simple


        # get the min and max
        if xmin=="auto": xmin = self.xmin
        if xmax=="auto": xmax = self.xmax
        if clear: _pylab.gca().clear()

        if not type(y_values) in [type([]), type(_pylab.array([]))]: y_values = [y_values]

        for y in y_values:
            # define a new simple function to plot, then plot it
            def f(x): return self.evaluate(x, y, x_derivative, smooth, simple)
            _pylab_help.plot_function(f, xmin, xmax, steps, 0, True)

            # label it
            a = _pylab.gca()
            th = "th"
            if x_derivative == 1: th = "st"
            if x_derivative == 2: th = "nd"
            if x_derivative == 3: th = "rd"
            if x_derivative: a.set_ylabel(str(x_derivative)+th+" "+self.xlabel+" derivative of "+self.zlabel+" spline")
            else:            a.set_ylabel(self.zlabel)
            a.set_xlabel(self.xlabel)
            a.set_title(self._path+"\nSpline array plot at fixed y "+self.ylabel)
            a.get_lines()[-1].set_label("y ("+self.ylabel+") = "+str(y))
        if format: _s.format_figure()
        return a
1002715
def plotit(self, x, y, fields, colors=[]):
        ''''''
        pylab.ion()
        fig = pylab.figure(num=1, figsize=(12,6))
        ax1 = fig.gca()
        ax2 = None
        xrange = 0.0
        for i in range(0, len(fields)):
            if len(x[i]) == 0: continue
            if self.lowest_x is None or x[i][0] < self.lowest_x:
                self.lowest_x = x[i][0]
            if self.highest_x is None or x[i][-1] > self.highest_x:
                self.highest_x = x[i][-1]
        if self.highest_x is None or self.lowest_x is None:
            return
        xrange = self.highest_x - self.lowest_x
        xrange *= 24 * 60 * 60
        self.formatter = matplotlib.dates.DateFormatter('%H:%M:%S')
        interval = 1
        intervals = [ 1, 2, 5, 10, 15, 30, 60, 120, 240, 300, 600,
                      900, 1800, 3600, 7200, 5*3600, 10*3600, 24*3600 ]
        for interval in intervals:
            if xrange / interval < 15:
                break
        locator = matplotlib.dates.SecondLocator(interval=interval)
        if not self.xaxis:
            ax1.xaxis.set_major_locator(locator)
            ax1.xaxis.set_major_formatter(self.formatter)
        empty = True
        ax1_labels = []
        ax2_labels = []

        for i in range(0, len(fields)):
            if len(x[i]) == 0:
                print("Failed to find any values for field %s" % fields[i])
                continue
            if i < len(colors):
                color = colors[i]
            else:
                color = 'red'
                (tz, tzdst) = time.tzname

            if self.axes[i] == 2:
                if ax2 == None:
                    ax2 = ax1.twinx()
                    ax2.format_coord = self.make_format(ax2, ax1)
                ax = ax2
                if not self.xaxis:
                    ax2.xaxis.set_major_locator(locator)
                    ax2.xaxis.set_major_formatter(self.formatter)
                label = fields[i]
                if label.endswith(":2"):
                    label = label[:-2]
                ax2_labels.append(label)
            else:
                ax1_labels.append(fields[i])
                ax = ax1
            
            if self.xaxis:
                if self.marker is not None:
                    marker = self.marker
                else:
                    marker = '+'
                if self.linestyle is not None:
                    linestyle = self.linestyle
                else:
                    linestyle = 'None'
                ax.plot(x[i], y[i], color=color, label=fields[i],
                        linestyle=linestyle, marker=marker)
            else:
                if self.marker is not None:
                    marker = self.marker
                else:
                    marker = 'None'
                if self.linestyle is not None:
                    linestyle = self.linestyle
                else:
                    linestyle = '-'
                ax.plot_date(x[i], y[i], color=color, label=fields[i],
                             linestyle=linestyle, marker=marker, tz=None)

            empty = False
            if self.flightmode is not None:
                for i in range(len(self.modes)-1):
                    c = colourmap[self.flightmode].get(self.modes[i][1], edge_colour)
                    ax1.axvspan(self.modes[i][0], self.modes[i+1][0], fc=c, ec=edge_colour, alpha=0.1)
                c = colourmap[self.flightmode].get(self.modes[-1][1], edge_colour)
                ax1.axvspan(self.modes[-1][0], ax1.get_xlim()[1], fc=c, ec=edge_colour, alpha=0.1)

            if ax1_labels != []:
                ax1.legend(ax1_labels,loc=self.legend)
            if ax2_labels != []:
                ax2.legend(ax2_labels,loc=self.legend2)
            if empty:
                print("No data to graph")
                return
724124
def plotit(self, x, y, fields, colors=[], title=None):
        ''''''
        pylab.ion()
        self.fig = pylab.figure(num=1, figsize=(12,6))
        self.ax1 = self.fig.gca()
        ax2 = None
        for i in range(0, len(fields)):
            if len(x[i]) == 0: continue
            if self.lowest_x is None or x[i][0] < self.lowest_x:
                self.lowest_x = x[i][0]
            if self.highest_x is None or x[i][-1] > self.highest_x:
                self.highest_x = x[i][-1]
        if self.highest_x is None or self.lowest_x is None:
            return
        self.formatter = matplotlib.dates.DateFormatter('%H:%M:%S')
        if not self.xaxis:
            self.setup_xrange(self.highest_x - self.lowest_x)
            self.ax1.xaxis.set_major_formatter(self.formatter)
            self.ax1.callbacks.connect('xlim_changed', self.xlim_changed)
            self.fig.canvas.mpl_connect('draw_event', self.draw_event)
        empty = True
        ax1_labels = []
        ax2_labels = []

        for i in range(0, len(fields)):
            if len(x[i]) == 0:
                #print("Failed to find any values for field %s" % fields[i])
                continue
            if i < len(colors):
                color = colors[i]
            else:
                color = 'red'
                (tz, tzdst) = time.tzname

            if self.axes[i] == 2:
                if ax2 is None:
                    ax2 = self.ax1.twinx()
                    ax2.format_coord = self.make_format(ax2, self.ax1)
                ax = ax2
                if not self.xaxis:
                    ax2.xaxis.set_major_locator(self.locator)
                    ax2.xaxis.set_major_formatter(self.formatter)
                label = fields[i]
                if label.endswith(":2"):
                    label = label[:-2]
                ax2_labels.append(label)
            else:
                ax1_labels.append(fields[i])
                ax = self.ax1

            if self.xaxis:
                if self.marker is not None:
                    marker = self.marker
                else:
                    marker = '+'
                if self.linestyle is not None:
                    linestyle = self.linestyle
                else:
                    linestyle = 'None'
                ax.plot(x[i], y[i], color=color, label=fields[i],
                        linestyle=linestyle, marker=marker)
            else:
                if self.marker is not None:
                    marker = self.marker
                else:
                    marker = 'None'
                if self.linestyle is not None:
                    linestyle = self.linestyle
                else:
                    linestyle = '-'
                if len(y[i]) > 0 and isinstance(y[i][0],str):
                    # assume this is a piece of text to be rendered at a point in time
                    last_text_time = -1
                    last_text = None
                    for n in range(0, len(x[i])):
                        this_text_time = round(x[i][n], 6)
                        this_text = y[i][n]
                        if last_text is None:
                            last_text = "[y" + this_text + "]"
                            last_text_time = this_text_time
                        elif this_text_time == last_text_time:
                            last_text += ("[x" + this_text + "]")
                        else:
                            ax.text(last_text_time,
                                    10,
                                    last_text,
                                    rotation=90,
                                    alpha=0.3,
                                    verticalalignment='baseline')
                            last_text = this_text
                            last_text_time = this_text_time
                    if last_text is not None:
                        ax.text(last_text_time, 10, last_text,
                                rotation=90,
                                alpha=0.3,
                                verticalalignment='baseline')
                else:
                    ax.plot_date(x[i], y[i], color=color, label=fields[i],
                                 linestyle=linestyle, marker=marker, tz=None)

            empty = False
            
        if self.show_flightmode:
            alpha = 0.3
            xlim = self.ax1.get_xlim()
            for i in range(len(self.flightmode_list)):
                (mode_name,t0,t1) = self.flightmode_list[i]
                c = self.flightmode_colour(mode_name)
                tday0 = self.timestamp_to_days(t0)
                tday1 = self.timestamp_to_days(t1)
                if tday0 > xlim[1] or tday1 < xlim[0]:
                    continue
                tday0 = max(tday0, xlim[0])
                tday1 = min(tday1, xlim[1])
                self.ax1.axvspan(tday0, tday1, fc=c, ec=edge_colour, alpha=alpha)
                self.modes_plotted[mode_name] = (c, alpha)

        if empty:
            print("No data to graph")
            return

        if title is not None:
            pylab.title(title)

        if self.show_flightmode:
            mode_patches = []
            for mode in self.modes_plotted.keys():
                (color, alpha) = self.modes_plotted[mode]
                mode_patches.append(matplotlib.patches.Patch(color=color,
                                                             label=mode, alpha=alpha*1.5))
            labels = [patch.get_label() for patch in mode_patches]
            if ax1_labels != []:
                patches_legend = matplotlib.pyplot.legend(mode_patches, labels, loc=self.legend_flightmode)
                self.fig.gca().add_artist(patches_legend)
            else:
                pylab.legend(mode_patches, labels)

        if ax1_labels != []:
            self.ax1.legend(ax1_labels,loc=self.legend)
        if ax2_labels != []:
            ax2.legend(ax2_labels,loc=self.legend2)
1094854
def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs):
        
        if ax == None:
            ax = pl.gca()

        if ax_channels is not None:
            flip = self._find_orientation(ax_channels)

        plot_func = ax.axes.axhline if flip else ax.axes.axvline

        kwargs.setdefault('color', 'black')
        a1 = plot_func(self.vert[0], *args, **kwargs)
        a2 = plot_func(self.vert[1], *args, **kwargs)

        return (a1, a2)
874368
def plot_ortho_double(image, image2, overlay=None, overlay2=None, reorient=True,
    # xyz arguments
    xyz=None, xyz_lines=True, xyz_color='red', xyz_alpha=0.6, xyz_linewidth=2, xyz_pad=5,
    # base image arguments
    cmap='Greys_r', alpha=1, cmap2='Greys_r', alpha2=1,
    # overlay arguments
    overlay_cmap='jet', overlay_alpha=0.9, overlay_cmap2='jet', overlay_alpha2=0.9,  
    # background arguments
    black_bg=True, bg_thresh_quant=0.01, bg_val_quant=0.99, 
    # scale/crop/domain arguments
    crop=False, scale=False, crop2=False, scale2=True, domain_image_map=None, 
    # title arguments
    title=None, titlefontsize=24, title_dx=0, title_dy=0, 
    # 4th panel text arguemnts
    text=None, textfontsize=24, textfontcolor='white', text_dx=0, text_dy=0,
    # save & size arguments
    filename=None, dpi=500, figsize=1., flat=True, transpose=False, transparent=True):
    
    def mirror_matrix(x):
        return x[::-1,:]
    def rotate270_matrix(x):
        return mirror_matrix(x.T)
    def reorient_slice(x, axis):
        return rotate270_matrix(x)

    # need this hack because of a weird NaN warning from matplotlib with overlays
    warnings.simplefilter('ignore')

    # handle `image` argument
    if isinstance(image, str):
        image = iio2.image_read(image)
    if not isinstance(image, iio.ANTsImage):
        raise ValueError('image argument must be an ANTsImage')
    if image.dimension != 3:
        raise ValueError('Input image must have 3 dimensions!')
    
    if isinstance(image2, str):
        image2 = iio2.image_read(image2)
    if not isinstance(image2, iio.ANTsImage):
        raise ValueError('image2 argument must be an ANTsImage')
    if image2.dimension != 3:
        raise ValueError('Input image2 must have 3 dimensions!')

    # handle `overlay` argument 
    if overlay is not None:
        if isinstance(overlay, str):
            overlay = iio2.image_read(overlay)
        if not isinstance(overlay, iio.ANTsImage):
            raise ValueError('overlay argument must be an ANTsImage')
        if overlay.dimension != 3:
            raise ValueError('Overlay image must have 3 dimensions!')

        if not iio.image_physical_space_consistency(image, overlay):
            overlay = reg.resample_image_to_target(overlay, image, interp_type='linear')
    
    if overlay2 is not None:
        if isinstance(overlay2, str):
            overlay2 = iio2.image_read(overlay2)
        if not isinstance(overlay2, iio.ANTsImage):
            raise ValueError('overlay2 argument must be an ANTsImage')
        if overlay2.dimension != 3:
            raise ValueError('Overlay2 image must have 3 dimensions!')

        if not iio.image_physical_space_consistency(image2, overlay2):
            overlay2 = reg.resample_image_to_target(overlay2, image2, interp_type='linear')

    if not iio.image_physical_space_consistency(image, image2):
        image2 = reg.resample_image_to_target(image2, image, interp_type='linear')

    if image.pixeltype not in {'float', 'double'}:
        scale = False # turn off scaling if image is discrete

    if image2.pixeltype not in {'float', 'double'}:
        scale2 = False # turn off scaling if image is discrete

    # reorient images
    if reorient != False:
        if reorient == True:
            reorient = 'RPI'
        image = image.reorient_image2(reorient)
        image2 = image2.reorient_image2(reorient)
        if overlay is not None:
            overlay = overlay.reorient_image2(reorient)
        if overlay2 is not None:
            overlay2 = overlay2.reorient_image2(reorient)

    # handle `slices` argument
    if xyz is None:
        xyz = [int(s/2) for s in image.shape]
    for i in range(3):
        if xyz[i] is None:
            xyz[i] = int(image.shape[i]/2)

    # resample image if spacing is very unbalanced
    spacing = [s for i,s in enumerate(image.spacing)]
    if (max(spacing) / min(spacing)) > 3.:
        new_spacing = (1,1,1)
        image = image.resample_image(tuple(new_spacing))
        image2 = image2.resample_image_to_target(tuple(new_spacing))
        if overlay is not None:
            overlay = overlay.resample_image(tuple(new_spacing))
        if overlay2 is not None:
            overlay2 = overlay2.resample_image(tuple(new_spacing))
        xyz = [int(sl*(sold/snew)) for sl,sold,snew in zip(xyz,spacing,new_spacing)]

    # pad images
    image, lowpad, uppad = image.pad_image(return_padvals=True)
    image2, lowpad2, uppad2 = image2.pad_image(return_padvals=True)
    xyz = [v+l for v,l in zip(xyz,lowpad)]
    if overlay is not None:
        overlay = overlay.pad_image()
    if overlay2 is not None:
        overlay2 = overlay2.pad_image()

    # handle `domain_image_map` argument
    if domain_image_map is not None:
        if isinstance(domain_image_map, iio.ANTsImage):
            tx = tio2.new_ants_transform(precision='float', transform_type='AffineTransform',
                                         dimension=image.dimension)
            image = tio.apply_ants_transform_to_image(tx, image, domain_image_map)
            image2 = tio.apply_ants_transform_to_image(tx, image2, domain_image_map)
            if overlay is not None:
                overlay = tio.apply_ants_transform_to_image(tx, overlay, 
                                                            domain_image_map, 
                                                            interpolation='linear')
            if overlay2 is not None:
                overlay2 = tio.apply_ants_transform_to_image(tx, overlay2, 
                                                            domain_image_map, 
                                                            interpolation='linear')          
        elif isinstance(domain_image_map, (list, tuple)):
            # expect an image and transformation
            if len(domain_image_map) != 2:
                raise ValueError('domain_image_map list or tuple must have length == 2')
            
            dimg = domain_image_map[0]
            if not isinstance(dimg, iio.ANTsImage):
                raise ValueError('domain_image_map first entry should be ANTsImage')

            tx = domain_image_map[1]
            image = reg.apply_transforms(dimg, image, transform_list=tx)
            if overlay is not None:
                overlay = reg.apply_transforms(dimg, overlay, transform_list=tx,
                                               interpolator='linear')

            image2 = reg.apply_transforms(dimg, image2, transform_list=tx)
            if overlay2 is not None:
                overlay2 = reg.apply_transforms(dimg, overlay2, transform_list=tx,
                                               interpolator='linear')

    ## single-channel images ##
    if image.components == 1:
        
        # potentially crop image
        if crop:
            plotmask = image.get_mask(cleanup=0)
            if plotmask.max() == 0:
                plotmask += 1
            image = image.crop_image(plotmask)
            if overlay is not None:
                overlay = overlay.crop_image(plotmask)
        
        if crop2:
            plotmask2 = image2.get_mask(cleanup=0)
            if plotmask2.max() == 0:
                plotmask2 += 1
            image2 = image2.crop_image(plotmask2)
            if overlay2 is not None:
                overlay2 = overlay2.crop_image(plotmask2)


        # potentially find dynamic range
        if scale == True:
            vmin, vmax = image.quantile((0.05,0.95))
        elif isinstance(scale, (list,tuple)):
            if len(scale) != 2:
                raise ValueError('scale argument must be boolean or list/tuple with two values')
            vmin, vmax = image.quantile(scale)
        else:
            vmin = None
            vmax = None

        if scale2 == True:
            vmin2, vmax2 = image2.quantile((0.05,0.95))
        elif isinstance(scale2, (list,tuple)):
            if len(scale2) != 2:
                raise ValueError('scale2 argument must be boolean or list/tuple with two values')
            vmin2, vmax2 = image2.quantile(scale2)
        else:
            vmin2 = None
            vmax2 = None

        if not flat:
            nrow = 2
            ncol = 4
        else:
            if not transpose:
                nrow = 2
                ncol = 3
            else:
                nrow = 3
                ncol = 2

        fig = plt.figure(figsize=((ncol+1)*2.5*figsize, (nrow+1)*2.5*figsize))
        if title is not None:
            basey = 0.88 if not flat else 0.66
            basex = 0.5
            fig.suptitle(title, fontsize=titlefontsize, x=basex+title_dx, y=basey+title_dy)

        gs = gridspec.GridSpec(nrow, ncol,
                 wspace=0.0, hspace=0.0, 
                 top=1.-0.5/(nrow+1), bottom=0.5/(nrow+1), 
                 left=0.5/(ncol+1), right=1-0.5/(ncol+1))

        # pad image to have isotropic array dimensions
        image = image.numpy()
        if overlay is not None:
            overlay = overlay.numpy()
            overlay[np.abs(overlay) == 0] = np.nan

        image2 = image2.numpy()
        if overlay2 is not None:
            overlay2 = overlay2.numpy()
            overlay2[np.abs(overlay2) == 0] = np.nan

        ####################
        ####################
        yz_slice = reorient_slice(image[xyz[0],:,:],0)
        ax = plt.subplot(gs[0,0])
        ax.imshow(yz_slice, cmap=cmap, vmin=vmin, vmax=vmax)
        if overlay is not None:
            yz_overlay = reorient_slice(overlay[xyz[0],:,:],0)
            ax.imshow(yz_overlay, alpha=overlay_alpha, cmap=overlay_cmap)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([yz_slice.shape[0]-xyz[1],yz_slice.shape[0]-xyz[1]], 
                              [xyz_pad,yz_slice.shape[0]-xyz_pad],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,yz_slice.shape[1]-xyz_pad], 
                              [yz_slice.shape[1]-xyz[2],yz_slice.shape[1]-xyz[2]],
                color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')

        #######
        yz_slice2 = reorient_slice(image2[xyz[0],:,:],0)
        if not flat:
            ax = plt.subplot(gs[0,1])
        else:
            if not transpose:
                ax = plt.subplot(gs[1,0])
            else:
                ax = plt.subplot(gs[0,1])
        ax.imshow(yz_slice2, cmap=cmap2, vmin=vmin2, vmax=vmax2)
        if overlay2 is not None:
            yz_overlay2 = reorient_slice(overlay2[xyz[0],:,:],0)
            ax.imshow(yz_overlay2, alpha=overlay_alpha2, cmap=overlay_cmap2)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([yz_slice2.shape[0]-xyz[1],yz_slice2.shape[0]-xyz[1]], 
                              [xyz_pad,yz_slice2.shape[0]-xyz_pad],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,yz_slice2.shape[1]-xyz_pad], 
                              [yz_slice2.shape[1]-xyz[2],yz_slice2.shape[1]-xyz[2]],
                color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')
        ####################
        ####################

        xz_slice = reorient_slice(image[:,xyz[1],:],1)
        if not flat:
            ax = plt.subplot(gs[0,2])
        else:
            if not transpose:
                ax = plt.subplot(gs[0,1])
            else:
                ax = plt.subplot(gs[1,0])
        ax.imshow(xz_slice, cmap=cmap, vmin=vmin, vmax=vmax)
        if overlay is not None:
            xz_overlay = reorient_slice(overlay[:,xyz[1],:],1)
            ax.imshow(xz_overlay, alpha=overlay_alpha, cmap=overlay_cmap)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([xz_slice.shape[0]-xyz[0],xz_slice.shape[0]-xyz[0]], 
                              [xyz_pad,xz_slice.shape[0]-xyz_pad],
                               color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,xz_slice.shape[1]-xyz_pad], 
                              [xz_slice.shape[1]-xyz[2],xz_slice.shape[1]-xyz[2]],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')

        #######
        xz_slice2 = reorient_slice(image2[:,xyz[1],:],1)
        if not flat:
            ax = plt.subplot(gs[0,3])
        else:
            ax = plt.subplot(gs[1,1])
        ax.imshow(xz_slice2, cmap=cmap2, vmin=vmin2, vmax=vmax2)
        if overlay is not None:
            xz_overlay2 = reorient_slice(overlay2[:,xyz[1],:],1)
            ax.imshow(xz_overlay2, alpha=overlay_alpha2, cmap=overlay_cmap2)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([xz_slice2.shape[0]-xyz[0],xz_slice2.shape[0]-xyz[0]], 
                              [xyz_pad,xz_slice2.shape[0]-xyz_pad],
                               color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,xz_slice2.shape[1]-xyz_pad], 
                              [xz_slice2.shape[1]-xyz[2],xz_slice2.shape[1]-xyz[2]],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')

        ####################
        ####################
        xy_slice = reorient_slice(image[:,:,xyz[2]],2)
        if not flat:
            ax = plt.subplot(gs[1,2])
        else:
            if not transpose:
                ax = plt.subplot(gs[0,2])
            else:
                ax = plt.subplot(gs[2,0])
        ax.imshow(xy_slice, cmap=cmap, vmin=vmin, vmax=vmax)
        if overlay is not None:
            xy_overlay = reorient_slice(overlay[:,:,xyz[2]],2)
            ax.imshow(xy_overlay, alpha=overlay_alpha, cmap=overlay_cmap)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([xy_slice.shape[0]-xyz[0],xy_slice.shape[0]-xyz[0]], 
                              [xyz_pad,xy_slice.shape[0]-xyz_pad],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,xy_slice.shape[1]-xyz_pad], 
                              [xy_slice.shape[1]-xyz[1],xy_slice.shape[1]-xyz[1]],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')

        #######
        xy_slice2 = reorient_slice(image2[:,:,xyz[2]],2)
        if not flat:
            ax = plt.subplot(gs[1,3])
        else:
            if not transpose:
                ax = plt.subplot(gs[1,2])
            else:
                ax = plt.subplot(gs[2,1])
        ax.imshow(xy_slice2, cmap=cmap2, vmin=vmin2, vmax=vmax2)
        if overlay is not None:
            xy_overlay2 = reorient_slice(overlay2[:,:,xyz[2]],2)
            ax.imshow(xy_overlay2, alpha=overlay_alpha2, cmap=overlay_cmap2)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([xy_slice2.shape[0]-xyz[0],xy_slice2.shape[0]-xyz[0]], 
                              [xyz_pad,xy_slice2.shape[0]-xyz_pad],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,xy_slice2.shape[1]-xyz_pad], 
                              [xy_slice2.shape[1]-xyz[1],xy_slice2.shape[1]-xyz[1]],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')

        ####################
        ####################

        if not flat:
            # empty corner
            ax = plt.subplot(gs[1,:2])
            if text is not None:
                # add text
                left, width = .25, .5
                bottom, height = .25, .5
                right = left + width
                top = bottom + height
                ax.text(0.5*(left+right)+text_dx, 0.5*(bottom+top)+text_dy, text,
                        horizontalalignment='center',
                        verticalalignment='center',
                        fontsize=textfontsize, color=textfontcolor,
                        transform=ax.transAxes)
            #ax.text(0.5, 0.5)
            img_shape = list(image.shape[:-1])
            img_shape[1] *= 2
            ax.imshow(np.zeros(img_shape), cmap='Greys_r')
            ax.axis('off')


    ## multi-channel images ##
    elif image.components > 1:
        raise ValueError('Multi-channel images not currently supported!')

    if filename is not None:
        plt.savefig(filename, dpi=dpi, transparent=transparent)
        plt.close(fig)
    else:
        plt.show()

    # turn warnings back to default
    warnings.simplefilter('default')
850539
function plot($x, $y, $type, $size, $colour, $offset) {
      //print("drawing point of type: $type, at offset: $offset");
      $u = $x + $offset;
      $v = $this->calculated['inner_border']['bottom'] - $y + $offset;
      $half = $size / 2;

      switch ($type) {
        case 'square':
          ImageFilledRectangle($this->image, $u-$half, $v-$half, $u+$half, $v+$half, $this->colour[$colour]);
          break;
        case 'square-open':
          ImageRectangle($this->image, $u-$half, $v-$half, $u+$half, $v+$half, $this->colour[$colour]);
          break;
        case 'circle':
          ImageArc($this->image, $u, $v, $size, $size, 0, 360, $this->colour[$colour]);
          ImageFillToBorder($this->image, $u, $v, $this->colour[$colour], $this->colour[$colour]);
          break;
        case 'circle-open':
          ImageArc($this->image, $u, $v, $size, $size, 0, 360, $this->colour[$colour]);
          break;
        case 'diamond':
          ImageFilledPolygon($this->image, array($u, $v-$half, $u+$half, $v, $u, $v+$half, $u-$half, $v), 4, $this->colour[$colour]);
          break;
        case 'diamond-open':
          ImagePolygon($this->image, array($u, $v-$half, $u+$half, $v, $u, $v+$half, $u-$half, $v), 4, $this->colour[$colour]);
          break;
        case 'triangle':
          ImageFilledPolygon($this->image, array($u, $v-$half, $u+$half, $v+$half, $u-$half, $v+$half), 3, $this->colour[$colour]);
          break;
        case 'triangle-open':
          ImagePolygon($this->image, array($u, $v-$half, $u+$half, $v+$half, $u-$half, $v+$half), 3, $this->colour[$colour]);
          break;
        case 'dot':
          ImageSetPixel($this->image, $u, $v, $this->colour[$colour]);
          break;
      }
    }
252374
def _plot(x, mph, mpd, threshold, edge, valley, ax, ind):
    """"""
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        print('matplotlib is not available.')
    else:
        if ax is None:
            _, ax = plt.subplots(1, 1, figsize=(8, 4))

        ax.plot(x, 'b', lw=1)
        if ind.size:
            label = 'valley' if valley else 'peak'
            label = label + 's' if ind.size > 1 else label
            ax.plot(ind, x[ind], '+', mfc=None, mec='r', mew=2, ms=8,
                    label='%d %s' % (ind.size, label))
            ax.legend(loc='best', framealpha=.5, numpoints=1)
        ax.set_xlim(-.02*x.size, x.size*1.02-1)
        ymin, ymax = x[np.isfinite(x)].min(), x[np.isfinite(x)].max()
        yrange = ymax - ymin if ymax > ymin else 1
        ax.set_ylim(ymin - 0.1*yrange, ymax + 0.1*yrange)
        ax.set_xlabel('Data #', fontsize=14)
        ax.set_ylabel('Amplitude', fontsize=14)
        mode = 'Valley detection' if valley else 'Peak detection'
        ax.set_title("%s (mph=%s, mpd=%d, threshold=%s, edge='%s')"
                     % (mode, str(mph), mpd, str(threshold), edge))
1149676
def plot_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
                             labels=None, color_labels=None, ellipse_outline=False,
                             ellipse_fill=True, show_points=True, **kwargs):
        """"""
        utils.validation.check_is_fitted(self, 's_')

        if ax is None:
            fig, ax = plt.subplots(figsize=figsize)

        # Add style
        ax = plot.stylize_axis(ax)

        # Make sure X is a DataFrame
        if not isinstance(X, pd.DataFrame):
            X = pd.DataFrame(X)

        # Retrieve principal coordinates
        coordinates = self.row_coordinates(X)
        x = coordinates[x_component].astype(np.float)
        y = coordinates[y_component].astype(np.float)

        # Plot
        if color_labels is None:
            ax.scatter(x, y, **kwargs)
        else:
            for color_label in sorted(list(set(color_labels))):
                mask = np.array(color_labels) == color_label
                color = ax._get_lines.get_next_color()
                # Plot points
                if show_points:
                    ax.scatter(x[mask], y[mask], color=color, **kwargs, label=color_label)
                # Plot ellipse
                if (ellipse_outline or ellipse_fill):
                    x_mean, y_mean, width, height, angle = plot.build_ellipse(x[mask], y[mask])
                    ax.add_patch(mpl.patches.Ellipse(
                        (x_mean, y_mean),
                        width,
                        height,
                        angle=angle,
                        linewidth=2 if ellipse_outline else 0,
                        color=color,
                        fill=ellipse_fill,
                        alpha=0.2 + (0.3 if not show_points else 0) if ellipse_fill else 1
                    ))

        # Add labels
        if labels is not None:
            for i, label in enumerate(labels):
                ax.annotate(label, (x[i], y[i]))

        # Legend
        ax.legend()

        # Text
        ax.set_title('Row principal coordinates')
        ei = self.explained_inertia_
        ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
        ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))

        return ax
1062190
def plot_trajectories(T, colors=None, fig='current', ax=None, colorbar=False,
                      cmap=None, alpha=1, linewidth=1, title=None):
  ''''''
  ax = _get_axis(fig, ax, False)
  if colors is not None:
    colors = np.asanyarray(colors)
  lc = LineCollection(T, array=colors, cmap=cmap, alpha=alpha,
                      linewidth=linewidth)
  ax.add_collection(lc, autolim=True)
  if colors is not None and colorbar:
    cbar = ax.figure.colorbar(lc)
    cbar.set_alpha(1.)  # colorbars with alpha are ugly
    cbar.draw_all()
  ax.autoscale_view()
  if title:
    ax.set_title(title)
  return plt.show
808029
def _plot(self, xticks=[], yticks=[], minor_xticks=[], minor_yticks=[],
              xlabel='Longitude', ylabel='Latitude', ax=None, ax2=None,
              colorbar=None, cb_label=None, cb_orientation=None, grid=False,
              axes_labelsize=None, tick_labelsize=None, **kwargs):
        """"""
        if ax is None:
            if colorbar is True:
                if cb_orientation == 'horizontal':
                    scale = 1.5
                else:
                    scale = 1.1
            else:
                scale = 1.2
            figsize = (_mpl.rcParams['figure.figsize'][0],
                       _mpl.rcParams['figure.figsize'][0]*scale)
            fig, axes = _plt.subplots(2, 1, figsize=figsize)
            axreal = axes.flat[0]
            axcomplex = axes.flat[1]
        else:
            axreal = ax
            axcomplex = ax2

        deg = '$^{\circ}$'
        xticklabels = [str(int(y)) + deg for y in xticks]
        yticklabels = [str(int(y)) + deg for y in yticks]

        cim1 = axreal.imshow(self.data.real, origin='upper',
                             extent=(0., 360., -90., 90.), **kwargs)
        axreal.set(title='Real component', xticks=xticks, yticks=yticks)
        axreal.set_xlabel(xlabel, fontsize=axes_labelsize)
        axreal.set_ylabel(ylabel, fontsize=axes_labelsize)
        axreal.set_xticklabels(xticklabels, fontsize=tick_labelsize)
        axreal.set_yticklabels(yticklabels, fontsize=tick_labelsize)
        axreal.set_xticks(minor_xticks, minor=True)
        axreal.set_yticks(minor_yticks, minor=True)
        axreal.grid(grid, which='major')
        cim2 = axcomplex.imshow(self.data.imag, origin='upper',
                                extent=(0., 360., -90., 90.), **kwargs)
        axcomplex.set(title='Imaginary component', xticks=xticks,
                      yticks=yticks)
        axcomplex.set_xlabel(xlabel, fontsize=axes_labelsize)
        axcomplex.set_ylabel(ylabel, fontsize=axes_labelsize)
        axcomplex.set_xticklabels(xticklabels, fontsize=tick_labelsize)
        axcomplex.set_yticklabels(yticklabels, fontsize=tick_labelsize)
        axcomplex.set_xticks(minor_xticks, minor=True)
        axcomplex.set_yticks(minor_yticks, minor=True)
        axcomplex.grid(grid, which='major')

        if colorbar is True:
            if cb_orientation == 'vertical':
                divider1 = _make_axes_locatable(axreal)
                cax1 = divider1.append_axes("right", size="2.5%", pad=0.05)
                cbar1 = _plt.colorbar(cim1, cax=cax1,
                                      orientation=cb_orientation)
                divider2 = _make_axes_locatable(axcomplex)
                cax2 = divider2.append_axes("right", size="2.5%", pad=0.05)
                cbar2 = _plt.colorbar(cim2, cax=cax2,
                                      orientation=cb_orientation)
            else:
                divider1 = _make_axes_locatable(axreal)
                cax1 = divider1.append_axes("bottom", size="5%", pad=0.5)
                cbar1 = _plt.colorbar(cim1, cax=cax1,
                                      orientation=cb_orientation)
                divider2 = _make_axes_locatable(axcomplex)
                cax2 = divider2.append_axes("bottom", size="5%", pad=0.5)
                cbar2 = _plt.colorbar(cim2, cax=cax2,
                                      orientation=cb_orientation)

            if cb_label is not None:
                cbar1.set_label(cb_label, fontsize=axes_labelsize)
                cbar2.set_label(cb_label, fontsize=axes_labelsize)
            cbar1.ax.tick_params(labelsize=tick_labelsize)
            cbar2.ax.tick_params(labelsize=tick_labelsize)

        if ax is None:
            return fig, axes
69614
def plot_triaxial(height, width, tools):
    ''''''
    import bokeh.plotting

    p = bokeh.plotting.figure(x_axis_type='datetime',
                              plot_height=height,
                              plot_width=width,
                              title=' ',
                              toolbar_sticky=False,
                              tools=tools,
                              active_drag=BoxZoomTool(),
                              output_backend='webgl')

    p.yaxis.axis_label = 'Acceleration (count)'
    p.xaxis.axis_label = 'Time (timezone as programmed)'

    # Plot accelerometry data as lines and scatter (for BoxSelectTool)
    colors = ['#1b9e77', '#d95f02', '#7570b3']
    axes = ['x', 'y', 'z']
    lines = [None,]*3
    scats = [None,]*3
    for i, (ax, c) in enumerate(zip(axes, colors)):
        lines[i] = p.line(y=ax, x='dt', color=c, legend=False, source=source)
        scats[i] = p.scatter(y=ax, x='dt', color=c, legend=False, size=1,
                             source=source)
    return p, lines, scats
1054613
def plot_curves_z(data, name, title=None):
    """"""

    plt.figure()
    for zet, c in zip(data['zeta'], data['doping']):
        plt.plot(data['u_int'], zet[:, 0], label='$n={}$'.format(str(c)))
    if title != None:
        plt.title(title)
    label_saves(name+'.png')