Generate interactive plot
766337
def displayplot(data, plinds, plottype, scaling, fileroot, url_path='http://www.aoc.nrao.edu/~claw/plots'):
    

    plotdict = {'dmt': plotdmt, 'norm': plotnorm,
               'loc': plotloc, 'stat': plotstat,
               'all': plotall}
    sizedict = {'dmt': [900,500], 'norm': [700, 700], 'loc': [700,700],
                'stat': [700,700]}

    sortinds = sorted(set(plinds['cir'] + plinds['cro'] + plinds['edg']))
    sizesrc, plaw = scaling.split('_')
    data['sizes'] = calcsize(data[sizesrc], inds=sortinds, plaw=int(plaw))

    if plottype != 'all':
        wid, hei = sizedict[plottype]
        pl = plotdict[plottype](data, circleinds=plinds['cir'], crossinds=plinds['cro'],
                                edgeinds=plinds['edg'], url_path=url_path,
                                fileroot=fileroot, plot_width=wid, plot_height=hei)
    else:
        pl = plotall(data, circleinds=plinds['cir'], crossinds=plinds['cro'],
                                 edgeinds=plinds['edg'], url_path=url_path,
                                 fileroot=fileroot)
    hdl = show(pl)
813936
def plotit(self):
        '''
        
        '''
        [self._plot(i) for i in range(len(self.plots))]
748010
def getPlot(self, params):
        
        try:
            return eval("self." + str(params['output_id']) + "(params)")
        except AttributeError:
            df = self.getData(params)
            if df is None:
                return None
            return df.plot()
947875
def plot_results(fout_img, goea_results, **kws):
    """"""
    if "{NS}" not in fout_img:
        plt_goea_results(fout_img, goea_results, **kws)
    else:
        # Plot separately by NS: BP, MF, CC
        ns2goea_results = cx.defaultdict(list)
        for rec in goea_results:
            ns2goea_results[rec.NS].append(rec)
        for ns_name, ns_res in ns2goea_results.items():
            fout = fout_img.format(NS=ns_name)
            plt_goea_results(fout, ns_res, **kws)
1204111
def _generate_collection(group, ax, ctype, colors):
    ''''''
    color = TREE_COLOR[ctype]

    # generate segment collection
    collection = PolyCollection(group, closed=False, antialiaseds=True,
                                edgecolors='face', facecolors=color)

    # add it to the axes
    ax.add_collection(collection)

    # dummy plot for the legend
    if color not in colors:
        label = str(ctype).replace('NeuriteType.', '').replace('_', ' ').capitalize()
        ax.plot((0., 0.), (0., 0.), c=color, label=label)
        colors.add(color)
720065
def plot(self, axis, ith_plot, total_plots, limits):
        
        print(self.plot_type_str.upper() + " plot")
        print("%5s %9s  %s" % ("id", " #points", "group"))

        for idx, group in enumerate(self.groups):
            print("%5s %9s  %s" % (idx + 1, len(self.groups[group]), group))

        print('')

        datasets = []
        colors = []
        minx = np.inf
        maxx = -np.inf

        for idx, group in enumerate(self.groups):
            x = date2num([logevent.datetime
                          for logevent in self.groups[group]])
            minx = min(minx, min(x))
            maxx = max(maxx, max(x))
            datasets.append(x)
            color, marker = self.color_map(group)
            colors.append(color)

        if total_plots > 1:
            # if more than one plot, move histogram to twin axis on the right
            twin_axis = axis.twinx()
            twin_axis.set_ylabel(self.ylabel)
            axis.set_zorder(twin_axis.get_zorder() + 1)  # put ax ahead of ax2
            axis.patch.set_visible(False)  # hide the 'canvas'
            axis = twin_axis

        n_bins = max(1, int((maxx - minx) * 24. * 60. * 60. / self.bucketsize))
        if n_bins > 1000:
            # warning for too many buckets
            print("warning: %i buckets, will take a while to render. "
                  "consider increasing --bucketsize." % n_bins)

        n, bins, artists = axis.hist(datasets, bins=n_bins, align='mid',
                                     log=self.logscale,
                                     histtype="barstacked"
                                     if self.barstacked else "bar",
                                     color=colors, edgecolor="none",
                                     linewidth=0, alpha=0.8, picker=True,
                                     label=map(str, self.groups.keys()))

        # scale current y-axis to match min and max values
        axis.set_ylim(np.min(n), np.max(n))

        # add meta-data for picking
        if len(self.groups) > 1:
            for g, group in enumerate(self.groups.keys()):
                for i in range(len(artists[g])):
                    artists[g][i]._mt_plot_type = self
                    artists[g][i]._mt_group = group
                    artists[g][i]._mt_n = n[g][i]
                    if self.barstacked:
                        artists[g][i]._mt_n -= (n[g - 1][i] if g > 0 else 0)

                    artists[g][i]._mt_bin = bins[i]
        else:
            for i in range(len(artists)):
                artists[i]._mt_plot_type = self
                artists[i]._mt_group = group
                artists[i]._mt_n = n[i]
                artists[i]._mt_bin = bins[i]

        return artists
873152
def main():
    
    allowed_format = ("emf", "eps", "pdf", "png", "ps", \
                      "raw", "rgba", "svg", "svgz")
    p = OptionParser(main.__doc__)
    p.add_option("--skip", default=0, type="int",
            help="skip the first several lines [default: %default]")
    p.add_option("--col", default=0, type="int", help="Get the n-th column")
    p.set_histogram()
    p.add_option("--tags", dest="tags", default=None,
            help="tags for data if multiple input files, comma sep")
    p.add_option("--ascii", default=False, action="store_true",
            help="print ASCII text stem-leaf plot [default: %default]")
    p.add_option("--base", default="0", choices=("0", "2", "10"),
            help="use logarithm axis with base, 0 to disable [default: %default]")
    p.add_option("--facet", default=False, action="store_true",
            help="place multiple histograms side-by-side [default: %default]")
    p.add_option("--fill", default="white",
            help="color of the bin [default: %default]")
    p.add_option("--format", default="pdf", choices=allowed_format,
            help="Generate image of format [default: %default]")
    p.add_option("--quick", default=False, action="store_true",
            help="Use quick plot, assuming bins are already counted")
    p.add_option("--noprintstats", default=False, action="store_true",
            help="Write basic stats when using --quick")
    opts, args = p.parse_args()

    if len(args) < 1:
        sys.exit(not p.print_help())

    skip = opts.skip
    vmin, vmax = opts.vmin, opts.vmax
    bins = opts.bins
    xlabel, title = opts.xlabel, opts.title
    title = title or args[0]
    base = int(opts.base)
    fileno = len(args)

    if opts.quick:
        assert fileno == 1, "Single input file expected using --quick"
        filename = args[0]
        figname = filename.rsplit(".", 1)[0] + ".pdf"
        data = DictFile(filename, keycast=int, cast=int)
        quickplot(data, vmin, vmax, xlabel, title, figname=figname,
                  print_stats=(not opts.noprintstats))
        return

    if fileno == 1:
        histogram(args[0], vmin, vmax, xlabel, title, outfmt=opts.format,
                bins=bins, skip=skip, ascii=opts.ascii,
                base=base, fill=opts.fill, col=opts.col)
    else:
        histogram_multiple(args, vmin, vmax, xlabel, title, outfmt=opts.format,
                tags=opts.tags, bins=bins, skip=skip, ascii=opts.ascii,
                facet=opts.facet, fill=opts.fill)
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)
23885
def plot(self, f, lfilter=None,**kargs):
        """"""

        return plt.plot([ f(i) for i in self.res if not lfilter or lfilter(i) ], **kargs)
813280
def plot(self, x, y, color="black"):
        
        p = Point(x, y)
        p.fill(color)
        p.draw(self)
597556
def plot(self):
		'''
		
		'''
		pl.plot(self.x, self.y, '.')
		pl.plot(self.x_int, self.y_int)
		pl.grid(True)
		pl.show()
57547
def draw_plot(self):
        
        import numpy, pylab
        state = self.state

        if len(self.data[0]) == 0:
            print("no data to plot")
            return
        vhigh = max(self.data[0])
        vlow  = min(self.data[0])

        for i in range(1,len(self.plot_data)):
            vhigh = max(vhigh, max(self.data[i]))
            vlow  = min(vlow,  min(self.data[i]))
        ymin = vlow  - 0.05*(vhigh-vlow)
        ymax = vhigh + 0.05*(vhigh-vlow)

        if ymin == ymax:
            ymax = ymin + 0.1
            ymin = ymin - 0.1
        self.axes.set_ybound(lower=ymin, upper=ymax)
        self.axes.grid(True, color='gray')
        pylab.setp(self.axes.get_xticklabels(), visible=True)
        pylab.setp(self.axes.get_legend().get_texts(), fontsize='small')

        for i in range(len(self.plot_data)):
            ydata = numpy.array(self.data[i])
            xdata = self.xdata
            if len(ydata) < len(self.xdata):
                xdata = xdata[-len(ydata):]
            self.plot_data[i].set_xdata(xdata)
            self.plot_data[i].set_ydata(ydata)

        self.canvas.draw()
1347256
def plot_clicked(self, event):
        """"""
        flip = False
        choose = False
        zoom = False
        replot = False
        items = self.win.scene().items(event.scenePos())
        posx = 0
        posy = 0
        iplot = 0
        if self.loaded:
            # print(event.modifiers() == QtCore.Qt.ControlModifier)
            for x in items:
                if x == self.p0:
                    if self.embedded:
                        iplot = 0
                        vb = self.p0.vb
                        pos = vb.mapSceneToView(event.scenePos())
                        x = pos.x()
                        y = pos.y()
                        if event.double():
                            self.zoom_plot(iplot)
                        elif event.button() == 2:
                            # do nothing
                            nothing = True
                        elif event.modifiers() == QtCore.Qt.ShiftModifier:
                            if not self.startROI:
                                self.startROI = True
                                self.endROI = False
                                self.posROI[0,:] = [x,y]
                            else:
                                # plotting
                                self.startROI = True
                                self.endROI = False
                                self.posROI[1,:] = [x,y]
                                #print(self.)
                                self.posAll.append(self.posROI[:2,:].copy())
                                pos = self.posAll[-1]
                                self.lp.append(pg.PlotDataItem(pos[:, 0], pos[:, 1]))
                                self.posROI[0,:] = [x,y]
                                self.p0.addItem(self.lp[-1])
                                self.p0.show()
                        elif self.startROI:
                            self.posROI[1,:] = [x,y]
                            self.posAll.append(self.posROI[:2,:].copy())
                            self.p0.removeItem(self.l0)
                            pos = self.posAll[-1]
                            self.lp.append(pg.PlotDataItem(pos[:, 0], pos[:, 1]))
                            self.p0.addItem(self.lp[-1])
                            self.p0.show()
                            self.endROI = True
                            self.startROI = False
                        elif self.endROI:
                            self.posROI[2,:] = [x,y]
                            self.endROI = False
                            for lp in self.lp:
                                self.p0.removeItem(lp)
                            self.ROI_add(self.posAll, self.prect)
                            self.posAll = []
                            self.lp = []

                        elif event.modifiers() == QtCore.Qt.AltModifier:
                            self.ROI_remove([x,y])

                elif x == self.p1:
                    iplot = 1
                    y = self.p1.vb.mapSceneToView(event.scenePos()).y()
                    ineur = min(self.colormat.shape[0]-1, max(0, int(np.floor(y))))
                    ineur = ineur + self.yrange[0]
                    if event.double():
                        self.zoom_plot(iplot)
                    elif event.modifiers() == QtCore.Qt.AltModifier:
                        self.ROI_remove([ineur])
                elif x == self.p3:
                    iplot = 2
                    y = self.p3.vb.mapSceneToView(event.scenePos()).y()
                    ineur = min(self.colormat.shape[0]-1, max(0, int(np.floor(y))))
                    if event.modifiers() == QtCore.Qt.AltModifier:
                        self.ROI_remove([ineur])
657361
def plot(self, x, y, **kw):
        
        self.panel.plot(x, y, **kw)
344976
def make_interactive_tree(matrix=None,labels=None):
    '''
    '''
    from scipy.cluster.hierarchy import (
        dendrogram, 
        linkage,
        to_tree
    )

    d3 = None
    from scipy.cluster.hierarchy import cophenet
    from scipy.spatial.distance import pdist

    if isinstance(matrix,pandas.DataFrame):
        Z = linkage(matrix, 'ward') # clusters
        T = to_tree(Z, rd=False)

        if labels == None:
            labels = matrix.index.tolist()
        lookup = dict(zip(range(len(labels)), labels))

        # Create a dendrogram object without plotting
        dend = dendrogram(Z,no_plot=True,
                      orientation="right",
                      leaf_rotation=90.,  # rotates the x axis labels
                      leaf_font_size=8.,  # font size for the x axis labels
                      labels=labels)

        d3 = dict(children=[], name="root")
        add_node(T, d3)
        label_tree(d3["children"][0],lookup)
    else:
        bot.warning('Please provide data as pandas Data Frame.')
    return d3
1223799
def plot_line(axes, fname, ltype):
    """"""
    x = np.genfromtxt(fname, unpack=True)
    axes.plot(x[0], x[1], ltype)
1082615
def plot(self, numPoints=100):
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    # generate cylinder
    x = np.linspace(- self.dimensions[0]/2., self.dimensions[0]/2., numPoints)
    y = np.linspace(- self.dimensions[1]/2., self.dimensions[1]/2., numPoints)
    z = np.linspace(- self.dimensions[2]/2., self.dimensions[2]/2., numPoints)

    # plot
    Xc, Yc = np.meshgrid(x, y)
    ax.plot_surface(Xc, Yc, -self.dimensions[2]/2,
                    alpha=0.2, rstride=20, cstride=10)
    ax.plot_surface(Xc, Yc, self.dimensions[2]/2,
                    alpha=0.2, rstride=20, cstride=10)
    Yc, Zc = np.meshgrid(y, z)
    ax.plot_surface(-self.dimensions[0]/2, Yc, Zc,
                    alpha=0.2, rstride=20, cstride=10)
    ax.plot_surface(self.dimensions[0]/2, Yc, Zc,
                    alpha=0.2, rstride=20, cstride=10)
    Xc, Zc = np.meshgrid(x, z)
    ax.plot_surface(Xc, -self.dimensions[1]/2, Zc,
                    alpha=0.2, rstride=20, cstride=10)
    ax.plot_surface(Xc, self.dimensions[1]/2, Zc,
                    alpha=0.2, rstride=20, cstride=10)

    ax.set_xlabel("X")
    ax.set_ylabel("Y")
    ax.set_zlabel("Z")

    plt.title("{}".format(self))
    return fig, ax