plots lines and planes on a great  circle with alpha 95 and mean
    deprecated (used in pmagplotlib)
6418
def plot_slnp(fignum, SiteRec, datablock, key):
    
# make the stereonet
    plt.figure(num=fignum)
    plot_net(fignum)
    s = SiteRec['er_site_name']
#
#   plot on the data
#
    coord = SiteRec['site_tilt_correction']
    title = ''
    if coord == '-1':
        title = s + ": specimen coordinates"
    if coord == '0':
        title = s + ": geographic coordinates"
    if coord == '100':
        title = s + ": tilt corrected coordinates"
    DIblock, GCblock = [], []
    for plotrec in datablock:
        if plotrec[key + '_direction_type'] == 'p':  # direction is pole to plane
            GCblock.append(
                (float(plotrec[key + "_dec"]), float(plotrec[key + "_inc"])))
        else:  # assume direction is a directed line
            DIblock.append(
                (float(plotrec[key + "_dec"]), float(plotrec[key + "_inc"])))
    if len(DIblock) > 0:
        plot_di(fignum, DIblock)  # plot directed lines
    if len(GCblock) > 0:
        for pole in GCblock:
            plot_circ(fignum, pole, 90., 'g')  # plot directed lines
#
# put on the mean direction
#
    x, y = [], []
    XY = pmag.dimap(float(SiteRec["site_dec"]), float(SiteRec["site_inc"]))
    x.append(XY[0])
    y.append(XY[1])
    plt.scatter(x, y, marker='d', s=80, c='g')
    plt.title(title)
#
# get the alpha95
#
    Xcirc, Ycirc = [], []
    Da95, Ia95 = pmag.circ(float(SiteRec["site_dec"]), float(
        SiteRec["site_inc"]), float(SiteRec["site_alpha95"]))
    for k in range(len(Da95)):
        XY = pmag.dimap(Da95[k], Ia95[k])
        Xcirc.append(XY[0])
        Ycirc.append(XY[1])
    plt.plot(Xcirc, Ycirc, 'g')
1267497
def main():
    
    fmt,plot='svg',0
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    elif '-f' in sys.argv: # ask for filename
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'r')
        input=f.readlines()
    Data=[]
    for line in input:
        line.replace('\n','')
        if '\t' in line:   # read in the data from standard input
            rec=line.split('\t') # split each line on space to get records
        else:
            rec=line.split() # split each line on space to get records
        Data.append(float(rec[0]))
    
#
    if len(Data) >=10: 
        QQ={'unf1':1}
        pmagplotlib.plot_init(QQ['unf1'],5,5)
        pmagplotlib.plot_qq_unf(QQ['unf1'],Data,'QQ-Uniform') # make plot
    else:
        print('you need N> 10')
        sys.exit()
    pmagplotlib.draw_figs(QQ) 
    files={}
    for key in list(QQ.keys()):
        files[key]=key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        EQ = pmagplotlib.add_borders(EQ,titles,black,purple)
        pmagplotlib.save_plots(QQ,files)
    elif plot==1:
        files['qq']=file+'.'+fmt 
        pmagplotlib.save_plots(QQ,files)
    else:
        ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans=="a": pmagplotlib.save_plots(QQ,files)
979267
def show(cmap, var, vmin=None, vmax=None):
    '''

    '''

    # get variable data
    lat, lon, z, data = read(var)

    fig = plt.figure(figsize=(16, 12))

    # Plot with grayscale
    ax = fig.add_subplot(3, 1, 1)
    map1 = ax.scatter(lon, -z, c=data, cmap='gray', s=10, linewidths=0., vmin=vmin, vmax=vmax)
    plt.colorbar(map1, ax=ax)

    # Plot with jet
    ax = fig.add_subplot(3, 1, 2)
    map1 = ax.scatter(lon, -z, c=data, cmap='jet', s=10, linewidths=0., vmin=vmin, vmax=vmax)
    plt.colorbar(map1, ax=ax)

    # Plot with cmap
    ax = fig.add_subplot(3, 1, 3)
    map1 = ax.scatter(lon, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=vmin, vmax=vmax)
    ax.set_xlabel('Longitude [degrees]')
    ax.set_ylabel('Depth [m]')
    plt.colorbar(map1, ax=ax)

    plt.suptitle(var)
1104019
def plot(x, y, z, color=default_color, **kwargs):
    
    fig = gcf()
    _grow_limits(x, y, z)
    defaults = dict(
        visible_lines=True, color_selected=None, size_selected=1, size=1, connected=True, visible_markers=False
    )
    kwargs = dict(defaults, **kwargs)
    s = ipv.Scatter(x=x, y=y, z=z, color=color, **kwargs)
    s.material.visible = False
    fig.scatters = fig.scatters + [s]
    return s
137127
def plot_circ(fignum, pole, ang, col):
    
    plt.figure(num=fignum)
    D_c, I_c = pmag.circ(pole[0], pole[1], ang)
    X_c_up, Y_c_up = [], []
    X_c_d, Y_c_d = [], []
    for k in range(len(D_c)):
        XY = pmag.dimap(D_c[k], I_c[k])
        if I_c[k] < 0:
            X_c_up.append(XY[0])
            Y_c_up.append(XY[1])
        else:
            X_c_d.append(XY[0])
            Y_c_d.append(XY[1])
    plt.plot(X_c_d, Y_c_d, col + '.', ms=5)
    plt.plot(X_c_up, Y_c_up, 'c.', ms=2)
736619
def plotdmt(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None,
            tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=950, plot_height=500):
    

    fields = ['dm', 'time', 'sizes', 'colors', 'snrs', 'key']

    if not circleinds: circleinds = range(len(data['snrs']))

    # set ranges
    datalen = len(data['dm'])
    inds = circleinds + crossinds + edgeinds
    dm = [data['dm'][i] for i in inds]
    dm_min = min(min(dm), max(dm)/1.2)
    dm_max = max(max(dm), min(dm)*1.2)
    time = [data['time'][i] for i in inds]
    time_min = min(time)
    time_max = max(time)

    source = ColumnDataSource(data = dict({(key, tuple([value[i] for i in circleinds if i not in edgeinds])) 
                                           for (key, value) in data.iteritems() if key in fields}))
    dmt = Figure(plot_width=plot_width, plot_height=plot_height, toolbar_location="left", x_axis_label='Time (s; relative)',
                 y_axis_label='DM (pc/cm3)', x_range=(time_min, time_max), y_range=(dm_min, dm_max), 
                 output_backend='webgl', tools=tools)
    dmt.circle('time', 'dm', size='sizes', fill_color='colors', line_color=None, fill_alpha=0.2, source=source)

    if crossinds:
        sourceneg = ColumnDataSource(data = dict({(key, tuple([value[i] for i in crossinds]))
                                                  for (key, value) in data.iteritems() if key in fields}))
        dmt.cross('time', 'dm', size='sizes', fill_color='colors', line_alpha=0.3, source=sourceneg)

    if edgeinds:
        sourceedge = ColumnDataSource(data = dict({(key, tuple([value[i] for i in edgeinds]))
                                                   for (key, value) in data.iteritems() if key in fields}))
        dmt.circle('time', 'dm', size='sizes', line_color='colors', fill_color='colors', line_alpha=0.5, fill_alpha=0.2, source=sourceedge)
    hover = dmt.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
#        url = '{}/cands_{}_sc@scan-seg@seg-i@candint-dm@dmind-dt@dtind.png'.format(url_path, fileroot)
        url = '{}/cands_{}_@key.png'.format(url_path, fileroot)
        taptool = dmt.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    return dmt
1137904
def umap(adata, **kwargs) -> Union[Axes, List[Axes], None]:
    
    return plot_scatter(adata, 'umap', **kwargs)
26842
def plotGrid(self, numLines=(5,5), lineWidth=1, colour="#777777"):
        
        x1, x2, y1, y2 = mp.axis()
        ra1, dec0 = self.pixToSky(x1, y1)
        ra0, dec1 = self.pixToSky(x2, y2)

        xNum, yNum = numLines
        self.raRange, self.decRange  = self.getRaDecRanges(numLines)

        #import pdb; pdb.set_trace()
        #Guard against Ra of zero within the plot
        a1 = np.abs(ra1-ra0)
        a2 = np.abs( min(ra0, ra1) - (max(ra0, ra1) - 360))
        if a2 < a1:     #Then we straddle 360 degrees in RA
            if ra0 < ra1:
                ra1 -= 360
            else:
                ra0 -= 360


        #Draw lines of constant dec
        lwr = min(ra0, ra1)
        upr = max(ra0, ra1)
        stepX = round((upr-lwr) / float(xNum))
        ra_deg = np.arange(lwr - 3*stepX, upr + 3.5*stepX, 1, dtype=np.float)
        for dec in self.decRange:
            self.plotLine(ra_deg, dec, '-', color = colour, linewidth = lineWidth)


        #Draw lines of const ra
        lwr = min(dec0, dec1)
        upr = max(dec0, dec1)
        stepY = round((upr-lwr) / float(yNum))
        dec_deg = np.arange(dec0 - 3*stepY, dec1 + 3.5*stepY, 1, dtype=np.float)
        for ra in self.raRange:
            self.plotLine(ra, dec_deg, '-', color = colour, linewidth = lineWidth)

        mp.axis([x1, x2, y1, y2])
1361884
def plotSkymapCatalog(lon,lat,**kwargs):
    
    fig = plt.figure()
    ax = plt.subplot(111,projection=projection)
    drawSkymapCatalog(ax,lon,lat,**kwargs)
544039
def cmd():
    
    sdat = StagyyData(conf.core.path)
    sovs = set_of_vars(conf.field.plot)
    minmax = {}
    if conf.plot.cminmax:
        conf.plot.vmin = None
        conf.plot.vmax = None
        for step in sdat.walk.filter(snap=True):
            for var, _ in sovs:
                if var in step.fields:
                    if var in phyvars.FIELD:
                        dim = phyvars.FIELD[var].dim
                    else:
                        dim = phyvars.FIELD_EXTRA[var].dim
                    field, _ = sdat.scale(step.fields[var], dim)
                    if var in minmax:
                        minmax[var] = (min(minmax[var][0], np.nanmin(field)),
                                       max(minmax[var][1], np.nanmax(field)))
                    else:
                        minmax[var] = np.nanmin(field), np.nanmax(field)
    for step in sdat.walk.filter(snap=True):
        for var in sovs:
            if var[0] not in step.fields:
                print("'{}' field on snap {} not found".format(var[0],
                                                               step.isnap))
                continue
            opts = {}
            if var[0] in minmax:
                opts = dict(vmin=minmax[var[0]][0], vmax=minmax[var[0]][1])
            fig, axis, _, _ = plot_scalar(step, var[0], **opts)
            if valid_field_var(var[1]):
                plot_iso(axis, step, var[1])
            elif var[1]:
                plot_vec(axis, step, var[1])
            oname = '{}_{}'.format(*var) if var[1] else var[0]
            misc.saveplot(fig, oname, step.isnap)
748811
def plotSolidAngleCMD(self):
        
        msg = "'%s.plotSolidAngleCMD': ADW 2018-05-05"%self.__class__.__name__
        DeprecationWarning(msg)

        import ugali.utils.plotting        
        ugali.utils.plotting.twoDimensionalHistogram('mask', 'color', 'magnitude',
                                                     self.solid_angle_cmd,
                                                     self.roi.bins_color,
                                                     self.roi.bins_mag,
                                                     lim_x = [self.roi.bins_color[0],
                                                              self.roi.bins_color[-1]],
                                                     lim_y = [self.roi.bins_mag[-1],
                                                              self.roi.bins_mag[0]])
1189436
def great_circle_Npoints(lonlat1r, lonlat2r, N):
    

    ratio = np.linspace(0.0,1.0, N).reshape(-1,1)


    xyz1 = lonlat2xyz(lonlat1r[0], lonlat1r[1])
    xyz2 = lonlat2xyz(lonlat2r[0], lonlat2r[1])

    mids = ratio * xyz2 + (1.0-ratio) * xyz1
    norm = np.sqrt((mids**2).sum(axis=1))
    xyzN = mids / norm.reshape(-1,1)

    lonlatN = xyz2lonlat( xyzN[:,0], xyzN[:,1], xyzN[:,2])

    return lonlatN
1266211
def plot_phens(phen_grid, **kwargs):
    
    denom, palette = get_kwargs(phen_grid, kwargs, True)

    grid = color_grid(phen_grid, palette, denom)

    for i in range(len(grid)):
        for j in range(len(grid[i])):
            if grid[i][j] != -1 and tuple(grid[i][j]) != -1:
                plt.gca().add_patch(plt.Circle((j, i),
                                    radius=.3, lw=1, ec="black",
                                    facecolor=grid[i][j], zorder=2))
421252
def lines(self, Width=1, Color='k'):
        '''
        
        '''
        self.axes.clear()

        # self.axes.set_xlim(-90, 450)
        self.axes.set_ylim(0, 90)

        titles = list('NWSE')

        titles = ['N', '330', '300', 'W', '240', '210', 'S', '150', '120', 'E', '60', '30']
        self.n = len(titles)
        self.angles = np.arange(90, 90 + 360, 360.0 / self.n)

        self.angles = np.array([90., 120., 150., 180., 210., 240., 270., 300., 330.,
                                360., 30., 60.])
        self.axes.set_thetagrids(self.angles, labels=titles, fontsize=14)

        raw = self._df

        Data = []
        Labels = []


        if (int(self.type_slider.value()) == 0):
            list1 = [self.eqan(x) for x in range(15, 90, 15)]
        else:
            list1 = [self.eqar(x) for x in range(15, 90, 15)]

        list2 = [str(x) for x in range(15, 90, 15)]
        self.axes.set_rgrids(list1, list2)

        for i in range(len(raw)):
            Data.append([raw.at[i, 'Dip'], raw.at[i, 'Dip-Angle'], raw.at[i, 'Color'],
                         raw.at[i, 'Width'], raw.at[i, 'Alpha'], raw.at[i, 'Label']])
            Dip = raw.at[i, 'Dip']
            Dip_Angle = raw.at[i, 'Dip-Angle']

            Label = raw.at[i, 'Label']
            if (Label not in Labels):
                Labels.append(Label)
            else:
                Label = ''

            Width = 1
            Color = 'red'
            Alpha = 0.8
            Marker = 'o'
            Size = 50

            Setting = [Width, Color, Alpha, Marker, Size]

            Width = raw.at[i, 'Width']
            Color = raw.at[i, 'Color']
            Alpha = raw.at[i, 'Alpha']
            Marker = raw.at[i, 'Marker']
            Size = raw.at[i, 'Size']

            if (Color not in Setting or Color != ''):
                Width = raw.at[i, 'Width']
                Color = raw.at[i, 'Color']
                Alpha = raw.at[i, 'Alpha']
                Marker = raw.at[i, 'Marker']
                Size = raw.at[i, 'Size']

                Setting = [Width, Color, Alpha, Marker, Size]
            r = np.arange(Dip - 90, Dip + 91, 1)
            BearR = [np.radians(-A + 90) for A in r]

            if (int(self.type_slider.value()) == 0):
                Line = (self.eqan(self.getangular(Dip_Angle, Dip, r)))
            else:
                Line = (self.eqar(self.getangular(Dip_Angle, Dip, r)))

            self.axes.plot(BearR, Line, color=Color, linewidth=Width, alpha=Alpha, label=Label)

        # self.axes.thetagrids(range(360 + 90, 0 + 90, -30), [str(x) for x in range(0, 360, 30)])

        if (self.legend_cb.isChecked()):
            self.axes.legend(bbox_to_anchor=(1.5, 1), loc=2, borderaxespad=0, prop=fontprop)
249997
def diag(ax=None, linecolor='0.0', linestyle='--', **kwargs):
    """"""
    ax = get_ax(ax)
    xy_min = np.min((ax.get_xlim(), ax.get_ylim()))
    xy_max = np.max((ax.get_ylim(), ax.get_xlim()))
    return ax.plot([xy_min, xy_max], [xy_min, xy_max],
                   ls=linestyle,
                   c=linecolor,
                   **kwargs)
1314751
def plot_campaign_outline(self, campaign=0, facecolor="#666666", text=None, dashed=False):
        
        try:
            from astropy.coordinates import SkyCoord
        except ImportError:
            logger.error("You need to install AstroPy for this feature.")
            return None
        # The outline is composed of two filled rectangles,
        # defined by the first coordinate of the corner of four channels each
        fov = getKeplerFov(campaign)
        corners = fov.getCoordsOfChannelCorners()
        for rectangle in [[4, 75, 84, 11], [15, 56, 71, 32]]:
            ra_outline, dec_outline = [], []
            for channel in rectangle:
                idx = np.where(corners[::, 2] == channel)
                ra_outline.append(corners[idx, 3][0][0])
                dec_outline.append(corners[idx, 4][0][0])

            crd = SkyCoord(ra_outline, dec_outline, unit='deg')
            l = crd.galactic.l.deg
            if campaign not in [4, 13, 1713]:
                l[l > 180] -= 360
            l, b = list(l), list(crd.galactic.b.deg)
            if dashed:
                myfill = self.ax.fill(l + l[:1],
                                      b + b[:1],
                                      facecolor=facecolor, zorder=151, lw=2, ls='dashed',
                                      edgecolor='white')
                # myfill = self.ax.plot(l + l[:1],
                #                      b + b[:1],
                #                      zorder=200, lw=2,
                #                      ls='dotted', color='white')
            else:
                myfill = self.ax.fill(l + l[:1],
                                      b + b[:1],
                                      facecolor=facecolor, zorder=151, lw=0)
        # Print the campaign number on top of the outline
        ra, dec, roll = fov.getBoresight()
        gal = SkyCoord(ra, dec, unit='deg').galactic
        l, b = gal.l.deg, gal.b.deg
        if l > 180:
            l -= 360
        if text is None:
            text = "{}".format(campaign)
        self.ax.text(l, b, text,
                     fontsize=14, color="white", ha="center", va="center",
                     zorder=255)
        return myfill
411778
def VarCircle(XY, Par):  # must have at least 4 sets of xy points or else division by zero occurs
    
    if type(XY) != numpy.ndarray:
        XY = numpy.array(XY)
    n = len(XY)
    if n < 4:
        raise Warning("Circle cannot be calculated with less than 4 data points.  Please include more data")
    Dx = XY[:,0] - Par[0]
    Dy = XY[:,1] - Par[1]
    D = numpy.sqrt(Dx * Dx + Dy * Dy) - Par[2]
    result = old_div(numpy.dot(D, D),(n-3))
    return result