returns vgp scatter for data set
329774
def get_Sb(data):
    
    Sb, N = 0., 0.
    for rec in data:
        delta = 90. - abs(rec['vgp_lat'])
        if rec['average_k'] != 0:
            k = rec['average_k']
            L = rec['average_lat'] * np.pi / 180.  # latitude in radians
            Nsi = rec['average_nn']
            K = old_div(k, (2. * (1. + 3. * np.sin(L)**2) /
                            (5. - 3. * np.sin(L)**2)))
            Sw = old_div(81., np.sqrt(K))
        else:
            Sw, Nsi = 0, 1.
        Sb += delta**2. - old_div((Sw**2), Nsi)
        N += 1.
    return np.sqrt(old_div(Sb, float(N - 1.)))
123374
def load_scatter_table(self, fn):
        
        data = pickle.load(file(fn))

        if ("version" not in data) or (data["version"]!=tmatrix_aux.VERSION):
            warnings.warn("Loading data saved with another version.", Warning)

        (self.num_points, self.D_max, self._psd_D, self._S_table, 
            self._Z_table, self._angular_table, self._m_table, 
            self.geometries) = data["psd_scatter"]
        return (data["time"], data["description"])
613574
def scatter_single(ax, Y, *args, **kwargs):
    
    if 's' not in kwargs:
        kwargs['s'] = 2 if Y.shape[0] > 500 else 10
    if 'edgecolors' not in kwargs:
        kwargs['edgecolors'] = 'face'
    ax.scatter(Y[:, 0], Y[:, 1], **kwargs, rasterized=settings._vector_friendly)
    ax.set_xticks([])
    ax.set_yticks([])
869709
def RDvcgt(s):
    """"""
    # See
    # http://developer.apple.com/documentation/GraphicsImaging/Reference/ColorSync_Manager/Reference/reference.html#//apple_ref/c/tdef/CMVideoCardGammaType
    assert s[0:4] == 'vcgt'
    tagtype, = struct.unpack('>L', s[8:12])
    if tagtype != 0:
        return s[8:]
    if tagtype == 0:
        # Table.
        channels, count, size = struct.unpack('>3H', s[12:18])
        if size == 1:
            fmt = 'B'
        elif size == 2:
            fmt = 'H'
        else:
            return s[8:]
        n = len(s[18:]) // size
        t = struct.unpack('>%d%s' % (n, fmt), s[18:])
        t = group(t, count)
        return size, t
    return s[8:]
575256
def _get_gosubdagplotnts(self, hdrgo, usrgos, pltargs, go2parentids):
        """"""
        dotgraphs = []
        go2color = pltargs.get_go2color_inst(hdrgo)
        # namedtuple fields: hdrgo gosubdag tot_usrgos parentcnt desc
        ntpltgo0 = self._get_pltdag_ancesters(hdrgo, usrgos, desc="")
        ntpltgo1 = self._get_pltdag_path_hdr(hdrgo, usrgos, desc="pruned")
        num_go0 = len(ntpltgo0.gosubdag.go2obj)
        num_go1 = len(ntpltgo1.gosubdag.go2obj)
        title = "{GO} {NAME}; {N} GO sources".format(
            GO=hdrgo,
            NAME=self.gosubdag.go2obj[hdrgo].name,
            N=len(ntpltgo0.gosubdag.go_sources))
        # print("PltGroupedGos::_get_gosubdagplotnts TITLE", title)
        if num_go0 < pltargs.max_gos:
            # print("PltGroupedGos::_get_gosubdagplotnts ntpltgo0 ALWAYS IF NOT TOO BIG")
            dotgraphs.append(self._get_gosubdagplotnt(ntpltgo0, title, go2color, pltargs))
        # PLOT A: Plot the entire GO ID group under GO header, hdrgo, if not too big
        if num_go0 < pltargs.max_gos and \
            ntpltgo0.tot_usrgos == ntpltgo1.tot_usrgos:
            # print("PltGroupedGos::_get_gosubdagplotnts ntpltgo0 AAAAAAAAAAAAAAAAA")
            dotgraphs.append(self._get_gosubdagplotnt(ntpltgo0, title, go2color, pltargs))
        # PLOT B: Plot only the GO ID group passing thru the GO header, hdrgo, if not too big
        elif num_go1 < pltargs.max_gos and ntpltgo0.tot_usrgos != ntpltgo1.tot_usrgos:
            # print("PltGroupedGos::_get_gosubdagplotnts ntpltgo1(pruned) BBBBBBBBBBBBBBBBB")
            dotgraphs.append(self._get_gosubdagplotnt(ntpltgo1, title, go2color, pltargs))
        # PLOT C: If DAG is large, just print upper portion
        # PLOT D: If DAG is large, just print upper portion passing through the GO header
        elif num_go1 >= pltargs.upper_trigger:
            # print("PltGroupedGos::_get_gosubdagplotnts upper_pruned CCCCCCCCCCCCCCCCC")
            gos_upper = self._get_gos_upper(ntpltgo1, pltargs.max_upper, go2parentids)
            #ntpltgo2 = self._get_pltdag_ancesters(hdrgo, gos_upper, "{BASE}_upper.png")
            ntpltgo3 = self._get_pltdag_path_hdr(hdrgo, gos_upper, "upper_pruned")
            # Middle GO terms chosen to be start points will be green unless reset back
            for goid in gos_upper:
                if goid not in go2color:
                    go2color[goid] = 'white'
            dotgraphs.append(self._get_gosubdagplotnt(ntpltgo3, title, go2color, pltargs))
        else:
            # print("PltGroupedGos::_get_gosubdagplotnts EEEEEEEEEEEEEEEEE")
            self._no_ntplt(ntpltgo0)
        return dotgraphs
603542
function(pixels, data) {
    const pixel = pixels[0];
    const value = vgi(pixel);
    summarize(value, data.counts);
    if (value >= data.threshold) {
      pixel[0] = 0;
      pixel[1] = 255;
      pixel[2] = 0;
      pixel[3] = 128;
    } else {
      pixel[3] = 0;
    }
    return pixel;
  }
1137904
def umap(adata, **kwargs) -> Union[Axes, List[Axes], None]:
    
    return plot_scatter(adata, 'umap', **kwargs)
1133706
def jitterplot(data, positions=None, ax=None, vert=True, scale=0.1,
               **scatter_kwargs):
  '''
  '''
  if ax is None:
    ax = plt.gca()
  if positions is None:
    positions = range(len(data))

  kwargs = dict(marker='.', c='k', alpha=0.75)
  kwargs.update(scatter_kwargs)

  for pos, y in zip(positions, data):
    if scale > 0:
      x = np.random.normal(loc=pos, scale=scale, size=len(y))
    else:
      x = np.zeros_like(y) + pos
    if not vert:
      x, y = y, x
    ax.scatter(x, y, **kwargs)
  return plt.show
1070527
def getRastersAsPngs(self, session, tableName, rasterIds, postGisRampString, rasterField='raster', rasterIdField='id',  cellSize=None, resampleMethod='NearestNeighbour'):
        
        # Validate
        VALID_RESAMPLE_METHODS = ('NearestNeighbour', 'Bilinear', 'Cubic', 'CubicSpline', 'Lanczos')

        # Validate
        if resampleMethod not in VALID_RESAMPLE_METHODS:
            print('RASTER CONVERSION ERROR: {0} is not a valid resampleMethod.'
                  ' Please use either {1}'.format(resampleMethod,
                                                  ', '.join(VALID_RESAMPLE_METHODS)))

        if cellSize is not None:
            if not self.isNumber(cellSize):
                raise ValueError('RASTER CONVERSION ERROR: cellSize must be a number or None.')

        # Convert raster ids into formatted string
        rasterIdsString = '({0})'.format(', '.join(rasterIds))

        if cellSize is not None:
            statement = '''
                        SELECT ST_AsPNG(ST_Transform(ST_ColorMap(ST_Rescale({0}, {5}, '{6}'), 1, '{4}'), 4326, 'Bilinear')) As png
                        FROM {1}
                        WHERE {2} IN {3};
                        '''.format(rasterField, tableName, rasterIdField, rasterIdsString, postGisRampString, cellSize,
                                   resampleMethod)
        else:
            statement = '''
                        SELECT ST_AsPNG(ST_Transform(ST_ColorMap({0}, 1, '{4}'), 4326, 'Bilinear')) As png
                        FROM {1}
                        WHERE {2} IN {3};
                        '''.format(rasterField, tableName, rasterIdField, rasterIdsString, postGisRampString)
        result = session.execute(statement)
        return result
29026
def _packetlist_timeskew_graph(self, ip, **kargs):
    """"""  # noqa: E501

    # Filter TCP segments which source address is 'ip'
    tmp = (self._elt2pkt(x) for x in self.res)
    b = (x for x in tmp if IP in x and x[IP].src == ip and TCP in x)

    # Build a list of tuples (creation_time, replied_timestamp)
    c = []
    tsf = ICMPTimeStampField("", None)
    for p in b:
        opts = p.getlayer(TCP).options
        for o in opts:
            if o[0] == "Timestamp":
                c.append((p.time, tsf.any2i("", o[1][0])))

    # Stop if the list is empty
    if not c:
        warning("No timestamps found in packet list")
        return []

    # Prepare the data that will be plotted
    first_creation_time = c[0][0]
    first_replied_timestamp = c[0][1]

    def _wrap_data(ts_tuple, wrap_seconds=2000):
        """Wrap the list of tuples."""

        ct, rt = ts_tuple  # (creation_time, replied_timestamp)
        X = ct % wrap_seconds
        Y = ((ct - first_creation_time) - ((rt - first_replied_timestamp) / 1000.0))  # noqa: E501

        return X, Y

    data = [_wrap_data(e) for e in c]

    # Mimic the default gnuplot output
    if kargs == {}:
        kargs = MATPLOTLIB_DEFAULT_PLOT_KARGS
    lines = plt.plot(data, **kargs)

    # Call show() if matplotlib is not inlined
    if not MATPLOTLIB_INLINED:
        plt.show()

    return lines
1271330
private Vec[][] makeTemplates(Frame dataset, double[] ratios) {
    Vec anyVec = dataset.anyVec();
    final long[][] espcPerSplit = computeEspcPerSplit(anyVec.espc(), anyVec.length(), ratios);
    final int num = dataset.numCols(); // number of columns in input frame
    final int nsplits = espcPerSplit.length; // number of splits
    final String[][] domains = dataset.domains(); // domains
    final byte[] types = new byte[num];
    int j=0;
    for (Vec v : dataset.vecs()) types[j++] = v.get_type();

    Vec[][] t = new Vec[nsplits][/*num*/]; // resulting vectors for all
    for (int i=0; i<nsplits; i++) {
      // vectors for j-th split
      Key vkey = Vec.newKey();
      int rowLayout = Vec.ESPC.rowLayout(vkey,espcPerSplit[i]);
      t[i] = new Vec(vkey,rowLayout).makeCons(num, 0, domains, types);
    }
    return t;
  }
177059
def visualize_poisson_w(w, labels, filename, method='pca', figsize=(18,10), title='', **scatter_options):
    
    if method == 'pca':
        pca = PCA(2)
        r_dim_red = pca.fit_transform(w.T).T
    elif method == 'tsne':
        pass
    else:
        print("Method is not available. use 'pca' (default) or 'tsne'.")
        return
    visualize_dim_red(r_dim_red, labels, filename, figsize, title, **scatter_options)
1172820
def epomeo_gpx(data_set='epomeo_gpx', sample_every=4):
    """"""
    import gpxpy
    import gpxpy.gpx
    if not data_available(data_set):
        download_data(data_set)
    files = ['endomondo_1', 'endomondo_2', 'garmin_watch_via_endomondo','viewranger_phone', 'viewranger_tablet']

    X = []
    for file in files:
        gpx_file = open(os.path.join(data_path, 'epomeo_gpx', file + '.gpx'), 'r')

        gpx = gpxpy.parse(gpx_file)
        segment = gpx.tracks[0].segments[0]
        points = [point for track in gpx.tracks for segment in track.segments for point in segment.points]
        data = [[(point.time-datetime.datetime(2013,8,21)).total_seconds(), point.latitude, point.longitude, point.elevation] for point in points]
        X.append(np.asarray(data)[::sample_every, :])
        gpx_file.close()
    if pandas_available:
        X = pd.DataFrame(X[0], columns=['seconds', 'latitude', 'longitude', 'elevation'])
        X.set_index(keys='seconds', inplace=True)
    return data_details_return({'X' : X, 'info' : 'Data is an array containing time in seconds, latitude, longitude and elevation in that order.'}, data_set)
852606
def _get_graph_properties(self, plot, element, data, mapping, ranges, style):
        ""
        sources = []
        properties, mappings = {}, {}

        for key in ('scatter_1', self.edge_glyph):
            gdata = data.pop(key, {})
            group_style = dict(style)
            style_group = self._style_groups.get('_'.join(key.split('_')[:-1]))

            with abbreviated_exception():
                group_style = self._apply_transforms(element, gdata, ranges, group_style, style_group)

            # Get source
            source = self._init_datasource(gdata)
            self.handles[key+'_source'] = source
            sources.append(source)

            # Get style
            others = [sg for sg in self._style_groups.values() if sg != style_group]
            glyph_props = self._glyph_properties(
                plot, element, source, ranges, group_style, style_group)
            for k, p in glyph_props.items():
                if any(k.startswith(o) for o in others):
                    continue
                properties[k] = p
            mappings.update(mapping.pop(key, {}))
        properties = {p: v for p, v in properties.items() if p not in ('legend', 'source')}
        properties.update(mappings)

        # Initialize graph layout
        layout = data.pop('layout', {})
        layout = StaticLayoutProvider(graph_layout=layout)
        self.handles['layout_source'] = layout

        return tuple(sources+[layout]), properties
1126199
def offline_plotly_scatter3d(df, x=0, y=1, z=-1):
    
    data = []
    # clusters = []
    colors = ['rgb(228,26,28)', 'rgb(55,126,184)', 'rgb(77,175,74)']

    # df.columns = clean_columns(df.columns)

    x = get_array(df, x, default=0)
    y = get_array(df, y, default=1)
    z = get_array(df, z, default=-1)
    for i in range(len(df['name'].unique())):
        name = df['Name'].unique()[i]
        color = colors[i]
        x = x[pd.np.array(df['name'] == name)]
        y = y[pd.np.array(df['name'] == name)]
        z = z[pd.np.array(df['name'] == name)]

        trace = dict(
            name=name,
            x=x, y=y, z=z,
            type="scatter3d",
            mode='markers',
            marker=dict(size=3, color=color, line=dict(width=0)))
        data.append(trace)

    layout = dict(
        width=800,
        height=550,
        autosize=False,
        title='Iris dataset',
        scene=dict(
            xaxis=dict(
                gridcolor='rgb(255, 255, 255)',
                zerolinecolor='rgb(255, 255, 255)',
                showbackground=True,
                backgroundcolor='rgb(230, 230,230)'
            ),
            yaxis=dict(
                gridcolor='rgb(255, 255, 255)',
                zerolinecolor='rgb(255, 255, 255)',
                showbackground=True,
                backgroundcolor='rgb(230, 230,230)'
            ),
            zaxis=dict(
                gridcolor='rgb(255, 255, 255)',
                zerolinecolor='rgb(255, 255, 255)',
                showbackground=True,
                backgroundcolor='rgb(230, 230,230)'
            ),
            aspectratio=dict(x=1, y=1, z=0.7),
            aspectmode='manual'
        ),
    )

    fig = dict(data=data, layout=layout)

    # IPython notebook
    # plotly.iplot(fig, filename='pandas-3d-iris', validate=False)

    url = plotly.offline.plot(fig, filename='pandas-3d-iris', validate=False)
    return url
322684
def scatter(h1: Histogram1D, **kwargs) -> dict:
    
    shape = kwargs.pop("shape", DEFAULT_SCATTER_SHAPE)
    # size = kwargs.pop("size", DEFAULT_SCATTER_SIZE)

    mark_template = [{
        "type": "symbol",
        "from": {"data": "series"},
        "encode": {
            "enter": {
                "x": {"scale": "xscale", "field": "x"},
                "y": {"scale": "yscale", "field": "y"},
                "shape": {"value": shape},
                # "size": {"value": size},
                "fill": {"scale": "series", "field": "c"},
            },
        }
    }]
    vega = _scatter_or_line(h1, mark_template=mark_template, kwargs=kwargs)
    return vega
1053703
public String getSVGPlotURI() {
    if(plotnum < 0) {
      plotnum = ThumbnailRegistryEntry.registerImage(plot);
    }
    return ThumbnailRegistryEntry.INTERNAL_PREFIX + plotnum;
  }