query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
scatter plot
python
def plot_scatter(f, xs, ys, size, pch, colour, title): """ Form a complex number. Arguments: f -- comma delimited file w/ x,y coordinates xs -- if f not specified this is a file w/ x coordinates ys -- if f not specified this is a filew / y coordinates size -- size of the plot pch -- shape of the points (any character) colour -- colour of the points title -- title of the plot """ cs = None if f: if isinstance(f, str): with open(f) as fh: data = [tuple(line.strip().split(',')) for line in fh] else: data = [tuple(line.strip().split(',')) for line in f] xs = [float(i[0]) for i in data] ys = [float(i[1]) for i in data] if len(data[0]) > 2: cs = [i[2].strip() for i in data] elif isinstance(xs, list) and isinstance(ys, list): pass else: with open(xs) as fh: xs = [float(str(row).strip()) for row in fh] with open(ys) as fh: ys = [float(str(row).strip()) for row in fh] _plot_scatter(xs, ys, size, pch, colour, title, cs)
https://github.com/glamp/bashplotlib/blob/f7533172c4dc912b5accae42edd5c0f655d7468f/bashplotlib/scatterplot.py#L52-L84
scatter plot
python
def scatter(self, *args, **kwargs): """Add a scatter plot.""" cls = _make_class(ScatterVisual, _default_marker=kwargs.pop('marker', None), ) return self._add_item(cls, *args, **kwargs)
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/plot.py#L153-L158
scatter plot
python
def scatterplot(self, x, y, **kw): """plot after clearing current plot """ self.panel.scatterplot(x, y, **kw)
https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/wxmplot/plotframe.py#L45-L47
scatter plot
python
def _scatter(self): """plot a scatter plot of count vs. elapsed. For internal use only""" plt.scatter(self.count_arr, self.elapsed_arr) plt.title('{}: Count vs. Elapsed'.format(self.name)) plt.xlabel('Items') plt.ylabel('Seconds')
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/output/plot.py#L62-L68
scatter plot
python
def scatter(h1: Histogram1D, **kwargs) -> dict: """Scatter plot of 1D histogram values. Points are horizontally placed in bin centers. Parameters ---------- shape : str """ 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
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/vega.py#L244-L270
scatter plot
python
def plot_pc_scatter(self, pc1, pc2, v=True, subset=None, ax=None, color=None, s=None, marker=None, color_name=None, s_name=None, marker_name=None): """ Make a scatter plot of two principal components. You can create differently colored, sized, or marked scatter points. Parameters ---------- pc1 : str String of form PCX where X is the number of the principal component you want to plot on the x-axis. pc2 : str String of form PCX where X is the number of the principal component you want to plot on the y-axis. v : bool If True, use the v matrix for plotting the principal components (typical if input data was genes as rows and samples as columns). If False, use the u matrix. subset : list Make the scatter plot using only a subset of the rows of u or v. ax : matplotlib.axes Plot the scatter plot on this axis. color : pandas.Series Pandas series containing a categorical variable to color the scatter points. Currently limited to 10 distinct values (colors). s : pandas.Series Pandas series containing a categorical variable to size the scatter points. Currently limited to 7 distinct values (sizes). marker : pandas.Series Pandas series containing a categorical variable to choose the marker type for the scatter points. Currently limited to 21 distinct values (marker styles). color_name : str Name for the color legend if a categorical variable for color is provided. s_name : str Name for the size legend if a categorical variable for size is provided. marker_name : str Name for the marker legend if a categorical variable for marker type is provided. Returns ------- ax : matplotlib.axes._subplots.AxesSubplot Scatter plot axis. TODO: Add ability to label points. """ import matplotlib.pyplot as plt if v: df = self.v else: df = self.u if color is not None: colormap = pd.Series(dict(zip(set(color.values), tableau20[0:2 * len(set(color)):2]))) color = pd.Series([colormap[x] for x in color.values], index=color.index) color_legend = True if not color_name: color_name = color.index.name else: color = pd.Series([tableau20[0]] * df.shape[0], index=df.index) color_legend = False if s is not None: smap = pd.Series(dict(zip( set(s.values), range(30, 351)[0::50][0:len(set(s)) + 1]))) s = pd.Series([smap[x] for x in s.values], index=s.index) s_legend = True if not s_name: s_name = s.index.name else: s = pd.Series(30, index=df.index) s_legend = False markers = ['o', '*', 's', 'v', '+', 'x', 'd', 'p', '2', '<', '|', '>', '_', 'h', '1', '2', '3', '4', '8', '^', 'D'] if marker is not None: markermap = pd.Series(dict(zip(set(marker.values), markers))) marker = pd.Series([markermap[x] for x in marker.values], index=marker.index) marker_legend = True if not marker_name: marker_name = marker.index.name else: marker = pd.Series('o', index=df.index) marker_legend = False if ax is None: fig, ax = plt.subplots(1, 1) for m in set(marker.values): mse = marker[marker == m] cse = color[mse.index] sse = s[mse.index] ax.scatter(df.ix[mse.index, pc1], df.ix[mse.index, pc2], s=sse.values, color=list(cse.values), marker=m, alpha=0.8) ax.set_title('{} vs. {}'.format(pc1, pc2)) ax.set_xlabel(pc1) ax.set_ylabel(pc2) if color_legend: legend_rects = make_color_legend_rects(colormap) for r in legend_rects: ax.add_patch(r) lgd = ax.legend(legend_rects.values, labels=legend_rects.index, title=color_name, loc='upper left', bbox_to_anchor=(1, 1)) if s_legend: if lgd: lgd = ax.add_artist(lgd) xa, xb = ax.get_xlim() ya, yb = ax.get_ylim() for i in smap.index: ax.scatter([xb + 1], [yb + 1], marker='o', s=smap[i], color='black', label=i) lgd = ax.legend(title=s_name, loc='center left', bbox_to_anchor=(1, 0.5)) ax.set_xlim(xa, xb) ax.set_ylim(ya, yb) if marker_legend: if lgd: lgd = ax.add_artist(lgd) xa, xb = ax.get_xlim() ya, yb = ax.get_ylim() for i in markermap.index: t = ax.scatter([xb + 1], [yb + 1], marker=markermap[i], s=sse.min(), color='black', label=i) handles, labels = ax.get_legend_handles_labels() if s_legend: handles = handles[len(smap):] labels = labels[len(smap):] lgd = ax.legend(handles, labels, title=marker_name, loc='lower left', bbox_to_anchor=(1, 0)) ax.set_xlim(xa, xb) ax.set_ylim(ya, yb) # fig.tight_layout() return fig, ax
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/analysis.py#L755-L909
scatter plot
python
def scatter_nb(self,xdata,ydata=[],trendline=False): '''Graphs a scatter plot and embeds it in a Jupyter notebook. See 'help(figure.scatter)' for more info.''' self.scatter(xdata,ydata,trendline)
https://github.com/Dfenestrator/GooPyCharts/blob/57117f213111dfe0401b1dc9720cdba8a23c3028/gpcharts.py#L561-L563
scatter plot
python
def create_scatterplot(df): """ create a mg line plot Args: df (pandas.DataFrame): data to plot """ fig = Figure("/mg/scatter/", "mg_scatter") fig.layout.set_size(width=450, height=200) fig.layout.set_margin(left=40, right=40) fig.graphics.animate_on_load() init_params = {"Data": "Steps"} def get_data(): y = request.args.get("Data", "Steps") return jsonify(ScatterPlot.to_json(df, "Steps", y)) # Make a histogram with 20 bins return ScatterPlot(df, fig, "Steps", "Distance", init_params={}, route_func=get_data)
https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/examples/metricsgraphics/project/buildui.py#L37-L56
scatter plot
python
def scatter(adata=None, x=None, y=None, basis=None, vkey=None, color=None, use_raw=None, layer=None, color_map=None, colorbar=True, palette=None, size=None, alpha=None, linewidth=None, perc=None, sort_order=True, groups=None, components=None, projection='2d', legend_loc='none', legend_fontsize=None, legend_fontweight=None, right_margin=None, left_margin=None, xlabel=None, ylabel=None, title=None, fontsize=None, figsize=None, dpi=None, frameon=None, show=True, save=None, ax=None, zorder=None, ncols=None, **kwargs): """\ Scatter plot along observations or variables axes. Arguments --------- adata: :class:`~anndata.AnnData` Annotated data matrix. x: `str`, `np.ndarray` or `None` (default: `None`) x coordinate y: `str`, `np.ndarray` or `None` (default: `None`) y coordinate {scatter} Returns ------- If `show==False` a `matplotlib.Axis` """ scatter_kwargs = {"use_raw": use_raw, "sort_order": sort_order, "alpha": alpha, "components": components, "projection": projection, "legend_loc": legend_loc, "groups": groups, "palette": palette, "legend_fontsize": legend_fontsize, "legend_fontweight": legend_fontweight, "right_margin": right_margin, "left_margin": left_margin, "show": False, "save": None} adata = AnnData(np.stack([x, y]).T) if adata is None and (x is not None and y is not None) else adata colors, layers, bases = make_unique_list(color, allow_array=True), make_unique_list(layer), make_unique_list(basis) multikey = colors if len(colors) > 1 else layers if len(layers) > 1 else bases if len(bases) > 1 else None if multikey is not None: if isinstance(title, (list, tuple)): title *= int(np.ceil(len(multikey) / len(title))) ncols = len(multikey) if ncols is None else min(len(multikey), ncols) nrows = int(np.ceil(len(multikey) / ncols)) figsize = rcParams['figure.figsize'] if figsize is None else figsize for i, gs in enumerate( pl.GridSpec(nrows, ncols, pl.figure(None, (figsize[0] * ncols, figsize[1] * nrows), dpi=dpi))): if i < len(multikey): scatter(adata, x=x, y=y, size=size, linewidth=linewidth, xlabel=xlabel, ylabel=ylabel, vkey=vkey, color_map=color_map, colorbar=colorbar, perc=perc, frameon=frameon, ax=pl.subplot(gs), zorder=zorder, color=colors[i] if len(colors) > 1 else color, layer=layers[i] if len(layers) > 1 else layer, basis=bases[i] if len(bases) > 1 else basis, title=title[i] if isinstance(title, (list, tuple)) else title, **scatter_kwargs, **kwargs) savefig_or_show('' if basis is None else basis, dpi=dpi, save=save, show=show) if not show: return ax else: color, layer, basis = colors[0], layers[0], bases[0] color = default_color(adata) if color is None else color color_map = default_color_map(adata, color) if color_map is None else color_map is_embedding = ((x is None) | (y is None)) and basis not in adata.var_names basis = default_basis(adata) if basis is None and is_embedding else basis size = default_size(adata) if size is None else size linewidth = 1 if linewidth is None else linewidth frameon = frameon if frameon is not None else True if not is_embedding else settings._frameon if projection == '3d': from mpl_toolkits.mplot3d import Axes3D ax = pl.figure(None, figsize, dpi=dpi).gca(projection=projection) if ax is None else ax else: ax = pl.figure(None, figsize, dpi=dpi).gca() if ax is None else ax if is_categorical(adata, color) and is_embedding: from scanpy.api.pl import scatter as scatter_ ax = scatter_(adata, basis=basis, color=color, color_map=color_map, size=size, frameon=frameon, ax=ax, title=title, **scatter_kwargs, **kwargs) else: if basis in adata.var_names: xkey, ykey = ('spliced', 'unspliced') if use_raw or 'Ms' not in adata.layers.keys() else ('Ms', 'Mu') x = make_dense(adata[:, basis].layers[xkey]) y = make_dense(adata[:, basis].layers[ykey]) xlabel, ylabel = 'spliced', 'unspliced' title = basis if title is None else title elif is_embedding: X_emb = adata.obsm['X_' + basis][:, get_components(components, basis)] x, y = X_emb[:, 0], X_emb[:, 1] elif isinstance(x, str) and isinstance(y, str) and x in adata.var_names and y in adata.var_names: x = adata[:, x].layers[layer] if layer in adata.layers.keys() else adata[:, x].X y = adata[:, y].layers[layer] if layer in adata.layers.keys() else adata[:, y].X if basis in adata.var_names and isinstance(color, str) and color in adata.layers.keys(): c = interpret_colorkey(adata, basis, color, perc) else: c = interpret_colorkey(adata, color, layer, perc) if layer is not None and 'velocity' in layer and isinstance(color, str) and color in adata.var_names: ub = np.percentile(np.abs(c), 98) kwargs.update({"vmin": -ub, "vmax": ub}) if layer is not None and ('spliced' in layer or 'Ms' in layer or 'Mu' in layer) \ and isinstance(color, str) and color in adata.var_names: ub = np.percentile(c, 98) kwargs.update({"vmax": ub}) if groups is not None or np.any(pd.isnull(c)): zorder = 0 if zorder is None else zorder ax = scatter(adata, basis=basis, color='lightgrey', ax=ax, zorder=zorder, **scatter_kwargs) zorder += 1 if basis in adata.var_names: fits = show_linear_fit(adata, basis, vkey, xkey, linewidth) from .simulation import show_full_dynamics if 'true_alpha' in adata.var.keys(): fit = show_full_dynamics(adata, basis, 'true', use_raw, linewidth) fits.append(fit) if 'fit_alpha' in adata.var.keys() and (vkey is None or 'dynamics' in vkey): fit = show_full_dynamics(adata, basis, 'fit', use_raw, linewidth, show_assigments=vkey is not None and 'assignment' in vkey) fits.append(fit) if vkey is not None and 'density' in vkey: show_density(x, y) if len(fits) > 0 and legend_loc is not None: pl.legend(fits, loc=legend_loc if legend_loc is not 'none' else 'lower right') if use_raw and perc is not None: pl.xlim(right=np.percentile(x, 99.9 if not isinstance(perc, int) else perc) * 1.05) pl.ylim(top=np.percentile(y, 99.9 if not isinstance(perc, int) else perc) * 1.05) pl.scatter(x, y, c=c, cmap=color_map, s=size, alpha=alpha, edgecolors='none', marker='.', zorder=zorder, **kwargs) set_label(xlabel, ylabel, fontsize, basis) set_title(title, layer, color, fontsize) ax = update_axes(ax, fontsize, is_embedding, frameon) if colorbar and not is_categorical(adata, color): set_colorbar(ax) savefig_or_show('' if basis is None else basis, dpi=dpi, save=save, show=show) if not show: return ax
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/plotting/scatter.py#L15-L145
scatter plot
python
def scatter(self, *args, **kwargs): ''' Creates a scatter plot of the given x and y items. Args: x (str or seq[float]) : values or field names of center x coordinates y (str or seq[float]) : values or field names of center y coordinates size (str or list[float]) : values or field names of sizes in screen units marker (str, or list[str]): values or field names of marker types color (color value, optional): shorthand to set both fill and line color source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. **kwargs: :ref:`userguide_styling_line_properties` and :ref:`userguide_styling_fill_properties` Examples: >>> p.scatter([1,2,3],[4,5,6], marker="square", fill_color="red") >>> p.scatter("data1", "data2", marker="mtype", source=data_source, ...) .. note:: When passing ``marker="circle"`` it is also possible to supply a ``radius`` value in data-space units. When configuring marker type from a data source column, *all* markers incuding circles may only be configured with ``size`` in screen units. ''' marker_type = kwargs.pop("marker", "circle") if isinstance(marker_type, string_types) and marker_type in _MARKER_SHORTCUTS: marker_type = _MARKER_SHORTCUTS[marker_type] # The original scatter implementation allowed circle scatters to set a # radius. We will leave this here for compatibility but note that it # only works when the marker type is "circle" (and not referencing a # data source column). Consider deprecating in the future. if marker_type == "circle" and "radius" in kwargs: return self.circle(*args, **kwargs) else: return self._scatter(*args, marker=marker_type, **kwargs)
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L757-L801
scatter plot
python
def twoDimensionalScatter(title, title_x, title_y, x, y, lim_x = None, lim_y = None, color = 'b', size = 20, alpha=None): """ Create a two-dimensional scatter plot. INPUTS """ plt.figure() plt.scatter(x, y, c=color, s=size, alpha=alpha, edgecolors='none') plt.xlabel(title_x) plt.ylabel(title_y) plt.title(title) if type(color) is not str: plt.colorbar() if lim_x: plt.xlim(lim_x[0], lim_x[1]) if lim_y: plt.ylim(lim_y[0], lim_y[1])
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L105-L127
scatter plot
python
def plot(self, numPoints=100): """ Plots the object in a 3D scatter. This method should be overriden when possible. This default behavior simply samples numPoints points from the object and plots them in a 3d scatter. """ fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for feature in self._FEATURES: for _ in xrange(numPoints): x, y, z = tuple(self.sampleLocationFromFeature(feature)) ax.scatter(x, y, z, marker=".") ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.title("{}".format(self)) return fig, ax
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/physical_object_base.py#L124-L145
scatter plot
python
def plot(x, y, z, color=default_color, **kwargs): """Plot a line in 3d. :param x: {x} :param y: {y} :param z: {z} :param color: {color} :param kwargs: extra arguments passed to the Scatter constructor :return: :any:`Scatter` """ 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
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L480-L499
scatter plot
python
def plot(self, x=None, y=None, z=None, what="count(*)", vwhat=None, reduce=["colormap"], f=None, normalize="normalize", normalize_axis="what", vmin=None, vmax=None, shape=256, vshape=32, limits=None, grid=None, colormap="afmhot", # colors=["red", "green", "blue"], figsize=None, xlabel=None, ylabel=None, aspect="auto", tight_layout=True, interpolation="nearest", show=False, colorbar=True, colorbar_label=None, selection=None, selection_labels=None, title=None, background_color="white", pre_blend=False, background_alpha=1., visual=dict(x="x", y="y", layer="z", fade="selection", row="subspace", column="what"), smooth_pre=None, smooth_post=None, wrap=True, wrap_columns=4, return_extra=False, hardcopy=None): """Viz data in a 2d histogram/heatmap. Declarative plotting of statistical plots using matplotlib, supports subplots, selections, layers. Instead of passing x and y, pass a list as x argument for multiple panels. Give what a list of options to have multiple panels. When both are present then will be origanized in a column/row order. This methods creates a 6 dimensional 'grid', where each dimension can map the a visual dimension. The grid dimensions are: * x: shape determined by shape, content by x argument or the first dimension of each space * y: ,, * z: related to the z argument * selection: shape equals length of selection argument * what: shape equals length of what argument * space: shape equals length of x argument if multiple values are given By default, this its shape is (1, 1, 1, 1, shape, shape) (where x is the last dimension) The visual dimensions are * x: x coordinate on a plot / image (default maps to grid's x) * y: y ,, (default maps to grid's y) * layer: each image in this dimension is blended togeher to one image (default maps to z) * fade: each image is shown faded after the next image (default mapt to selection) * row: rows of subplots (default maps to space) * columns: columns of subplot (default maps to what) All these mappings can be changes by the visual argument, some examples: >>> df.plot('x', 'y', what=['mean(x)', 'correlation(vx, vy)']) Will plot each 'what' as a column. >>> df.plot('x', 'y', selection=['FeH < -3', '(FeH >= -3) & (FeH < -2)'], visual=dict(column='selection')) Will plot each selection as a column, instead of a faded on top of each other. :param x: Expression to bin in the x direction (by default maps to x), or list of pairs, like [['x', 'y'], ['x', 'z']], if multiple pairs are given, this dimension maps to rows by default :param y: y (by default maps to y) :param z: Expression to bin in the z direction, followed by a :start,end,shape signature, like 'FeH:-3,1:5' will produce 5 layers between -10 and 10 (by default maps to layer) :param what: What to plot, count(*) will show a N-d histogram, mean('x'), the mean of the x column, sum('x') the sum, std('x') the standard deviation, correlation('vx', 'vy') the correlation coefficient. Can also be a list of values, like ['count(x)', std('vx')], (by default maps to column) :param reduce: :param f: transform values by: 'identity' does nothing 'log' or 'log10' will show the log of the value :param normalize: normalization function, currently only 'normalize' is supported :param normalize_axis: which axes to normalize on, None means normalize by the global maximum. :param vmin: instead of automatic normalization, (using normalize and normalization_axis) scale the data between vmin and vmax to [0, 1] :param vmax: see vmin :param shape: shape/size of the n-D histogram grid :param limits: list of [[xmin, xmax], [ymin, ymax]], or a description such as 'minmax', '99%' :param grid: if the binning is done before by yourself, you can pass it :param colormap: matplotlib colormap to use :param figsize: (x, y) tuple passed to pylab.figure for setting the figure size :param xlabel: :param ylabel: :param aspect: :param tight_layout: call pylab.tight_layout or not :param colorbar: plot a colorbar or not :param interpolation: interpolation for imshow, possible options are: 'nearest', 'bilinear', 'bicubic', see matplotlib for more :param return_extra: :return: """ import pylab import matplotlib n = _parse_n(normalize) if type(shape) == int: shape = (shape,) * 2 binby = [] x = _ensure_strings_from_expressions(x) y = _ensure_strings_from_expressions(y) for expression in [y, x]: if expression is not None: binby = [expression] + binby fig = pylab.gcf() if figsize is not None: fig.set_size_inches(*figsize) import re what_units = None whats = _ensure_list(what) selections = _ensure_list(selection) selections = _ensure_strings_from_expressions(selections) if y is None: waslist, [x, ] = vaex.utils.listify(x) else: waslist, [x, y] = vaex.utils.listify(x, y) x = list(zip(x, y)) limits = [limits] # every plot has its own vwhat for now vwhats = _expand_limits(vwhat, len(x)) # TODO: we're abusing this function.. logger.debug("x: %s", x) limits, shape = self.limits(x, limits, shape=shape) shape = shape[0] logger.debug("limits: %r", limits) # mapping of a grid axis to a label labels = {} shape = _expand_shape(shape, 2) vshape = _expand_shape(shape, 2) if z is not None: match = re.match("(.*):(.*),(.*),(.*)", z) if match: groups = match.groups() import ast z_expression = groups[0] logger.debug("found groups: %r", list(groups)) z_limits = [ast.literal_eval(groups[1]), ast.literal_eval(groups[2])] z_shape = ast.literal_eval(groups[3]) # for pair in x: x = [[z_expression] + list(k) for k in x] limits = np.array([[z_limits] + list(k) for k in limits]) shape = (z_shape,) + shape vshape = (z_shape,) + vshape logger.debug("x = %r", x) values = np.linspace(z_limits[0], z_limits[1], num=z_shape + 1) labels["z"] = list(["%s <= %s < %s" % (v1, z_expression, v2) for v1, v2 in zip(values[:-1], values[1:])]) else: raise ValueError("Could not understand 'z' argument %r, expected something in form: 'column:-1,10:5'" % facet) else: z_shape = 1 # z == 1 if z is None: total_grid = np.zeros((len(x), len(whats), len(selections), 1) + shape, dtype=float) total_vgrid = np.zeros((len(x), len(whats), len(selections), 1) + vshape, dtype=float) else: total_grid = np.zeros((len(x), len(whats), len(selections)) + shape, dtype=float) total_vgrid = np.zeros((len(x), len(whats), len(selections)) + vshape, dtype=float) logger.debug("shape of total grid: %r", total_grid.shape) axis = dict(plot=0, what=1, selection=2) xlimits = limits grid_axes = dict(x=-1, y=-2, z=-3, selection=-4, what=-5, subspace=-6) visual_axes = dict(x=-1, y=-2, layer=-3, fade=-4, column=-5, row=-6) # visual_default=dict(x="x", y="y", z="layer", selection="fade", subspace="row", what="column") # visual: mapping of a plot axis, to a grid axis visual_default = dict(x="x", y="y", layer="z", fade="selection", row="subspace", column="what") def invert(x): return dict((v, k) for k, v in x.items()) # visual_default_reverse = invert(visual_default) # visual_ = visual_default # visual = dict(visual) # copy for modification # add entries to avoid mapping multiple times to the same axis free_visual_axes = list(visual_default.keys()) # visual_reverse = invert(visual) logger.debug("1: %r %r", visual, free_visual_axes) for visual_name, grid_name in visual.items(): if visual_name in free_visual_axes: free_visual_axes.remove(visual_name) else: raise ValueError("visual axes %s used multiple times" % visual_name) logger.debug("2: %r %r", visual, free_visual_axes) for visual_name, grid_name in visual_default.items(): if visual_name in free_visual_axes and grid_name not in visual.values(): free_visual_axes.remove(visual_name) visual[visual_name] = grid_name logger.debug("3: %r %r", visual, free_visual_axes) for visual_name, grid_name in visual_default.items(): if visual_name not in free_visual_axes and grid_name not in visual.values(): visual[free_visual_axes.pop(0)] = grid_name logger.debug("4: %r %r", visual, free_visual_axes) visual_reverse = invert(visual) # TODO: the meaning of visual and visual_reverse is changed below this line, super confusing visual, visual_reverse = visual_reverse, visual # so now, visual: mapping of a grid axis to plot axis # visual_reverse: mapping of a grid axis to plot axis move = {} for grid_name, visual_name in visual.items(): if visual_axes[visual_name] in visual.values(): index = visual.values().find(visual_name) key = visual.keys()[index] raise ValueError("trying to map %s to %s while, it is already mapped by %s" % (grid_name, visual_name, key)) move[grid_axes[grid_name]] = visual_axes[visual_name] # normalize_axis = _ensure_list(normalize_axis) fs = _expand(f, total_grid.shape[grid_axes[normalize_axis]]) # assert len(vwhat) # labels["y"] = ylabels what_labels = [] if grid is None: grid_of_grids = [] for i, (binby, limits) in enumerate(zip(x, xlimits)): grid_of_grids.append([]) for j, what in enumerate(whats): if isinstance(what, vaex.stat.Expression): grid = what.calculate(self, binby=binby, shape=shape, limits=limits, selection=selections, delay=True) else: what = what.strip() index = what.index("(") import re groups = re.match("(.*)\((.*)\)", what).groups() if groups and len(groups) == 2: function = groups[0] arguments = groups[1].strip() if "," in arguments: arguments = arguments.split(",") functions = ["mean", "sum", "std", "var", "correlation", "covar", "min", "max", "median_approx"] unit_expression = None if function in ["mean", "sum", "std", "min", "max", "median"]: unit_expression = arguments if function in ["var"]: unit_expression = "(%s) * (%s)" % (arguments, arguments) if function in ["covar"]: unit_expression = "(%s) * (%s)" % arguments if unit_expression: unit = self.unit(unit_expression) if unit: what_units = unit.to_string('latex_inline') if function in functions: grid = getattr(self, function)(arguments, binby=binby, limits=limits, shape=shape, selection=selections, delay=True) elif function == "count": grid = self.count(arguments, binby, shape=shape, limits=limits, selection=selections, delay=True) else: raise ValueError("Could not understand method: %s, expected one of %r'" % (function, functions)) else: raise ValueError("Could not understand 'what' argument %r, expected something in form: 'count(*)', 'mean(x)'" % what) if i == 0: # and j == 0: what_label = str(whats[j]) if what_units: what_label += " (%s)" % what_units if fs[j]: what_label = fs[j] + " " + what_label what_labels.append(what_label) grid_of_grids[-1].append(grid) self.executor.execute() for i, (binby, limits) in enumerate(zip(x, xlimits)): for j, what in enumerate(whats): grid = grid_of_grids[i][j].get() total_grid[i, j, :, :] = grid[:, None, ...] labels["what"] = what_labels else: dims_left = 6 - len(grid.shape) total_grid = np.broadcast_to(grid, (1,) * dims_left + grid.shape) # visual=dict(x="x", y="y", selection="fade", subspace="facet1", what="facet2",) def _selection_name(name): if name in [None, False]: return "selection: all" elif name in ["default", True]: return "selection: default" else: return "selection: %s" % name if selection_labels is None: labels["selection"] = list([_selection_name(k) for k in selections]) else: labels["selection"] = selection_labels # visual_grid = np.moveaxis(total_grid, move.keys(), move.values()) # np.moveaxis is in np 1.11 only?, use transpose axes = [None] * len(move) for key, value in move.items(): axes[value] = key visual_grid = np.transpose(total_grid, axes) logger.debug("grid shape: %r", total_grid.shape) logger.debug("visual: %r", visual.items()) logger.debug("move: %r", move) logger.debug("visual grid shape: %r", visual_grid.shape) xexpressions = [] yexpressions = [] for i, (binby, limits) in enumerate(zip(x, xlimits)): xexpressions.append(binby[0]) yexpressions.append(binby[1]) if xlabel is None: xlabels = [] ylabels = [] for i, (binby, limits) in enumerate(zip(x, xlimits)): if z is not None: xlabels.append(self.label(binby[1])) ylabels.append(self.label(binby[2])) else: xlabels.append(self.label(binby[0])) ylabels.append(self.label(binby[1])) else: Nl = visual_grid.shape[visual_axes['row']] xlabels = _expand(xlabel, Nl) ylabels = _expand(ylabel, Nl) #labels[visual["x"]] = (xlabels, ylabels) labels["x"] = xlabels labels["y"] = ylabels # grid = total_grid # print(grid.shape) # grid = self.reduce(grid, ) axes = [] # cax = pylab.subplot(1,1,1) background_color = np.array(matplotlib.colors.colorConverter.to_rgb(background_color)) # if grid.shape[axis["selection"]] > 1:# and not facet: # rgrid = vaex.image.fade(rgrid) # finite_mask = np.any(finite_mask, axis=0) # do we really need this # print(rgrid.shape) # facet_row_axis = axis["what"] import math facet_columns = None facets = visual_grid.shape[visual_axes["row"]] * visual_grid.shape[visual_axes["column"]] if visual_grid.shape[visual_axes["column"]] == 1 and wrap: facet_columns = min(wrap_columns, visual_grid.shape[visual_axes["row"]]) wrapped = True elif visual_grid.shape[visual_axes["row"]] == 1 and wrap: facet_columns = min(wrap_columns, visual_grid.shape[visual_axes["column"]]) wrapped = True else: wrapped = False facet_columns = visual_grid.shape[visual_axes["column"]] facet_rows = int(math.ceil(facets / facet_columns)) logger.debug("facet_rows: %r", facet_rows) logger.debug("facet_columns: %r", facet_columns) # if visual_grid.shape[visual_axes["row"]] > 1: # and not wrap: # #facet_row_axis = axis["what"] # facet_columns = visual_grid.shape[visual_axes["column"]] # else: # facet_columns = min(wrap_columns, facets) # if grid.shape[axis["plot"]] > 1:# and not facet: # this loop could be done using axis arguments everywhere # assert len(normalize_axis) == 1, "currently only 1 normalization axis supported" grid = visual_grid * 1. fgrid = visual_grid * 1. ngrid = visual_grid * 1. # colorgrid = np.zeros(ngrid.shape + (4,), float) # print "norma", normalize_axis, visual_grid.shape[visual_axes[visual[normalize_axis]]] vmins = _expand(vmin, visual_grid.shape[visual_axes[visual[normalize_axis]]], type=list) vmaxs = _expand(vmax, visual_grid.shape[visual_axes[visual[normalize_axis]]], type=list) # for name in normalize_axis: visual_grid if smooth_pre: grid = vaex.grids.gf(grid, smooth_pre) if 1: axis = visual_axes[visual[normalize_axis]] for i in range(visual_grid.shape[axis]): item = [slice(None, None, None), ] * len(visual_grid.shape) item[axis] = i item = tuple(item) f = _parse_f(fs[i]) with np.errstate(divide='ignore', invalid='ignore'): # these are fine, we are ok with nan's in vaex fgrid.__setitem__(item, f(grid.__getitem__(item))) # print vmins[i], vmaxs[i] if vmins[i] is not None and vmaxs[i] is not None: nsubgrid = fgrid.__getitem__(item) * 1 nsubgrid -= vmins[i] nsubgrid /= (vmaxs[i] - vmins[i]) else: nsubgrid, vmin, vmax = n(fgrid.__getitem__(item)) vmins[i] = vmin vmaxs[i] = vmax # print " ", vmins[i], vmaxs[i] ngrid.__setitem__(item, nsubgrid) if 0: # TODO: above should be like the code below, with custom vmin and vmax grid = visual_grid[i] f = _parse_f(fs[i]) fgrid = f(grid) finite_mask = np.isfinite(grid) finite_mask = np.any(finite_mask, axis=0) if vmin is not None and vmax is not None: ngrid = fgrid * 1 ngrid -= vmin ngrid /= (vmax - vmin) ngrid = np.clip(ngrid, 0, 1) else: ngrid, vmin, vmax = n(fgrid) # vmin, vmax = np.nanmin(fgrid), np.nanmax(fgrid) # every 'what', should have its own colorbar, check if what corresponds to # rows or columns in facets, if so, do a colorbar per row or per column rows, columns = int(math.ceil(facets / float(facet_columns))), facet_columns colorbar_location = "individual" if visual["what"] == "row" and visual_grid.shape[1] == facet_columns: colorbar_location = "per_row" if visual["what"] == "column" and visual_grid.shape[0] == facet_rows: colorbar_location = "per_column" # values = np.linspace(facet_limits[0], facet_limits[1], facet_count+1) logger.debug("rows: %r, columns: %r", rows, columns) import matplotlib.gridspec as gridspec column_scale = 1 row_scale = 1 row_offset = 0 if facets > 1: if colorbar_location == "per_row": column_scale = 4 gs = gridspec.GridSpec(rows, columns * column_scale + 1) elif colorbar_location == "per_column": row_offset = 1 row_scale = 4 gs = gridspec.GridSpec(rows * row_scale + 1, columns) else: gs = gridspec.GridSpec(rows, columns) facet_index = 0 fs = _expand(f, len(whats)) colormaps = _expand(colormap, len(whats)) # row for i in range(visual_grid.shape[0]): # column for j in range(visual_grid.shape[1]): if colorbar and colorbar_location == "per_column" and i == 0: norm = matplotlib.colors.Normalize(vmins[j], vmaxs[j]) sm = matplotlib.cm.ScalarMappable(norm, colormaps[j]) sm.set_array(1) # make matplotlib happy (strange behavious) if facets > 1: ax = pylab.subplot(gs[0, j]) colorbar = fig.colorbar(sm, cax=ax, orientation="horizontal") else: colorbar = fig.colorbar(sm) if "what" in labels: label = labels["what"][j] if facets > 1: colorbar.ax.set_title(label) else: colorbar.ax.set_ylabel(colorbar_label or label) if colorbar and colorbar_location == "per_row" and j == 0: norm = matplotlib.colors.Normalize(vmins[i], vmaxs[i]) sm = matplotlib.cm.ScalarMappable(norm, colormaps[i]) sm.set_array(1) # make matplotlib happy (strange behavious) if facets > 1: ax = pylab.subplot(gs[i, -1]) colorbar = fig.colorbar(sm, cax=ax) else: colorbar = fig.colorbar(sm) label = labels["what"][i] colorbar.ax.set_ylabel(colorbar_label or label) rgrid = ngrid[i, j] * 1. # print rgrid.shape for k in range(rgrid.shape[0]): for l in range(rgrid.shape[0]): if smooth_post is not None: rgrid[k, l] = vaex.grids.gf(rgrid, smooth_post) if visual["what"] == "column": what_index = j elif visual["what"] == "row": what_index = i else: what_index = 0 if visual[normalize_axis] == "column": normalize_index = j elif visual[normalize_axis] == "row": normalize_index = i else: normalize_index = 0 for r in reduce: r = _parse_reduction(r, colormaps[what_index], []) rgrid = r(rgrid) row = facet_index // facet_columns column = facet_index % facet_columns if colorbar and colorbar_location == "individual": # visual_grid.shape[visual_axes[visual[normalize_axis]]] norm = matplotlib.colors.Normalize(vmins[normalize_index], vmaxs[normalize_index]) sm = matplotlib.cm.ScalarMappable(norm, colormaps[what_index]) sm.set_array(1) # make matplotlib happy (strange behavious) if facets > 1: ax = pylab.subplot(gs[row, column]) colorbar = fig.colorbar(sm, ax=ax) else: colorbar = fig.colorbar(sm) label = labels["what"][what_index] colorbar.ax.set_ylabel(colorbar_label or label) if facets > 1: ax = pylab.subplot(gs[row_offset + row * row_scale:row_offset + (row + 1) * row_scale, column * column_scale:(column + 1) * column_scale]) else: ax = pylab.gca() axes.append(ax) logger.debug("rgrid: %r", rgrid.shape) plot_rgrid = rgrid assert plot_rgrid.shape[1] == 1, "no layers supported yet" plot_rgrid = plot_rgrid[:, 0] if plot_rgrid.shape[0] > 1: plot_rgrid = vaex.image.fade(plot_rgrid[::-1]) else: plot_rgrid = plot_rgrid[0] extend = None if visual["subspace"] == "row": subplot_index = i elif visual["subspace"] == "column": subplot_index = j else: subplot_index = 0 extend = np.array(xlimits[subplot_index][-2:]).flatten() # extend = np.array(xlimits[i]).flatten() logger.debug("plot rgrid: %r", plot_rgrid.shape) plot_rgrid = np.transpose(plot_rgrid, (1, 0, 2)) im = ax.imshow(plot_rgrid, extent=extend.tolist(), origin="lower", aspect=aspect, interpolation=interpolation) # v1, v2 = values[i], values[i+1] def label(index, label, expression): if label and _issequence(label): return label[i] else: return self.label(expression) if visual_reverse["x"] =='x': labelsx = labels['x'] pylab.xlabel(labelsx[subplot_index]) if visual_reverse["x"] =='x': labelsy = labels['y'] pylab.ylabel(labelsy[subplot_index]) if visual["z"] in ['row']: labelsz = labels['z'] ax.set_title(labelsz[i]) if visual["z"] in ['column']: labelsz = labels['z'] ax.set_title(labelsz[j]) max_labels = 10 # xexpression = xexpressions[i] # if self.iscategory(xexpression): # labels = self.category_labels(xexpression) # step = len(labels) // max_labels # pylab.xticks(np.arange(len(labels))[::step], labels[::step], size='small') # yexpression = yexpressions[i] # if self.iscategory(yexpression): # labels = self.category_labels(yexpression) # step = len(labels) // max_labels # pylab.yticks(np.arange(len(labels))[::step], labels[::step], size='small') facet_index += 1 if title: fig.suptitle(title, fontsize="x-large") if tight_layout: if title: pylab.tight_layout(rect=[0, 0.03, 1, 0.95]) else: pylab.tight_layout() if hardcopy: pylab.savefig(hardcopy) if show: pylab.show() if return_extra: return im, grid, fgrid, ngrid, rgrid else: return im
https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-viz/vaex/viz/mpl.py#L290-L848
scatter plot
python
def scatter(self, x, y, xerr=[], yerr=[], mark='o', markstyle=None): """Plot a series of points. Plot a series of points (marks) that are not connected by a line. Shortcut for plot with linestyle=None. :param x: array containing x-values. :param y: array containing y-values. :param xerr: array containing errors on the x-values. :param yerr: array containing errors on the y-values. :param mark: the symbol used to mark the data points. May be any plot mark accepted by TikZ (e.g. ``*, x, +, o, square, triangle``). :param markstyle: the style of the plot marks (e.g. 'mark size=.75pt') Example:: >>> plot = artist.Plot() >>> x = np.random.normal(size=20) >>> y = np.random.normal(size=20) >>> plot.scatter(x, y, mark='*') """ self.plot(x, y, xerr=xerr, yerr=yerr, mark=mark, linestyle=None, markstyle=markstyle)
https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/artist/plot.py#L433-L458
scatter plot
python
def plot_2(data, *args): """Plot 2. Running best score (scatter plot)""" df_all = pd.DataFrame(data) df_params = nonconstant_parameters(data) x = [df_all['id'][0]] y = [df_all['mean_test_score'][0]] params = [df_params.loc[0]] for i in range(len(df_all)): if df_all['mean_test_score'][i] > y[-1]: x.append(df_all['id'][i]) y.append(df_all['mean_test_score'][i]) params.append(df_params.loc[i]) return build_scatter_tooltip( x=x, y=y, tt=pd.DataFrame(params), title='Running best')
https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/plot.py#L66-L79
scatter plot
python
def plot_scatter_matrix(self, freq=None, title=None, figsize=(10, 10), **kwargs): """ Wrapper around pandas' scatter_matrix. Args: * freq (str): Data frequency used for display purposes. Refer to pandas docs for valid freq strings. * figsize ((x,y)): figure size * title (str): Title if default not appropriate * kwargs: passed to pandas' scatter_matrix method """ if title is None: title = self._get_default_plot_title( freq, 'Return Scatter Matrix') plt.figure() ser = self._get_series(freq).to_returns().dropna() pd.scatter_matrix(ser, figsize=figsize, **kwargs) return plt.suptitle(title)
https://github.com/pmorissette/ffn/blob/ef09f28b858b7ffcd2627ce6a4dc618183a6bc8a/ffn/core.py#L910-L930
scatter plot
python
def scatter( x=None, y=None, label=None, color=None, width=None, dash=None, opacity=None, markersize=6, yaxis=1, fill=None, text="", mode='markers', ): """Draws dots. Parameters ---------- x : array-like, optional y : array-like, optional label : array-like, optional Returns ------- Chart """ return line( x=x, y=y, label=label, color=color, width=width, dash=dash, opacity=opacity, mode=mode, yaxis=yaxis, fill=fill, text=text, markersize=markersize, )
https://github.com/jwkvam/plotlywrapper/blob/762b42912e824fecb1212c186900f2ebdd0ab12b/plotlywrapper.py#L746-L786
scatter plot
python
def projScatter(lon, lat, **kwargs): """ Create a scatter plot on HEALPix projected axes. Inputs: lon (deg), lat (deg) """ hp.projscatter(lon, lat, lonlat=True, **kwargs)
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L141-L146
scatter plot
python
def scatmat(df, category=None, colors='rgob', num_plots=4, num_topics=100, num_columns=4, show=False, block=False, data_path=DATA_PATH, save=False, verbose=1): """Scatter plot with colored markers depending on the discrete values in a "category" column FIXME: empty plots that dont go away, Plot and/save scatter matrix in groups of num_columns topics""" if category is None: category = list(df.columns)[-1] if isinstance(category, (str, bytes, int)) and category in df.columns: category = df[category] else: category = pd.Series(category) suffix = '{}x{}'.format(*list(df.shape)) # suffix = compose_suffix(len(df), num_topics, save) # save = bool(save) for i in range(min(num_plots * num_columns, num_topics) / num_plots): scatter_matrix(df[df.columns[i * num_columns:(i + 1) * num_columns]], marker='+', c=[colors[int(x) % len(colors)] for x in category.values], figsize=(18, 12)) if save: name = 'scatmat_topics_{}-{}.jpg'.format(i * num_columns, (i + 1) * num_columns) + suffix plt.savefig(os.path.join(data_path, name + '.jpg')) if show: if block: plt.show() else: plt.show(block=False)
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/plots.py#L296-L323
scatter plot
python
def plot(self,*args,**kwargs): """ NAME: plot PURPOSE: plot the snapshot (with reasonable defaults) INPUT: d1= first dimension to plot ('x', 'y', 'R', 'vR', 'vT', 'z', 'vz', ...) d2= second dimension to plot matplotlib.plot inputs+bovy_plot.plot inputs OUTPUT: sends plot to output device HISTORY: 2011-02-06 - Written based on Orbit's plot """ labeldict= {'t':r'$t$','R':r'$R$','vR':r'$v_R$','vT':r'$v_T$', 'z':r'$z$','vz':r'$v_z$','phi':r'$\phi$', 'x':r'$x$','y':r'$y$','vx':r'$v_x$','vy':r'$v_y$'} #Defaults if not kwargs.has_key('d1') and not kwargs.has_key('d2'): if len(self.orbits[0].vxvv) == 3: d1= 'R' d2= 'vR' elif len(self.orbits[0].vxvv) == 4: d1= 'x' d2= 'y' elif len(self.orbits[0].vxvv) == 2: d1= 'x' d2= 'vx' elif len(self.orbits[0].vxvv) == 5 \ or len(self.orbits[0].vxvv) == 6: d1= 'R' d2= 'z' elif not kwargs.has_key('d1'): d2= kwargs['d2'] kwargs.pop('d2') d1= 't' elif not kwargs.has_key('d2'): d1= kwargs['d1'] kwargs.pop('d1') d2= 't' else: d1= kwargs['d1'] kwargs.pop('d1') d2= kwargs['d2'] kwargs.pop('d2') #Get x and y if d1 == 'R': x= [o.R() for o in self.orbits] elif d1 == 'z': x= [o.z() for o in self.orbits] elif d1 == 'vz': x= [o.vz() for o in self.orbits] elif d1 == 'vR': x= [o.vR() for o in self.orbits] elif d1 == 'vT': x= [o.vT() for o in self.orbits] elif d1 == 'x': x= [o.x() for o in self.orbits] elif d1 == 'y': x= [o.y() for o in self.orbits] elif d1 == 'vx': x= [o.vx() for o in self.orbits] elif d1 == 'vy': x= [o.vy() for o in self.orbits] elif d1 == 'phi': x= [o.phi() for o in self.orbits] if d2 == 'R': y= [o.R() for o in self.orbits] elif d2 == 'z': y= [o.z() for o in self.orbits] elif d2 == 'vz': y= [o.vz() for o in self.orbits] elif d2 == 'vR': y= [o.vR() for o in self.orbits] elif d2 == 'vT': y= [o.vT() for o in self.orbits] elif d2 == 'x': y= [o.x() for o in self.orbits] elif d2 == 'y': y= [o.y() for o in self.orbits] elif d2 == 'vx': y= [o.vx() for o in self.orbits] elif d2 == 'vy': y= [o.vy() for o in self.orbits] elif d2 == 'phi': y= [o.phi() for o in self.orbits] #Plot if not kwargs.has_key('xlabel'): kwargs['xlabel']= labeldict[d1] if not kwargs.has_key('ylabel'): kwargs['ylabel']= labeldict[d2] if len(args) == 0: args= (',',) plot.bovy_plot(x,y,*args,**kwargs)
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/snapshot/Snapshot.py#L148-L255
scatter plot
python
def scatter_drag( x_points: 'Array', y_points: 'Array', *, fig=None, show_eqn=True, options={} ): """ Generates an interactive scatter plot with the best fit line plotted over the points. The points can be dragged by the user and the line will automatically update. Args: x_points (Array Number): x-values of points to plot y_points (Array Number): y-values of points to plot Kwargs: show_eqn (bool): If True (default), displays the best fit line's equation above the scatterplot. {options} Returns: VBox with two children: the equation widget and the figure. >>> xs = np.arange(10) >>> ys = np.arange(10) + np.random.rand(10) >>> scatter_drag(xs, ys) VBox(...) """ params = { 'marks': [{ 'x': x_points, 'y': y_points, 'enable_move': True, }, { 'colors': [GOLDENROD], }] } fig = options.get('_fig', False) or _create_fig(options=options) [scat, lin] = _create_marks( fig=fig, marks=[bq.Scatter, bq.Lines], options=options, params=params ) _add_marks(fig, [scat, lin]) equation = widgets.Label() # create line fit to data and display equation def update_line(change=None): x_sc = scat.scales['x'] lin.x = [ x_sc.min if x_sc.min is not None else np.min(scat.x), x_sc.max if x_sc.max is not None else np.max(scat.x), ] poly = np.polyfit(scat.x, scat.y, deg=1) lin.y = np.polyval(poly, lin.x) if show_eqn: equation.value = 'y = {:.2f}x + {:.2f}'.format(poly[0], poly[1]) update_line() scat.observe(update_line, names=['x', 'y']) return widgets.VBox([equation, fig])
https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/plotting.py#L312-L377
scatter plot
python
def imscatter(images, positions): ''' Creates a scatter plot, where each plot is shown by corresponding image ''' positions = np.array(positions) bottoms = positions[:, 1] - np.array([im.shape[1] / 2.0 for im in images]) tops = bottoms + np.array([im.shape[1] for im in images]) lefts = positions[:, 0] - np.array([im.shape[0] / 2.0 for im in images]) rigths = lefts + np.array([im.shape[0] for im in images]) most_bottom = int(np.floor(bottoms.min())) most_top = int(np.ceil(tops.max())) most_left = int(np.floor(lefts.min())) most_right = int(np.ceil(rigths.max())) scatter_image = np.zeros( [most_right - most_left, most_top - most_bottom, 3], dtype=imgs[0].dtype) # shift, now all from zero positions -= [most_left, most_bottom] for im, pos in zip(images, positions): xl = int(pos[0] - im.shape[0] / 2) xr = xl + im.shape[0] yb = int(pos[1] - im.shape[1] / 2) yt = yb + im.shape[1] scatter_image[xl:xr, yb:yt, :] = im return scatter_image
https://github.com/DmitryUlyanov/Multicore-TSNE/blob/62dedde52469f3a0aeb22fdd7bce2538f17f77ef/tsne-embedding.py#L9-L42
scatter plot
python
def plot(x, fmt='-', marker=None, markers=None, linestyle=None, linestyles=None, color=None, colors=None, palette='hls', group=None, hue=None, labels=None, legend=None, title=None, size=None, elev=10, azim=-60, ndims=3, model=None, model_params=None, reduce='IncrementalPCA', cluster=None, align=None, normalize=None, n_clusters=None, save_path=None, animate=False, duration=30, tail_duration=2, rotations=2, zoom=1, chemtrails=False, precog=False, bullettime=False, frame_rate=50, explore=False, show=True, transform=None, vectorizer='CountVectorizer', semantic='LatentDirichletAllocation', corpus='wiki', ax=None): """ Plots dimensionality reduced data and parses plot arguments Parameters ---------- x : Numpy array, DataFrame, String, Geo or mixed list Data for the plot. The form should be samples (rows) by features (cols). fmt : str or list of strings A list of format strings. All matplotlib format strings are supported. linestyle(s) : str or list of str A list of line styles marker(s) : str or list of str A list of marker types color(s) : str or list of str A list of marker types palette : str A matplotlib or seaborn color palette group : str/int/float or list A list of group labels. Length must match the number of rows in your dataset. If the data type is numerical, the values will be mapped to rgb values in the specified palette. If the data type is strings, the points will be labeled categorically. To label a subset of points, use None (i.e. ['a', None, 'b','a']). labels : list A list of labels for each point. Must be dimensionality of data (x). If no label is wanted for a particular point, input None. legend : list or bool If set to True, legend is implicitly computed from data. Passing a list will add string labels to the legend (one for each list item). title : str A title for the plot size : list A list of [width, height] in inches to resize the figure normalize : str or False If set to 'across', the columns of the input data will be z-scored across lists (default). If set to 'within', the columns will be z-scored within each list that is passed. If set to 'row', each row of the input data will be z-scored. If set to False, the input data will be returned (default is False). reduce : str or dict Decomposition/manifold learning model to use. Models supported: PCA, IncrementalPCA, SparsePCA, MiniBatchSparsePCA, KernelPCA, FastICA, FactorAnalysis, TruncatedSVD, DictionaryLearning, MiniBatchDictionaryLearning, TSNE, Isomap, SpectralEmbedding, LocallyLinearEmbedding, and MDS. Can be passed as a string, but for finer control of the model parameters, pass as a dictionary, e.g. reduce={'model' : 'PCA', 'params' : {'whiten' : True}}. See scikit-learn specific model docs for details on parameters supported for each model. ndims : int An `int` representing the number of dims to reduce the data x to. If ndims > 3, will plot in 3 dimensions but return the higher dimensional data. Default is None, which will plot data in 3 dimensions and return the data with the same number of dimensions possibly normalized and/or aligned according to normalize/align kwargs. align : str or dict or False/None If str, either 'hyper' or 'SRM'. If 'hyper', alignment algorithm will be hyperalignment. If 'SRM', alignment algorithm will be shared response model. You can also pass a dictionary for finer control, where the 'model' key is a string that specifies the model and the params key is a dictionary of parameter values (default : 'hyper'). cluster : str or dict or False/None If cluster is passed, HyperTools will perform clustering using the specified clustering clustering model. Supportted algorithms are: KMeans, MiniBatchKMeans, AgglomerativeClustering, Birch, FeatureAgglomeration, SpectralClustering and HDBSCAN (default: None). Can be passed as a string, but for finer control of the model parameters, pass as a dictionary, e.g. reduce={'model' : 'KMeans', 'params' : {'max_iter' : 100}}. See scikit-learn specific model docs for details on parameters supported for each model. If no parameters are specified in the string a default set of parameters will be used. n_clusters : int If n_clusters is passed, HyperTools will perform k-means clustering with the k parameter set to n_clusters. The resulting clusters will be plotted in different colors according to the color palette. save_path : str Path to save the image/movie. Must include the file extension in the save path (i.e. save_path='/path/to/file/image.png'). NOTE: If saving an animation, FFMPEG must be installed (this is a matplotlib req). FFMPEG can be easily installed on a mac via homebrew brew install ffmpeg or linux via apt-get apt-get install ffmpeg. If you don't have homebrew (mac only), you can install it like this: /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)". animate : bool, 'parallel' or 'spin' If True or 'parallel', plots the data as an animated trajectory, with each dataset plotted simultaneously. If 'spin', all the data is plotted at once but the camera spins around the plot (default: False). duration (animation only) : float Length of the animation in seconds (default: 30 seconds) tail_duration (animation only) : float Sets the length of the tail of the data (default: 2 seconds) rotations (animation only) : float Number of rotations around the box (default: 2) zoom (animation only) : float How far to zoom into the plot, positive numbers will zoom in (default: 0) chemtrails (animation only) : bool A low-opacity trail is left behind the trajectory (default: False). precog (animation only) : bool A low-opacity trail is plotted ahead of the trajectory (default: False). bullettime (animation only) : bool A low-opacity trail is plotted ahead and behind the trajectory (default: False). frame_rate (animation only) : int or float Frame rate for animation (default: 50) explore : bool Displays user defined labels will appear on hover. If no labels are passed, the point index and coordinate will be plotted. To use, set explore=True. Note: Explore mode is currently only supported for 3D static plots, and is an experimental feature (i.e it may not yet work properly). show : bool If set to False, the figure will not be displayed, but the figure, axis and data objects will still be returned (default: True). transform : list of numpy arrays or None The transformed data, bypasses transformations if this is set (default : None). vectorizer : str, dict, class or class instance The vectorizer to use. Built-in options are 'CountVectorizer' or 'TfidfVectorizer'. To change default parameters, set to a dictionary e.g. {'model' : 'CountVectorizer', 'params' : {'max_features' : 10}}. See http://scikit-learn.org/stable/modules/classes.html#module-sklearn.feature_extraction.text for details. You can also specify your own vectorizer model as a class, or class instance. With either option, the class must have a fit_transform method (see here: http://scikit-learn.org/stable/data_transforms.html). If a class, pass any parameters as a dictionary to vectorizer_params. If a class instance, no parameters can be passed. semantic : str, dict, class or class instance Text model to use to transform text data. Built-in options are 'LatentDirichletAllocation' or 'NMF' (default: LDA). To change default parameters, set to a dictionary e.g. {'model' : 'NMF', 'params' : {'n_components' : 10}}. See http://scikit-learn.org/stable/modules/classes.html#module-sklearn.decomposition for details on the two model options. You can also specify your own text model as a class, or class instance. With either option, the class must have a fit_transform method (see here: http://scikit-learn.org/stable/data_transforms.html). If a class, pass any parameters as a dictionary to text_params. If a class instance, no parameters can be passed. corpus : list (or list of lists) of text samples or 'wiki', 'nips', 'sotus'. Text to use to fit the semantic model (optional). If set to 'wiki', 'nips' or 'sotus' and the default semantic and vectorizer models are used, a pretrained model will be loaded which can save a lot of time. ax : matplotlib.Axes Axis handle to plot the figure Returns ---------- geo : hypertools.DataGeometry A new data geometry object """ # warnings for deprecated API args if (model is not None) or (model_params is not None): warnings.warn('Model and model_params arguments will be deprecated. Please use \ reduce keyword argument. See docs for details: http://hypertools.readthedocs.io/en/latest/hypertools.plot.html#hypertools.plot') reduce = {} reduce['model'] = model reduce['params'] = model_params if group is not None: warnings.warn('Group will be deprecated. Please use ' 'hue keyword argument. See docs for details: ' 'http://hypertools.readthedocs.io/en/latest/hypertools.plot.html#hypertools.plot') hue = group if ax is not None: if ndims>2: if ax.name!='3d': raise ValueError('If passing ax and the plot is 3D, ax must ' 'also be 3d') text_args = { 'vectorizer' : vectorizer, 'semantic' : semantic, 'corpus' : corpus } # analyze the data if transform is None: raw = format_data(x, **text_args) xform = analyze(raw, ndims=ndims, normalize=normalize, reduce=reduce, align=align, internal=True) else: xform = transform # Return data that has been normalized and possibly reduced and/or aligned xform_data = copy.copy(xform) # catch all matplotlib kwargs here to pass on mpl_kwargs = {} # handle color (to be passed onto matplotlib) if color is not None: mpl_kwargs['color'] = color if colors is not None: mpl_kwargs['color'] = colors warnings.warn('Both color and colors defined: color will be ignored \ in favor of colors.') # handle linestyle (to be passed onto matplotlib) if linestyle is not None: mpl_kwargs['linestyle'] = linestyle if linestyles is not None: mpl_kwargs['linestyle'] = linestyles warnings.warn('Both linestyle and linestyles defined: linestyle \ will be ignored in favor of linestyles.') # handle marker (to be passed onto matplotlib) if marker is not None: mpl_kwargs['marker'] = marker if markers is not None: mpl_kwargs['marker'] = markers warnings.warn('Both marker and markers defined: marker will be \ ignored in favor of markers.') # reduce data to 3 dims for plotting, if ndims is None, return this if (ndims and ndims < 3): xform = reducer(xform, ndims=ndims, reduce=reduce, internal=True) else: xform = reducer(xform, ndims=3, reduce=reduce, internal=True) # find cluster and reshape if n_clusters if cluster is not None: if hue is not None: warnings.warn('cluster overrides hue, ignoring hue.') if isinstance(cluster, (six.string_types, six.binary_type)): model = cluster params = default_params(model) elif isinstance(cluster, dict): model = cluster['model'] params = default_params(model, cluster['params']) else: raise ValueError('Invalid cluster model specified; should be' ' string or dictionary!') if n_clusters is not None: if cluster in ('HDBSCAN',): warnings.warn('n_clusters is not a valid parameter for ' 'HDBSCAN clustering and will be ignored.') else: params['n_clusters'] = n_clusters cluster_labels = clusterer(xform, cluster={'model': model, 'params': params}) xform, labels = reshape_data(xform, cluster_labels, labels) hue = cluster_labels elif n_clusters is not None: # If cluster was None default to KMeans cluster_labels = clusterer(xform, cluster='KMeans', n_clusters=n_clusters) xform, labels = reshape_data(xform, cluster_labels, labels) if hue is not None: warnings.warn('n_clusters overrides hue, ignoring hue.') # group data if there is a grouping var elif hue is not None: if color is not None: warnings.warn("Using group, color keyword will be ignored.") # if list of lists, unpack if any(isinstance(el, list) for el in hue): hue = list(itertools.chain(*hue)) # if all of the elements are numbers, map them to colors if all(isinstance(el, int) or isinstance(el, float) for el in hue): hue = vals2bins(hue) elif all(isinstance(el, str) for el in hue): hue = group_by_category(hue) # reshape the data according to group if n_clusters is None: xform, labels = reshape_data(xform, hue, labels) # interpolate lines if they are grouped if is_line(fmt): xform = patch_lines(xform) # handle legend if legend is not None: if legend is False: legend = None elif legend is True and hue is not None: legend = [item for item in sorted(set(hue), key=list(hue).index)] elif legend is True and hue is None: legend = [i + 1 for i in range(len(xform))] mpl_kwargs['label'] = legend # interpolate if its a line plot if fmt is None or isinstance(fmt, six.string_types): if is_line(fmt): if xform[0].shape[0] > 1: xform = interp_array_list(xform, interp_val=frame_rate*duration/(xform[0].shape[0] - 1)) elif type(fmt) is list: for idx, xi in enumerate(xform): if is_line(fmt[idx]): if xi.shape[0] > 1: xform[idx] = interp_array_list(xi, interp_val=frame_rate*duration/(xi.shape[0] - 1)) # handle explore flag if explore: assert xform[0].shape[1] is 3, "Explore mode is currently only supported for 3D plots." mpl_kwargs['picker']=True # center xform = center(xform) # scale xform = scale(xform) # handle palette with seaborn if isinstance(palette, np.bytes_): palette = palette.decode("utf-8") sns.set_palette(palette=palette, n_colors=len(xform)) sns.set_style(style='whitegrid') # turn kwargs into a list kwargs_list = parse_kwargs(xform, mpl_kwargs) # handle format strings if fmt is not None: if type(fmt) is not list: draw_fmt = [fmt for i in xform] else: draw_fmt = fmt else: draw_fmt = ['-']*len(x) # convert all nans to zeros for i, xi in enumerate(xform): xform[i] = np.nan_to_num(xi) # draw the plot fig, ax, data, line_ani = _draw(xform, fmt=draw_fmt, kwargs_list=kwargs_list, labels=labels, legend=legend, title=title, animate=animate, duration=duration, tail_duration=tail_duration, rotations=rotations, zoom=zoom, chemtrails=chemtrails, precog=precog, bullettime=bullettime, frame_rate=frame_rate, elev=elev, azim=azim, explore=explore, show=show, size=size, ax=ax) # tighten layout plt.tight_layout() # save if save_path is not None: if animate: Writer = animation.writers['ffmpeg'] writer = Writer(fps=frame_rate, bitrate=1800) line_ani.save(save_path, writer=writer) else: plt.savefig(save_path) # show the plot if show: plt.show() else: # safely closes the plot so it doesn't pop up in another call to this function plt.close('all') # gather reduce params if isinstance(reduce, dict): reduce_dict = reduce else: reduce_dict = { 'model' : reduce, 'params' : { 'n_components' : ndims }, } # gather align params if isinstance(align, dict): align_dict = align else: align_dict = { 'model' : align, 'params' : {} } # gather all other kwargs kwargs = { 'fmt' : fmt, 'marker': marker, 'markers' : markers, 'linestyle' : linestyle, 'linestyles' : linestyles, 'color' : color, 'colors' : colors, 'palette' : palette, 'hue' : hue, 'ndims' : ndims, 'labels' : labels, 'legend' : legend, 'title' : title, 'animate' : animate, 'duration' : duration, 'tail_duration' : tail_duration, 'rotations' : rotations, 'zoom' : zoom, 'chemtrails' : chemtrails, 'precog' : precog, 'bullettime' : bullettime, 'frame_rate' : frame_rate, 'elev' : elev, 'azim' : azim, 'explore' : explore, 'n_clusters' : n_clusters, 'size' : size } # turn lists into np arrays so that they don't turn into pickles when saved for kwarg in kwargs: if isinstance(kwargs[kwarg], list): try: kwargs[kwarg]=np.array(kwargs[kwarg]) except: warnings.warn('Could not convert all list arguments to numpy ' 'arrays. If list is longer than 256 items, it ' 'will automatically be pickled, which could ' 'cause Python 2/3 compatibility issues for the ' 'DataGeometry object.') return DataGeometry(fig=fig, ax=ax, data=x, xform_data=xform_data, line_ani=line_ani, reduce=reduce_dict, align=align_dict, normalize=normalize, semantic=semantic, vectorizer=vectorizer, corpus=corpus, kwargs=kwargs)
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/plot/plot.py#L24-L507
scatter plot
python
def plot(self, x, y, color="black"): """ Uses coordinant system. """ p = Point(x, y) p.fill(color) p.draw(self)
https://github.com/Calysto/calysto/blob/20813c0f48096317aa775d03a5c6b20f12fafc93/calysto/zgraphics.py#L71-L77
scatter plot
python
def scatter(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs): """Scatter plot of 1D histogram.""" show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) value_format = kwargs.pop("value_format", None) text_kwargs = pop_kwargs_with_prefix("text_", kwargs) data = get_data(h1, cumulative=cumulative, density=density) if "cmap" in kwargs: cmap = _get_cmap(kwargs) _, cmap_data = _get_cmap_data(data, kwargs) kwargs["color"] = cmap(cmap_data) else: kwargs["color"] = kwargs.pop("color", "blue") _apply_xy_lims(ax, h1, data, kwargs) _add_ticks(ax, h1, kwargs) _add_labels(ax, h1, kwargs) if errors: err_data = get_err_data(h1, cumulative=cumulative, density=density) ax.errorbar(h1.bin_centers, data, yerr=err_data, fmt=kwargs.pop("fmt", "o"), ecolor=kwargs.pop("ecolor", "black"), ms=0) ax.scatter(h1.bin_centers, data, **kwargs) if show_values: _add_values(ax, h1, data, value_format=value_format, **text_kwargs) if show_stats: _add_stats_box(h1, ax, stats=show_stats)
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L149-L180
scatter plot
python
def scatter(df, x, y, ax=None, legend=None, title=None, color=None, marker='o', linestyle=None, cmap=None, groupby=['model', 'scenario'], with_lines=False, **kwargs): """Plot data as a scatter chart. Parameters ---------- df : pd.DataFrame Data to plot as a long-form data frame x : str column to be plotted on the x-axis y : str column to be plotted on the y-axis ax : matplotlib.Axes, optional legend : bool, optional Include a legend (`None` displays legend only if less than 13 entries) default: None title : bool or string, optional Display a custom title. color : string, optional A valid matplotlib color or column name. If a column name, common values will be provided the same color. default: None marker : string A valid matplotlib marker or column name. If a column name, common values will be provided the same marker. default: 'o' linestyle : string, optional A valid matplotlib linestyle or column name. If a column name, common values will be provided the same linestyle. default: None cmap : string, optional A colormap to use. default: None groupby : list-like, optional Data grouping for plotting. default: ['model', 'scenario'] with_lines : bool, optional Make the scatter plot with lines connecting common data. default: False kwargs : Additional arguments to pass to the pd.DataFrame.plot() function """ if ax is None: fig, ax = plt.subplots() # assign styling properties props = assign_style_props(df, color=color, marker=marker, linestyle=linestyle, cmap=cmap) # group data groups = df.groupby(groupby) # loop over grouped dataframe, plot data legend_data = [] for name, group in groups: pargs = {} labels = [] for key, kind, var in [('c', 'color', color), ('marker', 'marker', marker), ('linestyle', 'linestyle', linestyle)]: if kind in props: label = group[var].values[0] pargs[key] = props[kind][group[var].values[0]] labels.append(repr(label).lstrip("u'").strip("'")) else: pargs[key] = var if len(labels) > 0: legend_data.append(' '.join(labels)) else: legend_data.append(' '.join(name)) kwargs.update(pargs) if with_lines: ax.plot(group[x], group[y], **kwargs) else: kwargs.pop('linestyle') # scatter() can't take a linestyle ax.scatter(group[x], group[y], **kwargs) # build legend handles and labels handles, labels = ax.get_legend_handles_labels() if legend_data != [''] * len(legend_data): labels = sorted(list(set(tuple(legend_data)))) idxs = [legend_data.index(d) for d in labels] handles = [handles[i] for i in idxs] if legend is None and len(labels) < 13 or legend is not False: _add_legend(ax, handles, labels, legend) # add labels and title ax.set_xlabel(x) ax.set_ylabel(y) if title: ax.set_title(title) return ax
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/plotting.py#L667-L760
scatter plot
python
def plot(y, x=None, ptyp='plot', xlbl=None, ylbl=None, title=None, lgnd=None, lglc=None, **kwargs): """ Plot points or lines in 2D. If a figure object is specified then the plot is drawn in that figure, and ``fig.show()`` is not called. The figure is closed on key entry 'q'. Parameters ---------- y : array_like 1d or 2d array of data to plot. If a 2d array, each column is plotted as a separate curve. x : array_like, optional (default None) Values for x-axis of the plot ptyp : string, optional (default 'plot') Plot type specification (options are 'plot', 'semilogx', 'semilogy', and 'loglog') xlbl : string, optional (default None) Label for x-axis ylbl : string, optional (default None) Label for y-axis title : string, optional (default None) Figure title lgnd : list of strings, optional (default None) List of legend string lglc : string, optional (default None) Legend location string **kwargs : :class:`matplotlib.lines.Line2D` properties or figure \ properties, optional Keyword arguments specifying :class:`matplotlib.lines.Line2D` properties, e.g. ``lw=2.0`` sets a line width of 2, or properties of the figure and axes. If not specified, the defaults for line width (``lw``) and marker size (``ms``) are 1.5 and 6.0 respectively. The valid figure and axes keyword arguments are listed below: .. |mplfg| replace:: :class:`matplotlib.figure.Figure` object .. |mplax| replace:: :class:`matplotlib.axes.Axes` object .. rst-class:: kwargs ===== ==================== ====================================== kwarg Accepts Description ===== ==================== ====================================== fgsz tuple (width,height) Specify figure dimensions in inches fgnm integer Figure number of figure fig |mplfg| Draw in specified figure instead of creating one ax |mplax| Plot in specified axes instead of current axes of figure ===== ==================== ====================================== Returns ------- fig : :class:`matplotlib.figure.Figure` object Figure object for this figure ax : :class:`matplotlib.axes.Axes` object Axes object for this plot """ # Extract kwargs entries that are not related to line properties fgsz = kwargs.pop('fgsz', None) fgnm = kwargs.pop('fgnm', None) fig = kwargs.pop('fig', None) ax = kwargs.pop('ax', None) figp = fig if fig is None: fig = plt.figure(num=fgnm, figsize=fgsz) fig.clf() ax = fig.gca() elif ax is None: ax = fig.gca() # Set defaults for line width and marker size if 'lw' not in kwargs and 'linewidth' not in kwargs: kwargs['lw'] = 1.5 if 'ms' not in kwargs and 'markersize' not in kwargs: kwargs['ms'] = 6.0 if ptyp not in ('plot', 'semilogx', 'semilogy', 'loglog'): raise ValueError("Invalid plot type '%s'" % ptyp) pltmth = getattr(ax, ptyp) if x is None: pltln = pltmth(y, **kwargs) else: pltln = pltmth(x, y, **kwargs) ax.fmt_xdata = lambda x: "{: .2f}".format(x) ax.fmt_ydata = lambda x: "{: .2f}".format(x) if title is not None: ax.set_title(title) if xlbl is not None: ax.set_xlabel(xlbl) if ylbl is not None: ax.set_ylabel(ylbl) if lgnd is not None: ax.legend(lgnd, loc=lglc) attach_keypress(fig) attach_zoom(ax) if have_mpldc: mpldc.datacursor(pltln) if figp is None: fig.show() return fig, ax
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/plot.py#L175-L285
scatter plot
python
def scatter(self, x, y, **kwargs): """Plot a scatter chart using metadata columns see pyam.plotting.scatter() for all available options """ variables = self.data['variable'].unique() xisvar = x in variables yisvar = y in variables if not xisvar and not yisvar: cols = [x, y] + self._discover_meta_cols(**kwargs) df = self.meta[cols].reset_index() elif xisvar and yisvar: # filter pivot both and rename dfx = ( self .filter(variable=x) .as_pandas(with_metadata=kwargs) .rename(columns={'value': x, 'unit': 'xunit'}) .set_index(YEAR_IDX) .drop('variable', axis=1) ) dfy = ( self .filter(variable=y) .as_pandas(with_metadata=kwargs) .rename(columns={'value': y, 'unit': 'yunit'}) .set_index(YEAR_IDX) .drop('variable', axis=1) ) df = dfx.join(dfy, lsuffix='_left', rsuffix='').reset_index() else: # filter, merge with meta, and rename value column to match var var = x if xisvar else y df = ( self .filter(variable=var) .as_pandas(with_metadata=kwargs) .rename(columns={'value': var}) ) ax = plotting.scatter(df.dropna(), x, y, **kwargs) return ax
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1189-L1229
scatter plot
python
def plot(self, x, y, **kw): """plot after clearing current plot """ self.panel.plot(x, y, **kw)
https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/wxmplot/plotframe.py#L34-L36
scatter plot
python
def _do_scatter_var(v, parallel): """Logic for scattering a variable. """ # For batches, scatter records only at the top level (double nested) if parallel.startswith("batch") and workflow.is_cwl_record(v): return (tz.get_in(["type", "type"], v) == "array" and tz.get_in(["type", "type", "type"], v) == "array") # Otherwise, scatter arrays else: return (tz.get_in(["type", "type"], v) == "array")
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/create.py#L352-L361
scatter plot
python
def scatter_plot(data, x, y, by=None, ax=None, figsize=None, grid=False, **kwargs): """ Make a scatter plot from two DataFrame columns Parameters ---------- data : DataFrame x : Column name for the x-axis values y : Column name for the y-axis values ax : Matplotlib axis object figsize : A tuple (width, height) in inches grid : Setting this to True will show the grid kwargs : other plotting keyword arguments To be passed to scatter function Returns ------- matplotlib.Figure """ import matplotlib.pyplot as plt kwargs.setdefault('edgecolors', 'none') def plot_group(group, ax): xvals = group[x].values yvals = group[y].values ax.scatter(xvals, yvals, **kwargs) ax.grid(grid) if by is not None: fig = _grouped_plot(plot_group, data, by=by, figsize=figsize, ax=ax) else: if ax is None: fig = plt.figure() ax = fig.add_subplot(111) else: fig = ax.get_figure() plot_group(data, ax) ax.set_ylabel(pprint_thing(y)) ax.set_xlabel(pprint_thing(x)) ax.grid(grid) return fig
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L2284-L2328
scatter plot
python
def plot (data, pconfig=None): """ Plot a scatter plot with X,Y data. :param data: 2D dict, first keys as sample names, then x:y data pairs :param pconfig: optional dict with config key:value pairs. See CONTRIBUTING.md :return: HTML and JS, ready to be inserted into the page """ if pconfig is None: pconfig = {} # Allow user to overwrite any given config for this plot if 'id' in pconfig and pconfig['id'] and pconfig['id'] in config.custom_plot_config: for k, v in config.custom_plot_config[pconfig['id']].items(): pconfig[k] = v # Given one dataset - turn it into a list if type(data) is not list: data = [data] # Generate the data dict structure expected by HighCharts series plotdata = list() for data_index, ds in enumerate(data): d = list() for s_name in ds: # Ensure any overwritting conditionals from data_labels (e.g. ymax) are taken in consideration series_config = pconfig.copy() if 'data_labels' in pconfig and type(pconfig['data_labels'][data_index]) is dict: # if not a dict: only dataset name is provided series_config.update(pconfig['data_labels'][data_index]) if type(ds[s_name]) is not list: ds[s_name] = [ ds[s_name] ] for k in ds[s_name]: if k['x'] is not None: if 'xmax' in series_config and float(k['x']) > float(series_config['xmax']): continue if 'xmin' in series_config and float(k['x']) < float(series_config['xmin']): continue if k['y'] is not None: if 'ymax' in series_config and float(k['y']) > float(series_config['ymax']): continue if 'ymin' in series_config and float(k['y']) < float(series_config['ymin']): continue this_series = { 'x': k['x'], 'y': k['y'] } try: this_series['name'] = "{}: {}".format(s_name, k['name']) except KeyError: this_series['name'] = s_name try: this_series['color'] = k['color'] except KeyError: try: this_series['color'] = series_config['colors'][s_name] except KeyError: pass d.append(this_series) plotdata.append(d) # Add on annotation data series try: if pconfig.get('extra_series'): extra_series = pconfig['extra_series'] if type(pconfig['extra_series']) == dict: extra_series = [[ pconfig['extra_series'] ]] elif type(pconfig['extra_series']) == list and type(pconfig['extra_series'][0]) == dict: extra_series = [ pconfig['extra_series'] ] for i, es in enumerate(extra_series): for s in es: plotdata[i].append(s) except (KeyError, IndexError): pass # Make a plot return highcharts_scatter_plot(plotdata, pconfig)
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/plots/scatter.py#L14-L85
scatter plot
python
def tsne(adata, **kwargs) -> Union[Axes, List[Axes], None]: """\ Scatter plot in tSNE basis. Parameters ---------- {adata_color_etc} {edges_arrows} {scatter_bulk} {show_save_ax} Returns ------- If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it. """ return plot_scatter(adata, 'tsne', **kwargs)
https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/plotting/_tools/scatterplots.py#L289-L304
scatter plot
python
def plot(var_item, off_screen=None, full_screen=False, screenshot=None, interactive=True, cpos=None, window_size=None, show_bounds=False, show_axes=True, notebook=None, background=None, text='', return_img=False, eye_dome_lighting=False, use_panel=None, **kwargs): """ Convenience plotting function for a vtk or numpy object. Parameters ---------- item : vtk or numpy object VTK object or numpy array to be plotted. off_screen : bool Plots off screen when True. Helpful for saving screenshots without a window popping up. full_screen : bool, optional Opens window in full screen. When enabled, ignores window_size. Default False. screenshot : str or bool, optional Saves screenshot to file when enabled. See: help(vtkinterface.Plotter.screenshot). Default disabled. When True, takes screenshot and returns numpy array of image. window_size : list, optional Window size in pixels. Defaults to [1024, 768] show_bounds : bool, optional Shows mesh bounds when True. Default False. Alias ``show_grid`` also accepted. notebook : bool, optional When True, the resulting plot is placed inline a jupyter notebook. Assumes a jupyter console is active. show_axes : bool, optional Shows a vtk axes widget. Enabled by default. text : str, optional Adds text at the bottom of the plot. **kwargs : optional keyword arguments See help(Plotter.add_mesh) for additional options. Returns ------- cpos : list List of camera position, focal point, and view up. img : numpy.ndarray Array containing pixel RGB and alpha. Sized: [Window height x Window width x 3] for transparent_background=False [Window height x Window width x 4] for transparent_background=True Returned only when screenshot enabled """ if notebook is None: if run_from_ipython(): try: notebook = type(get_ipython()).__module__.startswith('ipykernel.') except NameError: pass if notebook: off_screen = notebook plotter = Plotter(off_screen=off_screen, notebook=notebook) if show_axes: plotter.add_axes() plotter.set_background(background) if isinstance(var_item, list): if len(var_item) == 2: # might be arrows isarr_0 = isinstance(var_item[0], np.ndarray) isarr_1 = isinstance(var_item[1], np.ndarray) if isarr_0 and isarr_1: plotter.add_arrows(var_item[0], var_item[1]) else: for item in var_item: plotter.add_mesh(item, **kwargs) else: for item in var_item: plotter.add_mesh(item, **kwargs) else: plotter.add_mesh(var_item, **kwargs) if text: plotter.add_text(text) if show_bounds or kwargs.get('show_grid', False): if kwargs.get('show_grid', False): plotter.show_grid() else: plotter.show_bounds() if cpos is None: cpos = plotter.get_default_cam_pos() plotter.camera_position = cpos plotter.camera_set = False else: plotter.camera_position = cpos if eye_dome_lighting: plotter.enable_eye_dome_lighting() result = plotter.show(window_size=window_size, auto_close=False, interactive=interactive, full_screen=full_screen, screenshot=screenshot, return_img=return_img, use_panel=use_panel) # close and return camera position and maybe image plotter.close() # Result will be handled by plotter.show(): cpos or [cpos, img] return result
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L140-L260
scatter plot
python
def plot(self, name, funcname): """Plot item""" sw = self.shellwidget if sw._reading: sw.dbg_exec_magic('varexp', '--%s %s' % (funcname, name)) else: sw.execute("%%varexp --%s %s" % (funcname, name))
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1636-L1642
scatter plot
python
def scatterviz(X, y=None, ax=None, features=None, classes=None, color=None, colormap=None, markers=None, alpha=1.0, **kwargs): """Displays a bivariate scatter plot. This helper function is a quick wrapper to utilize the ScatterVisualizer (Transformer) for one-off analysis. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features y : ndarray or Series of length n, default: None An array or series of target or class values ax : matplotlib axes, default: None The axes to plot the figure on. features : list of strings, default: None The names of two features or columns. More than that will raise an error. classes : list of strings, default: None The names of the classes in the target color : list or tuple of colors, default: None Specify the colors for each individual class colormap : string or matplotlib cmap, default: None Sequential colormap for continuous target markers : iterable of strings, default: ,+o*vhd Matplotlib style markers for points on the scatter plot points alpha : float, default: 1.0 Specify a transparency where 1 is completely opaque and 0 is completely transparent. This property makes densely clustered points more visible. Returns ------- ax : matplotlib axes Returns the axes that the parallel coordinates were drawn on. """ # Instantiate the visualizer visualizer = ScatterVisualizer(ax=ax, features=features, classes=classes, color=color, colormap=colormap, markers=markers, alpha=alpha, **kwargs) # Fit and transform the visualizer (calls draw) visualizer.fit(X, y, **kwargs) visualizer.transform(X) # Return the axes object on the visualizer return visualizer.ax
https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/contrib/scatter.py#L32-L94
scatter plot
python
def plot(self,*args,**kwargs): """ NAME: plot PURPOSE: plot the snapshot INPUT: OUTPUT: HISTORY: 2011-08-15 - Started - Bovy (NYU) """ labeldict= {'t':r'$t$','R':r'$R$','vR':r'$v_R$','vT':r'$v_T$', 'z':r'$z$','vz':r'$v_z$','phi':r'$\phi$', 'x':r'$x$','y':r'$y$','vx':r'$v_x$','vy':r'$v_y$'} #Defaults if not kwargs.has_key('d1') and not kwargs.has_key('d2'): if len(self.orbits[0].vxvv) == 3: d1= 'R' d2= 'vR' elif len(self.orbits[0].vxvv) == 4: d1= 'x' d2= 'y' elif len(self.orbits[0].vxvv) == 2: d1= 'x' d2= 'vx' elif len(self.orbits[0].vxvv) == 5 \ or len(self.orbits[0].vxvv) == 6: d1= 'R' d2= 'z' elif not kwargs.has_key('d1'): d2= kwargs['d2'] kwargs.pop('d2') d1= 't' elif not kwargs.has_key('d2'): d1= kwargs['d1'] kwargs.pop('d1') d2= 't' else: d1= kwargs['d1'] kwargs.pop('d1') d2= kwargs['d2'] kwargs.pop('d2')
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/snapshot/GadgetSnapshot.py#L35-L77
scatter plot
python
def scatter_plot(self, ax, topic_dims, t=None, ms_limits=True, **kwargs_plot): """ 2D or 3D scatter plot. :param axes ax: matplotlib axes (use Axes3D if 3D data) :param tuple topic_dims: list of (topic, dims) tuples, where topic is a string and dims is a list of dimensions to be plotted for that topic. :param int t: time indexes to be plotted :param dict kwargs_plot: argument to be passed to matplotlib's plot function, e.g. the style of the plotted points 'or' :param bool ms_limits: if set to True, automatically set axes boundaries to the sensorimotor boundaries (default: True) """ plot_specs = {'marker': 'o', 'linestyle': 'None'} plot_specs.update(kwargs_plot) # t_bound = float('inf') # if t is None: # for topic, _ in topic_dims: # t_bound = min(t_bound, self.counts[topic]) # t = range(t_bound) # data = self.pack(topic_dims, t) data = self.data_t(topic_dims, t) ax.plot(*(data.T), **plot_specs) if ms_limits: ax.axis(self.axes_limits(topic_dims))
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/experiment/log.py#L67-L93
scatter plot
python
def scatter2d(data, **kwargs): """Create a 2D scatter plot Builds upon `matplotlib.pyplot.scatter` with nice defaults and handles categorical colors / legends better. Parameters ---------- data : array-like, shape=[n_samples, n_features] Input data. Only the first two components will be used. c : list-like or None, optional (default: None) Color vector. Can be a single color value (RGB, RGBA, or named matplotlib colors), an array of these of length n_samples, or a list of discrete or continuous values of any data type. If `c` is not a single or list of matplotlib colors, the values in `c` will be used to populate the legend / colorbar with colors from `cmap` cmap : `matplotlib` colormap, str, dict or None, optional (default: None) matplotlib colormap. If None, uses `tab20` for discrete data and `inferno` for continuous data. If a dictionary, expects one key for every unique value in `c`, where values are valid matplotlib colors (hsv, rbg, rgba, or named colors) s : float, optional (default: 1) Point size. discrete : bool or None, optional (default: None) If True, the legend is categorical. If False, the legend is a colorbar. If None, discreteness is detected automatically. Data containing non-numeric `c` is always discrete, and numeric data with 20 or less unique values is discrete. ax : `matplotlib.Axes` or None, optional (default: None) axis on which to plot. If None, an axis is created legend : bool, optional (default: True) States whether or not to create a legend. If data is continuous, the legend is a colorbar. figsize : tuple, optional (default: None) Tuple of floats for creation of new `matplotlib` figure. Only used if `ax` is None. xticks : True, False, or list-like (default: False) If True, keeps default x ticks. If False, removes x ticks. If a list, sets custom x ticks yticks : True, False, or list-like (default: False) If True, keeps default y ticks. If False, removes y ticks. If a list, sets custom y ticks zticks : True, False, or list-like (default: False) If True, keeps default z ticks. If False, removes z ticks. If a list, sets custom z ticks. Only used for 3D plots. xticklabels : True, False, or list-like (default: True) If True, keeps default x tick labels. If False, removes x tick labels. If a list, sets custom x tick labels yticklabels : True, False, or list-like (default: True) If True, keeps default y tick labels. If False, removes y tick labels. If a list, sets custom y tick labels zticklabels : True, False, or list-like (default: True) If True, keeps default z tick labels. If False, removes z tick labels. If a list, sets custom z tick labels. Only used for 3D plots. label_prefix : str or None (default: "PHATE") Prefix for all axis labels. Axes will be labelled `label_prefix`1, `label_prefix`2, etc. Can be overriden by setting `xlabel`, `ylabel`, and `zlabel`. xlabel : str or None (default : None) Label for the x axis. Overrides the automatic label given by label_prefix. If None and label_prefix is None, no label is set. ylabel : str or None (default : None) Label for the y axis. Overrides the automatic label given by label_prefix. If None and label_prefix is None, no label is set. zlabel : str or None (default : None) Label for the z axis. Overrides the automatic label given by label_prefix. If None and label_prefix is None, no label is set. Only used for 3D plots. title : str or None (default: None) axis title. If None, no title is set. legend_title : str (default: "") title for the colorbar of legend legend_loc : int or string or pair of floats, default: 'best' Matplotlib legend location. Only used for discrete data. See <https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html> for details. filename : str or None (default: None) file to which the output is saved dpi : int or None, optional (default: None) The resolution in dots per inch. If None it will default to the value savefig.dpi in the matplotlibrc file. If 'figure' it will set the dpi to be the value of the figure. Only used if filename is not None. **plot_kwargs : keyword arguments Extra arguments passed to `matplotlib.pyplot.scatter`. Returns ------- ax : `matplotlib.Axes` axis on which plot was drawn Examples -------- >>> import phate >>> import matplotlib.pyplot as plt >>> ### >>> # Running PHATE >>> ### >>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20, ... branch_length=100) >>> tree_data.shape (2000, 100) >>> phate_operator = phate.PHATE(k=5, a=20, t=150) >>> tree_phate = phate_operator.fit_transform(tree_data) >>> tree_phate.shape (2000, 2) >>> ### >>> # Plotting using phate.plot >>> ### >>> phate.plot.scatter2d(tree_phate, c=tree_clusters) >>> # You can also pass the PHATE operator instead of data >>> phate.plot.scatter2d(phate_operator, c=tree_clusters) >>> phate.plot.scatter3d(phate_operator, c=tree_clusters) >>> ### >>> # Using a cmap dictionary >>> ### >>> import numpy as np >>> X = np.random.normal(0,1,[1000,2]) >>> c = np.random.choice(['a','b'], 1000, replace=True) >>> X[c=='a'] += 10 >>> phate.plot.scatter2d(X, c=c, cmap={'a' : [1,0,0,1], 'b' : 'xkcd:sky blue'}) """ warnings.warn("`phate.plot.scatter2d` is deprecated. " "Use `scprep.plot.scatter2d` instead.", FutureWarning) data = _get_plot_data(data, ndim=2) return scprep.plot.scatter2d(data, **kwargs)
https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/plot.py#L220-L345
scatter plot
python
def scatter(self, x, y, xerr=None, yerr=None, cov=None, corr=None, s_expr=None, c_expr=None, labels=None, selection=None, length_limit=50000, length_check=True, label=None, xlabel=None, ylabel=None, errorbar_kwargs={}, ellipse_kwargs={}, **kwargs): """Viz (small amounts) of data in 2d using a scatter plot Convenience wrapper around pylab.scatter when for working with small DataFrames or selections :param x: Expression for x axis :param y: Idem for y :param s_expr: When given, use if for the s (size) argument of pylab.scatter :param c_expr: When given, use if for the c (color) argument of pylab.scatter :param labels: Annotate the points with these text values :param selection: Single selection expression, or None :param length_limit: maximum number of rows it will plot :param length_check: should we do the maximum row check or not? :param label: label for the legend :param xlabel: label for x axis, if None .label(x) is used :param ylabel: label for y axis, if None .label(y) is used :param errorbar_kwargs: extra dict with arguments passed to plt.errorbar :param kwargs: extra arguments passed to pylab.scatter :return: """ import pylab as plt x = _ensure_strings_from_expressions(x) y = _ensure_strings_from_expressions(y) label = str(label or selection) selection = _ensure_strings_from_expressions(selection) if length_check: count = self.count(selection=selection) if count > length_limit: raise ValueError("the number of rows (%d) is above the limit (%d), pass length_check=False, or increase length_limit" % (count, length_limit)) x_values = self.evaluate(x, selection=selection) y_values = self.evaluate(y, selection=selection) if s_expr: kwargs["s"] = self.evaluate(s_expr, selection=selection) if c_expr: kwargs["c"] = self.evaluate(c_expr, selection=selection) plt.xlabel(xlabel or self.label(x)) plt.ylabel(ylabel or self.label(y)) s = plt.scatter(x_values, y_values, label=label, **kwargs) if labels: label_values = self.evaluate(labels, selection=selection) for i, label_value in enumerate(label_values): plt.annotate(label_value, (x_values[i], y_values[i])) xerr_values = None yerr_values = None if cov is not None or corr is not None: from matplotlib.patches import Ellipse sx = self.evaluate(xerr, selection=selection) sy = self.evaluate(yerr, selection=selection) if corr is not None: sxy = self.evaluate(corr, selection=selection) * sx * sy elif cov is not None: sxy = self.evaluate(cov, selection=selection) cov_matrix = np.zeros((len(sx), 2, 2)) cov_matrix[:,0,0] = sx**2 cov_matrix[:,1,1] = sy**2 cov_matrix[:,0,1] = cov_matrix[:,1,0] = sxy ax = plt.gca() ellipse_kwargs = dict(ellipse_kwargs) ellipse_kwargs['facecolor'] = ellipse_kwargs.get('facecolor', 'none') ellipse_kwargs['edgecolor'] = ellipse_kwargs.get('edgecolor', 'black') for i in range(len(sx)): eigen_values, eigen_vectors = np.linalg.eig(cov_matrix[i]) indices = np.argsort(eigen_values)[::-1] eigen_values = eigen_values[indices] eigen_vectors = eigen_vectors[:,indices] v1 = eigen_vectors[:, 0] v2 = eigen_vectors[:, 1] varx = cov_matrix[i, 0, 0] vary = cov_matrix[i, 1, 1] angle = np.arctan2(v1[1], v1[0]) # round off errors cause negative values? if eigen_values[1] < 0 and abs((eigen_values[1]/eigen_values[0])) < 1e-10: eigen_values[1] = 0 if eigen_values[0] < 0 or eigen_values[1] < 0: raise ValueError('neg val') width, height = np.sqrt(np.max(eigen_values)), np.sqrt(np.min(eigen_values)) e = Ellipse(xy=(x_values[i], y_values[i]), width=width, height=height, angle=np.degrees(angle), **ellipse_kwargs) ax.add_artist(e) else: if xerr is not None: if _issequence(xerr): assert len(xerr) == 2, "if xerr is a sequence it should be of length 2" xerr_values = [self.evaluate(xerr[0], selection=selection), self.evaluate(xerr[1], selection=selection)] else: xerr_values = self.evaluate(xerr, selection=selection) if yerr is not None: if _issequence(yerr): assert len(yerr) == 2, "if yerr is a sequence it should be of length 2" yerr_values = [self.evaluate(yerr[0], selection=selection), self.evaluate(yerr[1], selection=selection)] else: yerr_values = self.evaluate(yerr, selection=selection) if xerr_values is not None or yerr_values is not None: errorbar_kwargs = dict(errorbar_kwargs) errorbar_kwargs['fmt'] = errorbar_kwargs.get('fmt', 'none') plt.errorbar(x_values, y_values, yerr=yerr_values, xerr=xerr_values, **errorbar_kwargs) return s
https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-viz/vaex/viz/mpl.py#L188-L284
scatter plot
python
def plot_target(target, ax): """Ajoute la target au plot""" ax.scatter(target[0], target[1], target[2], c="red", s=80)
https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/plot_utils.py#L57-L59
scatter plot
python
def scatter2d(data_list, channels=[0,1], xscale='logicle', yscale='logicle', xlabel=None, ylabel=None, xlim=None, ylim=None, title=None, color=None, savefig=None, **kwargs): """ Plot 2D scatter plot from one or more FCSData objects or numpy arrays. Parameters ---------- data_list : array or FCSData or list of array or list of FCSData Flow cytometry data to plot. channels : list of int, list of str Two channels to use for the plot. savefig : str, optional The name of the file to save the figure to. If None, do not save. Other parameters ---------------- xscale : str, optional Scale of the x axis, either ``linear``, ``log``, or ``logicle``. yscale : str, optional Scale of the y axis, either ``linear``, ``log``, or ``logicle``. xlabel : str, optional Label to use on the x axis. If None, attempts to extract channel name from last data object. ylabel : str, optional Label to use on the y axis. If None, attempts to extract channel name from last data object. xlim : tuple, optional Limits for the x axis. If None, attempts to extract limits from the range of the last data object. ylim : tuple, optional Limits for the y axis. If None, attempts to extract limits from the range of the last data object. title : str, optional Plot title. color : matplotlib color or list of matplotlib colors, optional Color for the scatter plot. It can be a list with the same length as `data_list`. If `color` is not specified, elements from `data_list` are plotted with colors taken from the module-level variable `cmap_default`. kwargs : dict, optional Additional parameters passed directly to matploblib's ``scatter``. Notes ----- `scatter2d` calls matplotlib's ``scatter`` function for each object in data_list. Additional keyword arguments provided to `scatter2d` are passed directly to ``plt.scatter``. """ # Check appropriate number of channels if len(channels) != 2: raise ValueError('two channels need to be specified') # Convert to list if necessary if not isinstance(data_list, list): data_list = [data_list] # Default colors if color is None: color = [cmap_default(i) for i in np.linspace(0, 1, len(data_list))] # Convert color to list, if necessary if not isinstance(color, list): color = [color]*len(data_list) # Iterate through data_list for i, data in enumerate(data_list): # Get channels to plot data_plot = data[:, channels] # Make scatter plot plt.scatter(data_plot[:,0], data_plot[:,1], s=5, alpha=0.25, color=color[i], **kwargs) # Set labels if specified, else try to extract channel names if xlabel is not None: plt.xlabel(xlabel) elif hasattr(data_plot, 'channels'): plt.xlabel(data_plot.channels[0]) if ylabel is not None: plt.ylabel(ylabel) elif hasattr(data_plot, 'channels'): plt.ylabel(data_plot.channels[1]) # Set scale of axes if xscale=='logicle': plt.gca().set_xscale(xscale, data=data_list, channel=channels[0]) else: plt.gca().set_xscale(xscale) if yscale=='logicle': plt.gca().set_yscale(yscale, data=data_list, channel=channels[1]) else: plt.gca().set_yscale(yscale) # Set plot limits if specified, else extract range from data_list. # ``.hist_bins`` with one bin works better for visualization that # ``.range``, because it deals with two issues. First, it automatically # deals with range values that are outside the domain of the current scaling # (e.g. when the lower range value is zero and the scaling is logarithmic). # Second, it takes into account events that are outside the limits specified # by .range (e.g. negative events will be shown with logicle scaling, even # when the lower range is zero). if xlim is None: xlim = [np.inf, -np.inf] for data in data_list: if hasattr(data, 'hist_bins') and \ hasattr(data.hist_bins, '__call__'): xlim_data = data.hist_bins(channels=channels[0], nbins=1, scale=xscale) xlim[0] = xlim_data[0] if xlim_data[0] < xlim[0] else xlim[0] xlim[1] = xlim_data[1] if xlim_data[1] > xlim[1] else xlim[1] plt.xlim(xlim) if ylim is None: ylim = [np.inf, -np.inf] for data in data_list: if hasattr(data, 'hist_bins') and \ hasattr(data.hist_bins, '__call__'): ylim_data = data.hist_bins(channels=channels[1], nbins=1, scale=yscale) ylim[0] = ylim_data[0] if ylim_data[0] < ylim[0] else ylim[0] ylim[1] = ylim_data[1] if ylim_data[1] > ylim[1] else ylim[1] plt.ylim(ylim) # Title if title is not None: plt.title(title) # Save if necessary if savefig is not None: plt.tight_layout() plt.savefig(savefig, dpi=savefig_dpi) plt.close()
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/plot.py#L1259-L1405
scatter plot
python
def plotMatches2(listofNValues, errors, listOfScales, scaleErrors, fileName = "images/scalar_matches.pdf"): """ Plot two figures side by side in an aspect ratio appropriate for the paper. """ w, h = figaspect(0.4) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(w,h)) plotMatches(listofNValues, errors, fileName=None, fig=fig, ax=ax1) plotScaledMatches(listOfScales, scaleErrors, fileName=None, fig=fig, ax=ax2) plt.savefig(fileName) plt.close()
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/scalar_sdrs.py#L570-L583
scatter plot
python
def scatter(self, canvas, X, Y, Z=None, color=None, vmin=None, vmax=None, label=None, **kwargs): """ Make a scatter plot between X and Y on the canvas given. the kwargs are plotting library specific kwargs! :param canvas: the plotting librarys specific canvas to plot on. :param array-like X: the inputs to plot. :param array-like Y: the outputs to plot. :param array-like Z: the Z level to plot (if plotting 3d). :param array-like c: the colorlevel for each point. :param float vmin: minimum colorscale :param float vmax: maximum colorscale :param kwargs: the specific kwargs for your plotting library """ raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/plotting/abstract_plotting_library.py#L148-L163
scatter plot
python
def plot(self, key, funcname): """Plot item""" data = self.model.get_data() import spyder.pyplot as plt plt.figure() getattr(plt, funcname)(data[key]) plt.show()
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1348-L1354
scatter plot
python
def plot_raster(self,cell_dimension='N',time_dimension=0, resolution=1.0,units=None,min_t=None,max_t=None, weight_function=None,normalize_time=True,normalize_n=True, start_units_with_0=True,**kwargs): """Plots a raster plot with `cell_dimension` as y and `time_dimension` as x (default: 'N' and 0). Accepts the same keyword arguments as matplotlib.pylab.plot() for points, eg. `marker`, `markerfacecolor`, `markersize` (or `ms`), `markeredgecolor`. See help for :func:`matplotlib.pylab.plot()`. Examples -------- >>> import numpy as np >>> from litus import spikes >>> spiking_data = np.random.rand(2000,20,20) < 0.01 >>> s = spikes.SpikeContainer(np.transpose(np.where(spiking_data)),labels='txy') >>> s['N'] = s['x']+20*s['y'] >>> s.plot_raster('N','t') >>> s(t__gt=1000,t__lt=1500,x__lt=2).plot_raster(ms=10,marker='$\\alpha$') # default: 'N' >>> s(t__gt=1000,t__lt=1500,y__lt=2).plot_raster(ms=10,marker='$\\beta$') # default: 'N' >>> s(n=350).plot_raster('n','t_rescaled',ms=10,marker='$\\gamma$') """ if bool(self): import matplotlib.pylab as plt plt.plot(self[time_dimension],self[cell_dimension],'.',**kwargs) plt.xlim(min_t, max_t)
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L1246-L1274
scatter plot
python
def plot(self, legend=None, tracks=None, track_titles=None, alias=None, basis=None, return_fig=False, extents='td', **kwargs): """ Plot multiple tracks. Args: legend (striplog.legend): A legend instance. tracks (list): A list of strings and/or lists of strings. The tracks you want to plot from ``data``. Optional, but you will usually want to give it. track_titles (list): Optional. A list of strings and/or lists of strings. The names to give the tracks, if you don't want welly to guess. alias (dict): a dictionary mapping mnemonics to lists of mnemonics. basis (ndarray): Optional. The basis of the plot, if you don't want welly to guess (probably the best idea). return_fig (bool): Whether to return the matplotlig figure. Default False. extents (str): What to use for the y limits: 'td' — plot 0 to TD. 'curves' — use a basis that accommodates all the curves. 'all' — use a basis that accommodates everything. (tuple) — give the upper and lower explictly. Returns: None. The plot is a side-effect. """ # These will be treated differently. depth_tracks = ['MD', 'TVD'] # Set tracks to 'all' if it's None. tracks = tracks or list(self.data.keys()) track_titles = track_titles or tracks # Figure out limits if basis is None: basis = self.survey_basis(keys=tracks) if extents == 'curves': upper, lower = basis[0], basis[-1] elif extents == 'td': try: upper, lower = 0, self.location.td except: m = "Could not read self.location.td, try extents='curves'" raise WellError(m) if not lower: lower = basis[-1] elif extents == 'all': raise NotImplementedError("You cannot do that yet.") else: try: upper, lower = extents except: upper, lower = basis[0], basis[-1] # Figure out widths because we can't us gs.update() for that. widths = [0.4 if t in depth_tracks else 1.0 for t in tracks] # Set up the figure. ntracks = len(tracks) fig = plt.figure(figsize=(2*ntracks, 12), facecolor='w') fig.suptitle(self.header.name, size=16, zorder=100, bbox=dict(facecolor='w', alpha=1.0, ec='none')) gs = mpl.gridspec.GridSpec(1, ntracks, width_ratios=widths) # Plot first axis. # kwargs = {} ax0 = fig.add_subplot(gs[0, 0]) ax0.depth_track = False track = tracks[0] if '.' in track: track, kwargs['field'] = track.split('.') if track in depth_tracks: ax0 = self._plot_depth_track(ax=ax0, md=basis, kind=track) else: try: # ...treating as a plottable object. ax0 = self.get_curve(track, alias=alias).plot(ax=ax0, legend=legend, **kwargs) except AttributeError: # ...it's not there. pass except TypeError: # ...it's a list. for t in track: try: ax0 = self.get_curve(t, alias=alias).plot(ax=ax0, legend=legend, **kwargs) except AttributeError: # ...it's not there. pass tx = ax0.get_xticks() ax0.set_xticks(tx[1:-1]) ax0.set_title(track_titles[0]) # Plot remaining axes. for i, track in enumerate(tracks[1:]): # kwargs = {} ax = fig.add_subplot(gs[0, i+1]) ax.depth_track = False if track in depth_tracks: ax = self._plot_depth_track(ax=ax, md=basis, kind=track) continue if '.' in track: track, kwargs['field'] = track.split('.') plt.setp(ax.get_yticklabels(), visible=False) try: # ...treating as a plottable object. ax = self.get_curve(track, alias=alias).plot(ax=ax, legend=legend, **kwargs) except AttributeError: # ...it's not there. continue except TypeError: # ...it's a list. for j, t in enumerate(track): if '.' in t: track, kwargs['field'] = track.split('.') try: ax = self.get_curve(t, alias=alias).plot(ax=ax, legend=legend, **kwargs) except AttributeError: continue except KeyError: continue tx = ax.get_xticks() ax.set_xticks(tx[1:-1]) ax.set_title(track_titles[i+1]) # Set sharing. axes = fig.get_axes() utils.sharey(axes) axes[0].set_ylim([lower, upper]) # Adjust the grid. gs.update(wspace=0) # Adjust spines and ticks for non-depth tracks. for ax in axes: if ax.depth_track: pass if not ax.depth_track: ax.set(yticks=[]) ax.autoscale(False) ax.yaxis.set_ticks_position('none') ax.spines['top'].set_visible(True) ax.spines['bottom'].set_visible(True) for sp in ax.spines.values(): sp.set_color('gray') if return_fig: return fig else: return None
https://github.com/agile-geoscience/welly/blob/ed4c991011d6290938fef365553041026ba29f42/welly/well.py#L525-L676
scatter plot
python
def plot(self, *args, **kwargs): """Plot lines and/or markers. If a 2D or higher Data object is passed, a lower dimensional channel can be plotted, provided the ``squeeze`` of the channel has ``ndim==1`` and the first axis does not span dimensions other than that spanned by the channel. Parameters ---------- data : 1D WrightTools.data.Data object Data to plot. channel : int or string (optional) Channel index or name. Default is 0. dynamic_range : boolean (optional) Force plotting of all contours, overloading for major extent. Only applies to signed data. Default is False. autolabel : {'none', 'both', 'x', 'y'} (optional) Parameterize application of labels directly from data object. Default is none. xlabel : string (optional) xlabel. Default is None. ylabel : string (optional) ylabel. Default is None. **kwargs matplotlib.axes.Axes.plot__ optional keyword arguments. __ https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.plot.html Returns ------- list list of matplotlib.lines.line2D objects """ args = list(args) # offer pop, append etc # unpack data object, if given if isinstance(args[0], Data): data = args.pop(0) channel = kwargs.pop("channel", 0) channel_index = wt_kit.get_index(data.channel_names, channel) squeeze = np.array(data.channels[channel_index].shape) == 1 xa = data.axes[0] for sq, xs in zip(squeeze, xa.shape): if sq and xs != 1: raise wt_exceptions.ValueError("Cannot squeeze axis to fit channel") squeeze = tuple([0 if i else slice(None) for i in squeeze]) zi = data.channels[channel_index].points xi = xa[squeeze] if not zi.ndim == 1: raise wt_exceptions.DimensionalityError(1, data.ndim) args = [xi, zi] + args else: data = None channel_index = 0 # labels self._apply_labels( autolabel=kwargs.pop("autolabel", False), xlabel=kwargs.pop("xlabel", None), ylabel=kwargs.pop("ylabel", None), data=data, channel_index=channel_index, ) # call parent return super().plot(*args, **kwargs)
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_base.py#L424-L486
scatter plot
python
def draw(self, X, y, **kwargs): """Called from the fit method, this method creates a scatter plot that draws each instance as a class or target colored point, whose location is determined by the feature data set. If y is not None, then it draws a scatter plot where each class is in a different color. """ nan_locs = self.get_nan_locs() if y is None: x_, y_ = list(zip(*nan_locs)) self.ax.scatter(x_, y_, alpha=self.alpha, marker=self.marker, label=None) else: self.draw_multi_dispersion_chart(nan_locs)
https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/contrib/missing/dispersion.py#L117-L130
scatter plot
python
def plot(self,axis=None,**kargs): """ - plot(axis=None, **kwarg): Finally, sphviewer.Scene class has its own plotting method. It shows the scene as seen by the camera. It is to say, it plots the particles according to their aparent coordinates; axis makes a reference to an existing axis. In case axis is None, the plot is made on the current axis. The kwargs are :class:`~matplotlib.lines.Line2D` properties: agg_filter: unknown alpha: float (0.0 transparent through 1.0 opaque) animated: [True | False] antialiased or aa: [True | False] axes: an :class:`~matplotlib.axes.Axes` instance clip_box: a :class:`matplotlib.transforms.Bbox` instance clip_on: [True | False] clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] color or c: any matplotlib color contains: a callable function dash_capstyle: ['butt' | 'round' | 'projecting'] dash_joinstyle: ['miter' | 'round' | 'bevel'] dashes: sequence of on/off ink in points data: 2D array (rows are x, y) or two 1D arrays drawstyle: [ 'default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post' ] figure: a :class:`matplotlib.figure.Figure` instance fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top'] gid: an id string label: any string linestyle or ls: [ ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''`` ] and any drawstyle in combination with a linestyle, e.g. ``'steps--'``. linewidth or lw: float value in points lod: [True | False] marker: [ ``7`` | ``4`` | ``5`` | ``6`` | ``'o'`` | ``'D'`` | ``'h'`` | ``'H'`` | ``'_'`` | ``''`` | ``'None'`` | ``' '`` | ``None`` | ``'8'`` | ``'p'`` | ``','`` | ``'+'`` | ``'.'`` | ``'s'`` | ``'*'`` | ``'d'`` | ``3`` | ``0`` | ``1`` | ``2`` | ``'1'`` | ``'3'`` | ``'4'`` | ``'2'`` | ``'v'`` | ``'<'`` | ``'>'`` | ``'^'`` | ``'|'`` | ``'x'`` | ``'$...$'`` | *tuple* | *Nx2 array* ] markeredgecolor or mec: any matplotlib color markeredgewidth or mew: float value in points markerfacecolor or mfc: any matplotlib color markerfacecoloralt or mfcalt: any matplotlib color markersize or ms: float markevery: None | integer | (startind, stride) picker: float distance in points or callable pick function ``fn(artist, event)`` pickradius: float distance in points rasterized: [True | False | None] snap: unknown solid_capstyle: ['butt' | 'round' | 'projecting'] solid_joinstyle: ['miter' | 'round' | 'bevel'] transform: a :class:`matplotlib.transforms.Transform` instance url: a url string visible: [True | False] xdata: 1D array ydata: 1D array zorder: any number kwargs *scalex* and *scaley*, if defined, are passed on to :meth:`~matplotlib.axes.Axes.autoscale_view` to determine whether the *x* and *y* axes are autoscaled; the default is *True*. Additional kwargs: hold = [True|False] overrides default hold state """ if(axis == None): axis = plt.gca() axis.plot(self.__x, self.__y, 'k.', **kargs)
https://github.com/alejandrobll/py-sphviewer/blob/f198bd9ed5adfb58ebdf66d169206e609fd46e42/sphviewer/Scene.py#L299-L359
scatter plot
python
def scatter(self, x, y, s=None, c=None, **kwds): """ Create a scatter plot with varying marker point size and color. The coordinates of each point are defined by two dataframe columns and filled circles are used to represent each point. This kind of plot is useful to see complex correlations between two variables. Points could be for instance natural 2D coordinates like longitude and latitude in a map or, in general, any pair of metrics that can be plotted against each other. Parameters ---------- x : int or str The column name or column position to be used as horizontal coordinates for each point. y : int or str The column name or column position to be used as vertical coordinates for each point. s : scalar or array_like, optional The size of each point. Possible values are: - A single scalar so all points have the same size. - A sequence of scalars, which will be used for each point's size recursively. For instance, when passing [2,14] all points size will be either 2 or 14, alternatively. c : str, int or array_like, optional The color of each point. Possible values are: - A single color string referred to by name, RGB or RGBA code, for instance 'red' or '#a98d19'. - A sequence of color strings referred to by name, RGB or RGBA code, which will be used for each point's color recursively. For instance ['green','yellow'] all points will be filled in green or yellow, alternatively. - A column name or position whose values will be used to color the marker points according to a colormap. **kwds Keyword arguments to pass on to :meth:`DataFrame.plot`. Returns ------- :class:`matplotlib.axes.Axes` or numpy.ndarray of them See Also -------- matplotlib.pyplot.scatter : Scatter plot using multiple input data formats. Examples -------- Let's see how to draw a scatter plot using coordinates from the values in a DataFrame's columns. .. plot:: :context: close-figs >>> df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1], ... [6.4, 3.2, 1], [5.9, 3.0, 2]], ... columns=['length', 'width', 'species']) >>> ax1 = df.plot.scatter(x='length', ... y='width', ... c='DarkBlue') And now with the color determined by a column as well. .. plot:: :context: close-figs >>> ax2 = df.plot.scatter(x='length', ... y='width', ... c='species', ... colormap='viridis') """ return self(kind='scatter', x=x, y=y, c=c, s=s, **kwds)
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L3463-L3542
scatter plot
python
def scatter(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d scatter plot, and returns the resulting Plot object. The function supports SArrays of dtypes: int, float. Parameters ---------- x : SArray The data to plot on the X axis of the scatter plot. Must be numeric (int/float). y : SArray The data to plot on the Y axis of the scatter plot. Must be the same length as `x`. Must be numeric (int/float). xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the scatter plot. Examples -------- Make a scatter plot. >>> x = turicreate.SArray([1,2,3,4,5]) >>> y = x * 2 >>> scplt = turicreate.visualization.scatter(x, y) """ if (not isinstance(x, tc.data_structures.sarray.SArray) or not isinstance(y, tc.data_structures.sarray.SArray) or x.dtype not in [int, float] or y.dtype not in [int, float]): raise ValueError("turicreate.visualization.scatter supports " + "SArrays of dtypes: int, float") # legit input title = _get_title(title) plt_ref = tc.extensions.plot_scatter(x, y, xlabel, ylabel,title) return Plot(plt_ref)
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/visualization/show.py#L145-L193
scatter plot
python
def plot_4(data, *args): """Scatter plot of score vs each param """ params = nonconstant_parameters(data) scores = np.array([d['mean_test_score'] for d in data]) order = np.argsort(scores) for key in params.keys(): if params[key].dtype == np.dtype('bool'): params[key] = params[key].astype(np.int) p_list = [] for key in params.keys(): x = params[key][order] y = scores[order] params = params.loc[order] try: radius = (np.max(x) - np.min(x)) / 100.0 except: print("error making plot4 for '%s'" % key) continue p_list.append(build_scatter_tooltip( x=x, y=y, radius=radius, add_line=False, tt=params, xlabel=key, title='Score vs %s' % key)) return p_list
https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/plot.py#L125-L149
scatter plot
python
def plot(self): """ Plot """ self.before_plot() self.do_plot_and_bestfit() self.after_plot() self.do_label() self.after_label() self.save() self.close() return self.outputdict
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/plot.py#L208-L219
scatter plot
python
def offline_plotly_scatter3d(df, x=0, y=1, z=-1): """ Plot an offline scatter plot colored according to the categories in the 'name' column. >> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/iris.csv') >> offline_plotly(df) """ 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
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/plots.py#L107-L172
scatter plot
python
def plot(self, show_test_labels=True, use_edge_lengths=True, collapse_outgroup=False, pct_tree_x=0.5, pct_tree_y=0.2, subset_tests=None, #toytree_kwargs=None, *args, **kwargs): """ Draw a multi-panel figure with tree, tests, and results Parameters: ----------- height: int ... width: int ... show_test_labels: bool ... use_edge_lengths: bool ... collapse_outgroups: bool ... pct_tree_x: float ... pct_tree_y: float ... subset_tests: list ... ... """ ## check for attributes if not self.newick: raise IPyradError("baba plot requires a newick treefile") if not self.tests: raise IPyradError("baba plot must have a .tests attribute") ## ensure tests is a list if isinstance(self.tests, dict): self.tests = [self.tests] ## re-decompose the tree ttree = toytree.tree( self.newick, orient='down', use_edge_lengths=use_edge_lengths, ) ## subset test to show fewer if subset_tests != None: #tests = self.tests[subset_tests] tests = [self.tests[i] for i in subset_tests] boots = self.results_boots[subset_tests] else: tests = self.tests boots = self.results_boots ## make the plot canvas, axes, panel = baba_panel_plot( ttree=ttree, tests=tests, boots=boots, show_test_labels=show_test_labels, use_edge_lengths=use_edge_lengths, collapse_outgroup=collapse_outgroup, pct_tree_x=pct_tree_x, pct_tree_y=pct_tree_y, *args, **kwargs) return canvas, axes, panel
https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/baba.py#L200-L282
scatter plot
python
def plot(self, key=None, cmap=None, ms=4, vmin=None, vmax=None, vmin_map=None, vmax_map=None, cmap_map=None, normt_map=False, ntMax=None, nchMax=None, nlbdMax=3, lls=None, lct=None, lcch=None, lclbd=None, cbck=None, inct=[1,10], incX=[1,5], inclbd=[1,10], fmt_t='06.3f', fmt_X='01.0f', invert=True, Lplot='In', dmarker=None, Bck=True, fs=None, dmargin=None, wintit=None, tit=None, fontsize=None, labelpad=None, draw=True, connect=True): """ Plot the data content in a generic interactive figure """ kh = _plot.Data_plot(self, key=key, indref=0, cmap=cmap, ms=ms, vmin=vmin, vmax=vmax, vmin_map=vmin_map, vmax_map=vmax_map, cmap_map=cmap_map, normt_map=normt_map, ntMax=ntMax, nchMax=nchMax, nlbdMax=nlbdMax, lls=lls, lct=lct, lcch=lcch, lclbd=lclbd, cbck=cbck, inct=inct, incX=incX, inclbd=inclbd, fmt_t=fmt_t, fmt_X=fmt_X, Lplot=Lplot, invert=invert, dmarker=dmarker, Bck=Bck, fs=fs, dmargin=dmargin, wintit=wintit, tit=tit, fontsize=fontsize, labelpad=labelpad, draw=draw, connect=connect) return kh
https://github.com/ToFuProject/tofu/blob/39d6b2e7ced9e13666572dfd37e19403f1d6ff8d/tofu/data/_core.py#L1582-L1605
scatter plot
python
def scatter(self, *args, **kwargs): """Adds a :py:class:`.ScatterSeries` to the chart. :param \*data: The data for the series as either (x,y) values or two big\ tuples/lists of x and y values respectively. :param str name: The name to be associated with the series. :param str color: The hex colour of the line. :param Number size: The size of each data point - generally the diameter. :param Number linewidth: The width in pixels of the data points' edge. :raises ValueError: if the size and length of the data doesn't match\ either format.""" if "color" not in kwargs: kwargs["color"] = self.next_color() series = ScatterSeries(*args, **kwargs) self.add_series(series)
https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/charts.py#L217-L232
scatter plot
python
def plot_1(data, *args): """Plot 1. All iterations (scatter plot)""" df_all = pd.DataFrame(data) df_params = nonconstant_parameters(data) return build_scatter_tooltip( x=df_all['id'], y=df_all['mean_test_score'], tt=df_params, title='All Iterations')
https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/plot.py#L57-L63
scatter plot
python
def scatter(x, y, names, path, plots, color="#4CB391", figformat="png", stat=None, log=False, minvalx=0, minvaly=0, title=None, plot_settings=None): """Create bivariate plots. Create four types of bivariate plots of x vs y, containing marginal summaries -A scatter plot with histograms on axes -A hexagonal binned plot with histograms on axes -A kernel density plot with density curves on axes -A pauvre-style plot using code from https://github.com/conchoecia/pauvre """ logging.info("Nanoplotter: Creating {} vs {} plots using statistics from {} reads.".format( names[0], names[1], x.size)) if not contains_variance([x, y], names): return [] sns.set(style="ticks", **plot_settings) maxvalx = np.amax(x) maxvaly = np.amax(y) plots_made = [] if plots["hex"]: hex_plot = Plot( path=path + "_hex." + figformat, title="{} vs {} plot using hexagonal bins".format(names[0], names[1])) plot = sns.jointplot( x=x, y=y, kind="hex", color=color, stat_func=stat, space=0, xlim=(minvalx, maxvalx), ylim=(minvaly, maxvaly), height=10) plot.set_axis_labels(names[0], names[1]) if log: hex_plot.title = hex_plot.title + " after log transformation of read lengths" ticks = [10**i for i in range(10) if not 10**i > 10 * (10**maxvalx)] plot.ax_joint.set_xticks(np.log10(ticks)) plot.ax_marg_x.set_xticks(np.log10(ticks)) plot.ax_joint.set_xticklabels(ticks) plt.subplots_adjust(top=0.90) plot.fig.suptitle(title or "{} vs {} plot".format(names[0], names[1]), fontsize=25) hex_plot.fig = plot hex_plot.save(format=figformat) plots_made.append(hex_plot) sns.set(style="darkgrid", **plot_settings) if plots["dot"]: dot_plot = Plot( path=path + "_dot." + figformat, title="{} vs {} plot using dots".format(names[0], names[1])) plot = sns.jointplot( x=x, y=y, kind="scatter", color=color, stat_func=stat, xlim=(minvalx, maxvalx), ylim=(minvaly, maxvaly), space=0, height=10, joint_kws={"s": 1}) plot.set_axis_labels(names[0], names[1]) if log: dot_plot.title = dot_plot.title + " after log transformation of read lengths" ticks = [10**i for i in range(10) if not 10**i > 10 * (10**maxvalx)] plot.ax_joint.set_xticks(np.log10(ticks)) plot.ax_marg_x.set_xticks(np.log10(ticks)) plot.ax_joint.set_xticklabels(ticks) plt.subplots_adjust(top=0.90) plot.fig.suptitle(title or "{} vs {} plot".format(names[0], names[1]), fontsize=25) dot_plot.fig = plot dot_plot.save(format=figformat) plots_made.append(dot_plot) if plots["kde"]: idx = np.random.choice(x.index, min(2000, len(x)), replace=False) kde_plot = Plot( path=path + "_kde." + figformat, title="{} vs {} plot using a kernel density estimation".format(names[0], names[1])) plot = sns.jointplot( x=x[idx], y=y[idx], kind="kde", clip=((0, np.Inf), (0, np.Inf)), xlim=(minvalx, maxvalx), ylim=(minvaly, maxvaly), space=0, color=color, stat_func=stat, shade_lowest=False, height=10) plot.set_axis_labels(names[0], names[1]) if log: kde_plot.title = kde_plot.title + " after log transformation of read lengths" ticks = [10**i for i in range(10) if not 10**i > 10 * (10**maxvalx)] plot.ax_joint.set_xticks(np.log10(ticks)) plot.ax_marg_x.set_xticks(np.log10(ticks)) plot.ax_joint.set_xticklabels(ticks) plt.subplots_adjust(top=0.90) plot.fig.suptitle(title or "{} vs {} plot".format(names[0], names[1]), fontsize=25) kde_plot.fig = plot kde_plot.save(format=figformat) plots_made.append(kde_plot) if plots["pauvre"] and names == ['Read lengths', 'Average read quality'] and log is False: pauvre_plot = Plot( path=path + "_pauvre." + figformat, title="{} vs {} plot using pauvre-style @conchoecia".format(names[0], names[1])) sns.set(style="white", **plot_settings) margin_plot(df=pd.DataFrame({"length": x, "meanQual": y}), Y_AXES=False, title=title or "Length vs Quality in Pauvre-style", plot_maxlen=None, plot_minlen=0, plot_maxqual=None, plot_minqual=0, lengthbin=None, qualbin=None, BASENAME="whatever", path=pauvre_plot.path, fileform=[figformat], dpi=600, TRANSPARENT=True, QUIET=True) plots_made.append(pauvre_plot) plt.close("all") return plots_made
https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/nanoplotter_main.py#L78-L206
scatter plot
python
def plot(self, size=1): """ Plot the values in the color palette as a horizontal array. See Seaborn's palplot function for inspiration. Parameters ---------- size : int scaling factor for size of the plot """ n = len(self) fig, ax = plt.subplots(1, 1, figsize=(n * size, size)) ax.imshow(np.arange(n).reshape(1,n), cmap=mpl.colors.ListedColormap(list(self)), interpolation="nearest", aspect="auto") ax.set_xticks(np.arange(n) - .5) ax.set_yticks([-.5, .5]) ax.set_xticklabels([]) ax.set_yticklabels([])
https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/style/palettes.py#L432-L451
scatter plot
python
def plot(self, sizescale=10, color=None, alpha=0.5, label=None, edgecolor='none', **kw): ''' Plot the ra and dec of the coordinates, at a given epoch, scaled by their magnitude. (This does *not* create a new empty figure.) Parameters ---------- sizescale : (optional) float The marker size for scatter for a star at the magnitudelimit. color : (optional) any valid color The color to plot (but there is a default for this catalog.) **kw : dict Additional keywords will be passed on to plt.scatter. Returns ------- plotted : outputs from the plots ''' # calculate the sizes of the stars (logarithmic with brightness?) size = np.maximum(sizescale*(1 + self.magnitudelimit - self.magnitude), 1) # make a scatter plot of the RA + Dec scatter = plt.scatter(self.ra, self.dec, s=size, color=color or self.color, label=label or '{} ({:.1f})'.format(self.name, self.epoch), alpha=alpha, edgecolor=edgecolor, **kw) return scatter
https://github.com/zkbt/the-friendly-stars/blob/50d3f979e79e63c66629065c75595696dc79802e/thefriendlystars/constellations/constellation.py#L281-L314
scatter plot
python
def plot_latent_scatter(self, labels=None, which_indices=None, legend=True, plot_limits=None, marker='<>^vsd', num_samples=1000, projection='2d', **kwargs): """ Plot a scatter plot of the latent space. :param array-like labels: a label for each data point (row) of the inputs :param (int, int) which_indices: which input dimensions to plot against each other :param bool legend: whether to plot the legend on the figure :param plot_limits: the plot limits for the plot :type plot_limits: (xmin, xmax, ymin, ymax) or ((xmin, xmax), (ymin, ymax)) :param str marker: markers to use - cycle if more labels then markers are given :param kwargs: the kwargs for the scatter plots """ canvas, projection, kwargs, sig_dims = _new_canvas(self, projection, kwargs, which_indices) X, _, _ = get_x_y_var(self) if labels is None: labels = np.ones(self.num_data) legend = False else: legend = find_best_layout_for_subplots(len(np.unique(labels)))[1] scatters = _plot_latent_scatter(canvas, X, sig_dims, labels, marker, num_samples, projection=projection, **kwargs) return pl().add_to_canvas(canvas, dict(scatter=scatters), legend=legend)
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/plotting/gpy_plot/latent_plots.py#L80-L108
scatter plot
python
def surface(x, y, z): """Surface plot. Parameters ---------- x : array-like, optional y : array-like, optional z : array-like, optional Returns ------- Chart """ data = [go.Surface(x=x, y=y, z=z)] return Chart(data=data)
https://github.com/jwkvam/plotlywrapper/blob/762b42912e824fecb1212c186900f2ebdd0ab12b/plotlywrapper.py#L987-L1002
scatter plot
python
def tplot(name, var_label=None, auto_color=True, interactive=False, combine_axes=True, nb=False, save_file=None, gui=False, qt=False, bokeh=False, save_png=None, display=True, testing=False): """ This is the function used to display the tplot variables stored in memory. The default output is to show the plots stacked on top of one another inside a GUI window. The GUI window has the option to export the plots in either PNG or HTML formats. .. note:: This plotting routine uses the python Bokeh library, which creates plots using HTML and Javascript. Bokeh is technically still in beta, so future patches to Bokeh may require updates to this function. Parameters: name : str / list List of tplot variables that will be plotted var_label : str, optional The name of the tplot variable you would like as a second x axis. auto_color : bool, optional Automatically color the plot lines. interactive : bool, optional If True, a secondary interactive plot will be generated next to spectrogram plots. Mousing over the spectrogram will display a slice of data from that time on the interactive chart. combine_axes : bool, optional If True, the axes are combined so that they all display the same x range. This also enables scrolling/zooming/panning on one plot to affect all of the other plots simultaneously. nb : bool, optional If True, the plot will be displayed inside of a current Jupyter notebook session. save_file : str, optional A full file name and path. If this option is set, the plot will be automatically saved to the file name provided in an HTML format. The plots can then be opened and viewed on any browser without any requirements. bokeh : bool, optional If True, plots data using bokeh Else (bokeh=False or omitted), plots data using PyQtGraph gui : bool, optional If True, then this function will output the 2 HTML components of the generated plots as string variables. This is useful if you are embedded the plots in your own GUI. For more information, see http://bokeh.pydata.org/en/latest/docs/user_guide/embed.html qt : bool, optional If True, then this function will display the plot inside of the Qt window. From this window, you can choose to export the plots as either an HTML file, or as a PNG. save_png : str, optional A full file name and path. If this option is set, the plot will be automatically saved to the file name provided in a PNG format. display: bool, optional If True, then this function will display the plotted tplot variables. Necessary to make this optional so we can avoid it in a headless server environment. testing: bool, optional If True, doesn't run the '(hasattr(sys, 'ps1'))' line that makes plots interactive - i.e., avoiding issues Returns: None Examples: >>> #Plot a single line in bokeh >>> import pytplot >>> x_data = [2,3,4,5,6] >>> y_data = [1,2,3,4,5] >>> pytplot.store_data("Variable1", data={'x':x_data, 'y':y_data}) >>> pytplot.tplot("Variable1",bokeh=True) >>> #Display two plots >>> x_data = [1,2,3,4,5] >>> y_data = [[1,5],[2,4],[3,3],[4,2],[5,1]] >>> pytplot.store_data("Variable2", data={'x':x_data, 'y':y_data}) >>> pytplot.tplot(["Variable1", "Variable2"]) >>> #Display 2 plots, using Variable1 as another x axis >>> x_data = [1,2,3] >>> y_data = [ [1,2,3] , [4,5,6], [7,8,9] ] >>> v_data = [1,2,3] >>> pytplot.store_data("Variable3", data={'x':x_data, 'y':y_data, 'v':v_data}) >>> pytplot.options("Variable3", 'spec', 1) >>> pytplot.tplot(["Variable2", "Variable3"], var_label='Variable1') >>> #Plot all 3 tplot variables, sending the output to an HTML file >>> pytplot.tplot(["Variable1", "Variable2", "Variable3"], save_file='C:/temp/pytplot_example.html') >>> #Plot all 3 tplot variables, sending the HTML output to a pair of strings >>> div, component = pytplot.tplot(["Variable1", "Variable2", "Variable3"], gui=True) """ if not pytplot.using_graphics and save_file is None: print("Qt was not successfully imported. Specify save_file to save the file as a .html file.") return # Check a bunch of things if not isinstance(name, list): name = [name] num_plots = 1 else: num_plots = len(name) for i in range(num_plots): if isinstance(name[i], int): name[i] = list(pytplot.data_quants.keys())[name[i]] if name[i] not in pytplot.data_quants.keys(): print(str(i) + " is currently not in pytplot") return if isinstance(var_label, int): var_label = list(pytplot.data_quants.keys())[var_label] if bokeh: layout = HTMLPlotter.generate_stack(name, var_label=var_label, auto_color=auto_color, combine_axes=combine_axes, interactive=interactive) # Output types if gui: script, div = components(layout) return script, div elif nb: output_notebook() show(layout) return elif save_file is not None: output_file(save_file, mode='inline') save(layout) return elif qt: available_qt_window = tplot_utilities.get_available_qt_window() dir_path = tempfile.gettempdir() # send to user's temp directory output_file(os.path.join(dir_path, "temp.html"), mode='inline') save(layout) new_layout = WebView() available_qt_window.resize(pytplot.tplot_opt_glob['window_size'][0] + 100, pytplot.tplot_opt_glob['window_size'][1] + 100) new_layout.resize(pytplot.tplot_opt_glob['window_size'][0], pytplot.tplot_opt_glob['window_size'][1]) dir_path = tempfile.gettempdir() # send to user's temp directory new_layout.setUrl(QtCore.QUrl.fromLocalFile(os.path.join(dir_path, "temp.html"))) available_qt_window.newlayout(new_layout) available_qt_window.show() available_qt_window.activateWindow() if testing: return if not (hasattr(sys, 'ps1')) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() return else: dir_path = tempfile.gettempdir() # send to user's temp directory output_file(os.path.join(dir_path, "temp.html"), mode='inline') show(layout) return else: if save_png is not None: layout = QtPlotter.generate_stack(name, var_label=var_label, combine_axes=combine_axes, mouse_moved_event=pytplot.hover_time.change_hover_time) layout.resize(pytplot.tplot_opt_glob['window_size'][0], pytplot.tplot_opt_glob['window_size'][1]) for i, item in enumerate(layout.items()): if type(item) == pg.graphicsItems.GraphicsLayout.GraphicsLayout: layout.items()[i].resize(pytplot.tplot_opt_glob['window_size'][0], pytplot.tplot_opt_glob['window_size'][1]) exporter = PyTPlot_Exporter.PytplotExporter(layout) exporter.parameters()['width'] = pytplot.tplot_opt_glob['window_size'][0] exporter.parameters()['height'] = pytplot.tplot_opt_glob['window_size'][1] exporter.export(save_png) if display: # Set up all things needed for when a user asks to save plot from window layout_orig = QtPlotter.generate_stack(name, var_label=var_label, combine_axes=combine_axes, mouse_moved_event=pytplot.hover_time.change_hover_time) layout_orig.resize(pytplot.tplot_opt_glob['window_size'][0], pytplot.tplot_opt_glob['window_size'][1]) for i, item in enumerate(layout_orig.items()): if type(item) == pg.graphicsItems.GraphicsLayout.GraphicsLayout: layout_orig.items()[i].resize(pytplot.tplot_opt_glob['window_size'][0], pytplot.tplot_opt_glob['window_size'][1]) exporter = QtPlotter.PytplotExporter(layout_orig) # Set up displayed plot window and grab plots to plot on it available_qt_window = tplot_utilities.get_available_qt_window() layout = QtPlotter.generate_stack(name, var_label=var_label, combine_axes=combine_axes, mouse_moved_event=pytplot.hover_time.change_hover_time) available_qt_window.newlayout(layout) available_qt_window.resize(pytplot.tplot_opt_glob['window_size'][0], pytplot.tplot_opt_glob['window_size'][1]) # Implement button that lets you save the PNG available_qt_window.init_savepng(exporter) # Show the plot window and plot available_qt_window.show() available_qt_window.activateWindow() if interactive: # Call 2D interactive window; This will only plot something when spectrograms are involved. interactiveplot.interactiveplot() static_list = [i for i in name if 'static' in pytplot.data_quants[i].extras] for tplot_var in static_list: # Call 2D static window; This will only plot something when spectrograms are involved. staticplot.static2dplot(tplot_var, pytplot.data_quants[tplot_var].extras['static']) static_tavg_list = [i for i in name if 'static_tavg' in pytplot.data_quants[i].extras] for tplot_var in static_tavg_list: # Call 2D static window for time-averaged values; This will only plot something when spectrograms # are involved staticplot_tavg.static2dplot_timeaveraged( tplot_var, pytplot.data_quants[tplot_var].extras['static_tavg']) # (hasattr(sys, 'ps1')) checks to see if we're in ipython # plots the plots! if testing: return if not (hasattr(sys, 'ps1')) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() return
https://github.com/MAVENSDC/PyTplot/blob/d76cdb95363a4bd4fea6bca7960f8523efa7fa83/pytplot/tplot.py#L28-L245
scatter plot
python
def plot(self, x, y, **kw): """plot x, y values (erasing old plot), for method options see PlotPanel.plot. """ return self.frame.plot(x,y,**kw)
https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/wxmplot/plotapp.py#L21-L25
scatter plot
python
def plot(self, data, color='k', symbol=None, line_kind='-', width=1., marker_size=10., edge_color='k', face_color='b', edge_width=1., title=None, xlabel=None, ylabel=None): """Plot a series of data using lines and markers Parameters ---------- data : array | two arrays Arguments can be passed as ``(Y,)``, ``(X, Y)`` or ``np.array((X, Y))``. color : instance of Color Color of the line. symbol : str Marker symbol to use. line_kind : str Kind of line to draw. For now, only solid lines (``'-'``) are supported. width : float Line width. marker_size : float Marker size. If `size == 0` markers will not be shown. edge_color : instance of Color Color of the marker edge. face_color : instance of Color Color of the marker face. edge_width : float Edge width of the marker. title : str | None The title string to be displayed above the plot xlabel : str | None The label to display along the bottom axis ylabel : str | None The label to display along the left axis. Returns ------- line : instance of LinePlot The line plot. See also -------- marker_types, LinePlot """ self._configure_2d() line = scene.LinePlot(data, connect='strip', color=color, symbol=symbol, line_kind=line_kind, width=width, marker_size=marker_size, edge_color=edge_color, face_color=face_color, edge_width=edge_width) self.view.add(line) self.view.camera.set_range() self.visuals.append(line) if title is not None: self.title.text = title if xlabel is not None: self.xlabel.text = xlabel if ylabel is not None: self.ylabel.text = ylabel return line
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/plot/plotwidget.py#L264-L325
scatter plot
python
def plot(self, atDataset, errorbars=False, grid=False): """ use matplotlib methods for plotting Parameters ---------- atDataset : allantools.Dataset() a dataset with computed data errorbars : boolean Plot errorbars. Defaults to False grid : boolean Plot grid. Defaults to False """ if errorbars: self.ax.errorbar(atDataset.out["taus"], atDataset.out["stat"], yerr=atDataset.out["stat_err"], ) else: self.ax.plot(atDataset.out["taus"], atDataset.out["stat"], ) self.ax.set_xlabel("Tau") self.ax.set_ylabel(atDataset.out["stat_id"]) self.ax.grid(grid, which="minor", ls="-", color='0.65') self.ax.grid(grid, which="major", ls="-", color='0.25')
https://github.com/aewallin/allantools/blob/b5c695a5af4379fcea4d4ce93a066cb902e7ee0a/allantools/plot.py#L66-L92
scatter plot
python
def scatter_plot(data, index_x, index_y, percent=100.0, seed=1, size=50, title=None, outfile=None, wait=True): """ Plots two attributes against each other. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html :param data: the dataset :type data: Instances :param index_x: the 0-based index of the attribute on the x axis :type index_x: int :param index_y: the 0-based index of the attribute on the y axis :type index_y: int :param percent: the percentage of the dataset to use for plotting :type percent: float :param seed: the seed value to use for subsampling :type seed: int :param size: the size of the circles in point :type size: int :param title: an optional title :type title: str :param outfile: the (optional) file to save the generated plot to. The extension determines the file format. :type outfile: str :param wait: whether to wait for the user to close the plot :type wait: bool """ if not plot.matplotlib_available: logger.error("Matplotlib is not installed, plotting unavailable!") return # create subsample data = plot.create_subsample(data, percent=percent, seed=seed) # collect data x = [] y = [] if data.class_index == -1: c = None else: c = [] for i in range(data.num_instances): inst = data.get_instance(i) x.append(inst.get_value(index_x)) y.append(inst.get_value(index_y)) if c is not None: c.append(inst.get_value(inst.class_index)) # plot data fig, ax = plt.subplots() if c is None: ax.scatter(x, y, s=size, alpha=0.5) else: ax.scatter(x, y, c=c, s=size, alpha=0.5) ax.set_xlabel(data.attribute(index_x).name) ax.set_ylabel(data.attribute(index_y).name) if title is None: title = "Attribute scatter plot" if percent != 100: title += " (%0.1f%%)" % percent ax.set_title(title) ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c="0.3") ax.grid(True) fig.canvas.set_window_title(data.relationname) plt.draw() if outfile is not None: plt.savefig(outfile) if wait: plt.show()
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/plot/dataset.py#L27-L93
scatter plot
python
def plot(self,x,y,panel=None,**kws): """plot after clearing current plot """ if panel is None: panel = self.current_panel opts = {} opts.update(self.default_panelopts) opts.update(kws) self.panels[panel].plot(x ,y, **opts)
https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/wxmplot/multiframe.py#L48-L55
scatter plot
python
def scatter(points, vertexlabels=None, **kwargs): '''Scatter plot of barycentric 2-simplex points on a 2D triangle. :param points: Points on a 2-simplex. :type points: N x 3 list or ndarray. :param vertexlabels: Labels for corners of plot in the order ``(a, b, c)`` where ``a == (1,0,0)``, ``b == (0,1,0)``, ``c == (0,0,1)``. :type vertexlabels: 3-tuple of strings. :param **kwargs: Arguments to :func:`plt.scatter`. :type **kwargs: keyword arguments.''' if vertexlabels is None: vertexlabels = ('1','2','3') projected = cartesian(points) plt.scatter(projected[:,0], projected[:,1], **kwargs) _draw_axes(vertexlabels) return plt.gcf()
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L54-L72
scatter plot
python
def plot(self, legend=None, width=1.5, ladder=True, aspect=10, ticks=(1, 10), match_only=None, ax=None, return_fig=False, colour=None, cmap='viridis', default=None, style='intervals', field=None, **kwargs): """ Hands-free plotting. Args: legend (Legend): The Legend to use for colours, etc. width (int): The width of the plot, in inches. Default 1. ladder (bool): Whether to use widths or not. Default False. aspect (int): The aspect ratio of the plot. Default 10. ticks (int or tuple): The (minor,major) tick interval for depth. Only the major interval is labeled. Default (1,10). match_only (list): A list of strings matching the attributes you want to compare when plotting. ax (ax): A maplotlib axis to plot onto. If you pass this, it will be returned. Optional. return_fig (bool): Whether or not to return the maplotlib ``fig`` object. Default False. colour (str): Which data field to use for colours. cmap (cmap): Matplotlib colourmap. Default ``viridis``. **kwargs are passed through to matplotlib's ``patches.Rectangle``. Returns: None. Unless you specify ``return_fig=True`` or pass in an ``ax``. """ if legend is None: legend = Legend.random(self.components) if style.lower() == 'tops': # Make sure width is at least 3 for 'tops' style width = max([3, width]) if ax is None: return_ax = False fig = plt.figure(figsize=(width, aspect*width)) ax = fig.add_axes([0.35, 0.05, 0.6, 0.95]) else: return_ax = True if (self.order == 'none') or (style.lower() == 'points'): # Then this is a set of points. ax = self.plot_points(ax=ax, legend=legend, field=field, **kwargs) elif style.lower() == 'field': if field is None: raise StriplogError('You must provide a field to plot.') ax = self.plot_field(ax=ax, legend=legend, field=field) elif style.lower() == 'tops': ax = self.plot_tops(ax=ax, legend=legend, field=field) ax.set_xticks([]) else: ax = self.plot_axis(ax=ax, legend=legend, ladder=ladder, default_width=width, match_only=kwargs.get('match_only', match_only), colour=colour, cmap=cmap, default=default, width_field=field, **kwargs ) ax.set_xlim([0, width]) ax.set_xticks([]) # Rely on interval order. lower, upper = self[-1].base.z, self[0].top.z rng = abs(upper - lower) ax.set_ylim([lower, upper]) # Make sure ticks is a tuple. try: ticks = tuple(ticks) except TypeError: ticks = (1, ticks) # Avoid MAXTICKS error. while rng/ticks[0] > 250: mi, ma = 10*ticks[0], ticks[1] if ma <= mi: ma = 10 * mi ticks = (mi, ma) # Carry on plotting... minorLocator = mpl.ticker.MultipleLocator(ticks[0]) ax.yaxis.set_minor_locator(minorLocator) majorLocator = mpl.ticker.MultipleLocator(ticks[1]) majorFormatter = mpl.ticker.FormatStrFormatter('%d') ax.yaxis.set_major_locator(majorLocator) ax.yaxis.set_major_formatter(majorFormatter) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.yaxis.set_ticks_position('left') ax.get_yaxis().set_tick_params(which='both', direction='out') # Optional title. title = getattr(self, 'title', None) if title is not None: ax.set_title(title) ax.patch.set_alpha(0) if return_ax: return ax elif return_fig: return fig else: return
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1447-L1571
scatter plot
python
def scatter(*args, **kwargs): """This function creates a scatter chart. Specifcally it creates an :py:class:`.AxisChart` and then adds a :py:class:`.ScatterSeries` to it. :param \*data: The data for the scatter series as either (x,y) values or two\ big tuples/lists of x and y values respectively. :param str name: The name to be associated with the series. :param str color: The hex colour of the data points. :param Number size: The size of each data point - generally the diameter. :param Number linewidth: The width in pixels of the data points' edge. :raises ValueError: if the size and length of the data doesn't match either\ format. :param str title: The chart's title. This will be displayed at the top of\ the chart. :param width: The width in pixels of the chart. :param height: The height in pixels of the chart. :param str x_label: The label for the x-axis. :param str y_label: The label for the y-axis. :rtype: :py:class:`.AxisChart`""" scatter_series_kwargs = {} for kwarg in ("name", "color", "size", "linewidth"): if kwarg in kwargs: scatter_series_kwargs[kwarg] = kwargs[kwarg] del kwargs[kwarg] if "color" not in scatter_series_kwargs: scatter_series_kwargs["color"] = colors[0] series = ScatterSeries(*args, **scatter_series_kwargs) chart = AxisChart(series, **kwargs) return chart
https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/quick.py#L39-L68
scatter plot
python
def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs): """ {_gate_plot_doc} """ 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)
https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/gates.py#L249-L265
scatter plot
python
def jitterplot(data, positions=None, ax=None, vert=True, scale=0.1, **scatter_kwargs): '''Plots jittered points as a distribution visualizer. Scatter plot arguments default to: marker='.', c='k', alpha=0.75 Also known as a stripplot. See also: boxplot, violinplot, beeswarm ''' 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
https://github.com/perimosocordiae/viztricks/blob/bae2f8a9ce9278ce0197f8efc34cc4fef1dfe1eb/viztricks/extensions.py#L189-L213
scatter plot
python
def plot(self, ax: GeoAxesSubplot, s: int = 10, **kwargs) -> Artist: """Plotting function. All arguments are passed to ax.scatter""" return ax.scatter( self.data.longitude, self.data.latitude, s=s, transform=PlateCarree(), **kwargs, )
https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/sv.py#L29-L37
scatter plot
python
def _scatter_matrix(self,theme=None,bins=10,color='grey',size=2, asFigure=False, **iplot_kwargs): """ Displays a matrix with scatter plot for each pair of Series in the DataFrame. The diagonal shows a histogram for each of the Series Parameters: ----------- df : DataFrame Pandas DataFrame theme : string Theme to be used (if not the default) bins : int Number of bins to use for histogram color : string Color to be used for each scatter plot size : int Size for each marker on the scatter plot iplot_kwargs : key-value pairs Keyword arguments to pass through to `iplot` """ sm=tools.scatter_matrix(self,theme=theme,bins=bins,color=color,size=size) if asFigure: return sm else: return iplot(sm,**iplot_kwargs)
https://github.com/santosjorge/cufflinks/blob/ca1cbf93998dc793d0b1f8ac30fe1f2bd105f63a/cufflinks/plotlytools.py#L1258-L1283
scatter plot
python
def plot(self, channel_names, kind='histogram', gates=None, gate_colors=None, ids=None, row_labels=None, col_labels=None, xlim='auto', ylim='auto', autolabel=True, **kwargs): """ Produces a grid plot with each subplot corresponding to the data at the given position. Parameters --------------- {FCMeasurement_plot_pars} {graph_plotFCM_pars} {_graph_grid_layout} Returns ------- {_graph_grid_layout_returns} Examples -------- Below, plate is an instance of FCOrderedCollection >>> plate.plot(['SSC-A', 'FSC-A'], kind='histogram', autolabel=True) >>> plate.plot(['SSC-A', 'FSC-A'], xlim=(0, 10000)) >>> plate.plot(['B1-A', 'Y2-A'], kind='scatter', color='red', s=1, alpha=0.3) >>> plate.plot(['B1-A', 'Y2-A'], bins=100, alpha=0.3) >>> plate.plot(['B1-A', 'Y2-A'], bins=[linspace(-1000, 10000, 100), linspace(-1000, 10000, 100)], alpha=0.3) .. note:: For more details see documentation for FCMeasurement.plot **kwargs passes arguments to both grid_plot and to FCMeasurement.plot. """ ## # Note # ------- # The function assumes that grid_plot and FCMeasurement.plot use unique key words. # Any key word arguments that appear in both functions are passed only to grid_plot in the end. ## # Automatically figure out which of the kwargs should # be sent to grid_plot instead of two sample.plot # (May not be a robust solution, we'll see as the code evolves grid_arg_list = inspect.getargspec(OrderedCollection.grid_plot).args grid_plot_kwargs = {'ids': ids, 'row_labels': row_labels, 'col_labels': col_labels} for key, value in list(kwargs.items()): if key in grid_arg_list: kwargs.pop(key) grid_plot_kwargs[key] = value ## # Make sure channel names is a list to make the code simpler below channel_names = to_list(channel_names) ## # Determine data limits for binning # if kind == 'histogram': nbins = kwargs.get('bins', 200) if isinstance(nbins, int): min_list = [] max_list = [] for sample in self: min_list.append(self[sample].data[channel_names].min().values) max_list.append(self[sample].data[channel_names].max().values) min_list = list(zip(*min_list)) max_list = list(zip(*max_list)) bins = [] for i, c in enumerate(channel_names): min_v = min(min_list[i]) max_v = max(max_list[i]) bins.append(np.linspace(min_v, max_v, nbins)) # Check if 1d if len(channel_names) == 1: bins = bins[0] # bins should be an ndarray, not a list of ndarrays kwargs['bins'] = bins ########## # Defining the plotting function that will be used. # At the moment grid_plot handles the labeling # (rather than sample.plot or the base function # in GoreUtilities.graph def plot_sample(sample, ax): return sample.plot(channel_names, ax=ax, gates=gates, gate_colors=gate_colors, colorbar=False, kind=kind, autolabel=False, **kwargs) xlabel, ylabel = None, None if autolabel: cnames = to_list(channel_names) xlabel = cnames[0] if len(cnames) == 2: ylabel = cnames[1] return self.grid_plot(plot_sample, xlim=xlim, ylim=ylim, xlabel=xlabel, ylabel=ylabel, **grid_plot_kwargs)
https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/containers.py#L545-L658
scatter plot
python
def plot_spectrogram(self, fmin=None, fmax=None, method='scipy-fourier', deg=False, window='hann', detrend='linear', nperseg=None, noverlap=None, boundary='constant', padded=True, wave='morlet', invert=True, plotmethod='imshow', cmap_f=None, cmap_img=None, ms=4, ntMax=None, nfMax=None, Bck=True, fs=None, dmargin=None, wintit=None, tit=None, vmin=None, vmax=None, normt=False, draw=True, connect=True, returnspect=False, warn=True): """ Plot the spectrogram of all channels with chosen method All non-plotting arguments are fed to self.calc_spectrogram() see self.calc_spectrogram? for details Parameters ---------- Return ------ kh : tofu.utils.HeyHandler The tofu KeyHandler object handling figure interactivity """ if self._isSpectral(): msg = "spectrogram not implemented yet for spectral data class" raise Exception(msg) tf, f, lpsd, lang = _comp.spectrogram(self.data, self.t, fmin=fmin, deg=deg, method=method, window=window, detrend=detrend, nperseg=nperseg, noverlap=noverlap, boundary=boundary, padded=padded, wave=wave, warn=warn) kh = _plot.Data_plot_spectrogram(self, tf, f, lpsd, lang, fmax=fmax, invert=invert, plotmethod=plotmethod, cmap_f=cmap_f, cmap_img=cmap_img, ms=ms, ntMax=ntMax, nfMax=nfMax, Bck=Bck, fs=fs, dmargin=dmargin, wintit=wintit, tit=tit, vmin=vmin, vmax=vmax, normt=normt, draw=draw, connect=connect) if returnspect: return kh, tf, f, lpsd, lang else: return kh
https://github.com/ToFuProject/tofu/blob/39d6b2e7ced9e13666572dfd37e19403f1d6ff8d/tofu/data/_core.py#L1756-L1802
scatter plot
python
def plot_scalar(step, var, field=None, axis=None, set_cbar=True, **extra): """Plot scalar field. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. var (str): the scalar field name. field (:class:`numpy.array`): if not None, it is plotted instead of step.fields[var]. This is useful to plot a masked or rescaled array. Note that if conf.scaling.dimensional is True, this field will be scaled accordingly. axis (:class:`matplotlib.axes.Axes`): the axis objet where the field should be plotted. If set to None, a new figure with one subplot is created. set_cbar (bool): whether to add a colorbar to the plot. extra (dict): options that will be passed on to :func:`matplotlib.axes.Axes.pcolormesh`. Returns: fig, axis, surf, cbar handles to various :mod:`matplotlib` objects, respectively the figure, the axis, the surface returned by :func:`~matplotlib.axes.Axes.pcolormesh`, and the colorbar returned by :func:`matplotlib.pyplot.colorbar`. """ if var in phyvars.FIELD: meta = phyvars.FIELD[var] else: meta = phyvars.FIELD_EXTRA[var] meta = phyvars.Varf(misc.baredoc(meta.description), meta.dim) if step.geom.threed: raise NotAvailableError('plot_scalar only implemented for 2D fields') xmesh, ymesh, fld = get_meshes_fld(step, var) xmin, xmax = xmesh.min(), xmesh.max() ymin, ymax = ymesh.min(), ymesh.max() if field is not None: fld = field if conf.field.perturbation: fld = fld - np.mean(fld, axis=0) if conf.field.shift: fld = np.roll(fld, conf.field.shift, axis=0) fld, unit = step.sdat.scale(fld, meta.dim) if axis is None: fig, axis = plt.subplots(ncols=1) else: fig = axis.get_figure() if step.sdat.par['magma_oceans_in']['magma_oceans_mode']: rcmb = step.sdat.par['geometry']['r_cmb'] xmax = rcmb + 1 ymax = xmax xmin = -xmax ymin = -ymax rsurf = xmax if step.timeinfo['thick_tmo'] > 0 \ else step.geom.r_mesh[0, 0, -3] cmb = mpat.Circle((0, 0), rcmb, color='dimgray', zorder=0) psurf = mpat.Circle((0, 0), rsurf, color='indianred', zorder=0) axis.add_patch(psurf) axis.add_patch(cmb) extra_opts = dict( cmap=conf.field.cmap.get(var), vmin=conf.plot.vmin, vmax=conf.plot.vmax, norm=mpl.colors.LogNorm() if var == 'eta' else None, rasterized=conf.plot.raster, shading='gouraud' if conf.field.interpolate else 'flat', ) extra_opts.update(extra) surf = axis.pcolormesh(xmesh, ymesh, fld, **extra_opts) cbar = None if set_cbar: cbar = plt.colorbar(surf, shrink=conf.field.shrinkcb) cbar.set_label(meta.description + (' pert.' if conf.field.perturbation else '') + (' ({})'.format(unit) if unit else '')) if step.geom.spherical or conf.plot.ratio is None: plt.axis('equal') plt.axis('off') else: axis.set_aspect(conf.plot.ratio / axis.get_data_ratio()) axis.set_adjustable('box') axis.set_xlim(xmin, xmax) axis.set_ylim(ymin, ymax) return fig, axis, surf, cbar
https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/field.py#L108-L196
scatter plot
python
def plot_flat(r, c, figsize): "Shortcut for `enumerate(subplots.flatten())`" return enumerate(plt.subplots(r, c, figsize=figsize)[1].flatten())
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L602-L604
scatter plot
python
def run(self, gta, mcube_map, **kwargs): """Make all plots.""" prefix = kwargs.get('prefix', 'test') format = kwargs.get('format', self.config['format']) loge_bounds = [None] + self.config['loge_bounds'] for x in loge_bounds: self.make_roi_plots(gta, mcube_map, loge_bounds=x, **kwargs) imfile = utils.format_filename(self.config['fileio']['workdir'], 'counts_spectrum', prefix=[prefix], extension=format) make_counts_spectrum_plot(gta._roi_data, gta.roi, gta.log_energies, imfile, **kwargs)
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/plotting.py#L924-L941
scatter plot
python
def plot_raster(self, ax, xlim, x, y, pop_names=False, markersize=20., alpha=1., legend=True, marker='o', rasterized=True): """ Plot network raster plot in subplot object. Parameters ---------- ax : `matplotlib.axes.AxesSubplot` object plot axes xlim : list List of floats. Spike time interval, e.g., [0., 1000.]. x : dict Key-value entries are population name and neuron spike times. y : dict Key-value entries are population name and neuron gid number. pop_names: bool If True, show population names on yaxis instead of gid number. markersize : float raster plot marker size alpha : float in [0, 1] transparency of marker legend : bool Switch on axes legends. marker : str marker symbol for matplotlib.pyplot.plot rasterized : bool if True, the scatter plot will be treated as a bitmap embedded in pdf file output Returns ------- None """ yoffset = [sum(self.N_X) if X=='TC' else 0 for X in self.X] for i, X in enumerate(self.X): if y[X].size > 0: ax.plot(x[X], y[X]+yoffset[i], marker, markersize=markersize, mfc=self.colors[i], mec='none' if marker in '.ov><v^1234sp*hHDd' else self.colors[i], alpha=alpha, label=X, rasterized=rasterized, clip_on=True) #don't draw anything for the may-be-quiet TC population N_X_sum = 0 for i, X in enumerate(self.X): if y[X].size > 0: N_X_sum += self.N_X[i] ax.axis([xlim[0], xlim[1], self.GIDs[self.X[0]][0], self.GIDs[self.X[0]][0]+N_X_sum]) ax.set_ylim(ax.get_ylim()[::-1]) ax.set_ylabel('cell id', labelpad=0) ax.set_xlabel('$t$ (ms)', labelpad=0) if legend: ax.legend() if pop_names: yticks = [] yticklabels = [] for i, X in enumerate(self.X): if y[X] != []: yticks.append(y[X].mean()+yoffset[i]) yticklabels.append(self.X[i]) ax.set_yticks(yticks) ax.set_yticklabels(yticklabels) # Add some horizontal lines separating the populations for i, X in enumerate(self.X): if y[X].size > 0: ax.plot([xlim[0], xlim[1]], [y[X].max()+yoffset[i], y[X].max()+yoffset[i]], 'k', lw=0.25)
https://github.com/INM-6/hybridLFPy/blob/c38bdf38982c4624c2f70caeb50c40f1d5980abd/hybridLFPy/cachednetworks.py#L258-L334
scatter plot
python
def plots(self): """ The sequence of plots in this chart. A plot, called a *chart group* in the Microsoft API, is a distinct sequence of one or more series depicted in a particular charting type. For example, a chart having a series plotted as a line overlaid on three series plotted as columns would have two plots; the first corresponding to the three column series and the second to the line series. Plots are sequenced in the order drawn, i.e. back-most to front-most. Supports *len()*, membership (e.g. ``p in plots``), iteration, slicing, and indexed access (e.g. ``plot = plots[i]``). """ plotArea = self._chartSpace.chart.plotArea return _Plots(plotArea, self)
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/chart/chart.py#L155-L168
scatter plot
python
def plot(self, key=None, invert=None, plotmethod='imshow', cmap=plt.cm.gray, ms=4, Max=None, fs=None, dmargin=None, wintit=None, draw=True, connect=True): """ Plot the data content in a predefined figure """ dax, KH = _plot.Data_plot(self, key=key, invert=invert, Max=Max, plotmethod=plotmethod, cmap=cmap, ms=ms, fs=fs, dmargin=dmargin, wintit=wintit, draw=draw, connect=connect) return dax, KH
https://github.com/ToFuProject/tofu/blob/39d6b2e7ced9e13666572dfd37e19403f1d6ff8d/tofu/data/_core.py#L2446-L2455
scatter plot
python
def plot_spectra_overlapped(ss, title=None, setup=_default_setup): """ Plots one or more spectra in the same plot. Args: ss: list of Spectrum objects title=None: window title setup: PlotSpectrumSetup object """ plt.figure() draw_spectra_overlapped(ss, title, setup) plt.show()
https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/vis/plotsp.py#L80-L92
scatter plot
python
def plotPlainImg(sim, cam, rawdata, t, odir): """ No subplots, just a plan http://stackoverflow.com/questions/22408237/named-colors-in-matplotlib """ for R, C in zip(rawdata, cam): fg = figure() ax = fg.gca() ax.set_axis_off() # no ticks ax.imshow(R[t, :, :], origin='lower', vmin=max(C.clim[0], 1), vmax=C.clim[1], cmap='gray') ax.text(0.05, 0.075, datetime.utcfromtimestamp(C.tKeo[t]).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3], ha='left', va='top', transform=ax.transAxes, color='limegreen', # weight='bold', size=24 ) writeplots(fg, 'cam{}rawFrame'.format(C.name), t, odir)
https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/plotsimul.py#L23-L46
scatter plot
python
def plotter(path, show, goodFormat): '''makes some plots creates binned histograms of the results of each module (ie count of results in ranges [(0,40), (40, 50), (50,60), (60, 70), (70, 80), (80, 90), (90, 100)]) Arguments: path {str} -- path to save plots to show {boolean} -- whether to show plots using python goodFormat {dict} -- module : [results for module] output: saves plots to files/shows plots depending on inputs ''' for module in goodFormat.items(): # for each module bins = [0, 40, 50, 60, 70, 80, 90, 100] # cut the data into bins out = pd.cut(module[1], bins=bins, include_lowest=True) ax = out.value_counts().plot.bar(rot=0, color="b", figsize=(10, 6), alpha=0.5, title=module[0]) # plot counts of the cut data as a bar ax.set_xticklabels(['0 to 40', '40 to 50', '50 to 60', '60 to 70', '70 to 80', '80 to 90', '90 to 100']) ax.set_ylabel("# of candidates") ax.set_xlabel( "grade bins \n total candidates: {}".format(len(module[1]))) if path is not None and show is not False: # if export path directory doesn't exist: create it if not pathlib.Path.is_dir(path.as_posix()): pathlib.Path.mkdir(path.as_posix()) plt.savefig(path / ''.join([module[0], '.png'])) plt.show() elif path is not None: # if export path directory doesn't exist: create it if not pathlib.Path.is_dir(path): pathlib.Path.mkdir(path) plt.savefig(path / ''.join([module[0], '.png'])) plt.close() elif show is not False: plt.show()
https://github.com/haykkh/resultr/blob/decd222a4c0d3ea75595fd546b797b60297623b6/resultr.py#L79-L127
scatter plot
python
def show_plots(fitdata, fitval, x=None, save=False, view='ratio'): """ Show plots comparing ``fitdata[k],fitval[k]`` for each key ``k`` in ``fitval``. Assumes :mod:`matplotlib` is installed (to make the plots). Plots are shown for one correlator at a time. Press key ``n`` to see the next correlator; press key ``p`` to see the previous one; press key ``q`` to quit the plot and return control to the calling program; press a digit to go directly to one of the first ten plots. Zoom, pan and save using the window controls. There are several different views available for each plot, specified by parameter ``view``: ``view='ratio'``: Data divided by fit (default). ``view='diff'``: Data minus fit, divided by data's standard deviation. ``view='std'``: Data and fit. ``view='log'``: ``'std'`` with log scale on the vertical axis. ``view='loglog'``: `'std'`` with log scale on both axes. Press key ``v`` to cycle through these views; or press keys ``r``, ``d``, or ``l`` for the ``'ratio'``, ``'diff'``, or ``'log'`` views, respectively. Copies of the plots that are viewed can be saved by setting parameter ``save=fmt`` where ``fmt`` is a string used to create file names: the file name for the plot corresponding to key ``k`` is ``fmt.format(k)``. It is important that the filename end with a suffix indicating the type of plot file desired: e.g., ``fmt='plot-{}.pdf'``. """ import matplotlib.pyplot as plt # collect plotinfo plotinfo = collections.OrderedDict() for tag in fitval: d = fitdata[tag] f = fitval[tag] plotinfo[tag] = ( numpy.arange(len(d))+1 if x is None else x[tag], gvar.mean(d), gvar.sdev(d), gvar.mean(f), gvar.sdev(f) ) plotinfo_keys = list(plotinfo.keys()) fig = plt.figure() viewlist = ['ratio', 'diff', 'std', 'log', 'loglog'] def onpress(event): if event is not None: try: # digit? onpress.idx = int(event.key) except ValueError: if event.key == 'n': onpress.idx += 1 elif event.key == 'p': onpress.idx -= 1 elif event.key == 'v': onpress.view = (onpress.view + 1) % len(viewlist) elif event.key == 'r': onpress.view = viewlist.index('ratio') elif event.key == 'd': onpress.view = viewlist.index('diff') elif event.key == 'l': onpress.view = viewlist.index('log') # elif event.key == 'q': # unnecessary # plt.close() # return else: return else: onpress.idx = 0 # do the plot if onpress.idx >= len(plotinfo_keys): onpress.idx = len(plotinfo_keys)-1 elif onpress.idx < 0: onpress.idx = 0 i = onpress.idx k = plotinfo_keys[i] x, g, dg, gth, dgth = plotinfo[k] fig.clear() plt.title("%d) %s (press 'n', 'p', 'q', 'v' or a digit)" % (i, k)) dx = (max(x) - min(x)) / 50. plt.xlim(min(x)-dx, max(x)+dx) plotview = viewlist[onpress.view] if plotview in ['std', 'log', 'loglog']: if plotview in ['log', 'loglog']: plt.yscale('log', nonposy='clip') if plotview == 'loglog': plt.xscale('log', nonposx='clip') plt.ylabel(str(k) + ' [%s]' % plotview) if len(x) > 0: if len(x) > 1: plt.plot(x, gth, 'r-') plt.fill_between( x, y2=gth + dgth, y1=gth - dgth, color='r', alpha=0.075, ) else: extra_x = [x[0] * 0.5, x[0] * 1.5] plt.plot(extra_x, 2 * [gth[0]], 'r-') plt.fill_between( extra_x, y2=2 * [gth[0] + dgth[0]], y1=2 * [gth[0] - dgth[0]], color='r', alpha=0.075, ) plt.errorbar(x, g, dg, fmt='o') elif plotview == 'ratio': plt.ylabel(str(k)+' / '+'fit' + ' [%s]' % plotview) ii = (gth != 0.0) # check for exact zeros (eg, antiperiodic) if len(x[ii]) > 0: if len(x[ii]) > 1: plt.fill_between( x[ii], y2=1 + dgth[ii] / gth[ii], y1=1 - dgth[ii] / gth[ii], color='r', alpha=0.075, ) plt.plot(x, numpy.ones(len(x), float), 'r-') else: extra_x = [x[ii][0] * 0.5, x[ii][0] * 1.5] plt.fill_between( extra_x, y2=2 * [1 + dgth[ii][0]/gth[ii][0]], y1=2 * [1 - dgth[ii][0]/gth[ii][0]], color='r', alpha=0.075, ) plt.plot(extra_x, numpy.ones(2, float), 'r-') plt.errorbar(x[ii], g[ii]/gth[ii], dg[ii]/gth[ii], fmt='o') elif plotview == 'diff': plt.ylabel('({} - fit) / sigma'.format(str(k)) + ' [%s]' % plotview) ii = (dg != 0.0) # check for exact zeros if len(x[ii]) > 0: if len(x[ii]) > 1: plt.fill_between( x[ii], y2=dgth[ii] / dg[ii], y1=-dgth[ii] / dg[ii], color='r', alpha=0.075 ) plt.plot(x, numpy.zeros(len(x), float), 'r-') else: extra_x = [x[ii][0] * 0.5, x[ii][0] * 1.5] plt.fill_between( extra_x, y2=2 * [dgth[ii][0] / dg[ii][0]], y1=2 * [-dgth[ii][0] / dg[ii][0]], color='r', alpha=0.075 ) plt.plot(extra_x, numpy.zeros(2, float), 'r-') plt.errorbar( x[ii], (g[ii] - gth[ii]) / dg[ii], dg[ii] / dg[ii], fmt='o' ) if save: plt.savefig(save.format(k), bbox_inches='tight') else: plt.draw() onpress.idx = 0 try: onpress.view = viewlist.index(view) except ValueError: raise ValueError('unknow view: ' + str(view)) fig.canvas.mpl_connect('key_press_event', onpress) onpress(None) plt.show()
https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/_extras.py#L1415-L1577
scatter plot
python
def scatter( adata, x=None, y=None, color=None, use_raw=None, layers='X', sort_order=True, alpha=None, basis=None, groups=None, components=None, projection='2d', legend_loc='right margin', legend_fontsize=None, legend_fontweight=None, color_map=None, palette=None, frameon=None, right_margin=None, left_margin=None, size=None, title=None, show=None, save=None, ax=None): """\ Scatter plot along observations or variables axes. Color the plot using annotations of observations (`.obs`), variables (`.var`) or expression of genes (`.var_names`). Parameters ---------- adata : :class:`~anndata.AnnData` Annotated data matrix. x : `str` or `None` x coordinate. y : `str` or `None` y coordinate. color : string or list of strings, optional (default: `None`) Keys for annotations of observations/cells or variables/genes, e.g., `'ann1'` or `['ann1', 'ann2']`. use_raw : `bool`, optional (default: `None`) Use `raw` attribute of `adata` if present. layers : `str` or tuple of strings, optional (default: `X`) Use the `layers` attribute of `adata` if present: specify the layer for `x`, `y` and `color`. If `layers` is a string, then it is expanded to `(layers, layers, layers)`. basis : {{'pca', 'tsne', 'umap', 'diffmap', 'draw_graph_fr', etc.}} String that denotes a plotting tool that computed coordinates. {scatter_temp} {show_save_ax} Returns ------- If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it. """ if basis is not None: axs = _scatter_obs( adata=adata, x=x, y=y, color=color, use_raw=use_raw, layers=layers, sort_order=sort_order, alpha=alpha, basis=basis, groups=groups, components=components, projection=projection, legend_loc=legend_loc, legend_fontsize=legend_fontsize, legend_fontweight=legend_fontweight, color_map=color_map, palette=palette, frameon=frameon, right_margin=right_margin, left_margin=left_margin, size=size, title=title, show=show, save=save, ax=ax) elif x is not None and y is not None: if ((x in adata.obs.keys() or x in adata.var.index) and (y in adata.obs.keys() or y in adata.var.index) and (color is None or color in adata.obs.keys() or color in adata.var.index)): axs = _scatter_obs( adata=adata, x=x, y=y, color=color, use_raw=use_raw, layers=layers, sort_order=sort_order, alpha=alpha, basis=basis, groups=groups, components=components, projection=projection, legend_loc=legend_loc, legend_fontsize=legend_fontsize, legend_fontweight=legend_fontweight, color_map=color_map, palette=palette, frameon=frameon, right_margin=right_margin, left_margin=left_margin, size=size, title=title, show=show, save=save, ax=ax) elif ((x in adata.var.keys() or x in adata.obs.index) and (y in adata.var.keys() or y in adata.obs.index) and (color is None or color in adata.var.keys() or color in adata.obs.index)): axs = _scatter_var( adata=adata, x=x, y=y, color=color, use_raw=use_raw, layers=layers, sort_order=sort_order, alpha=alpha, basis=basis, groups=groups, components=components, projection=projection, legend_loc=legend_loc, legend_fontsize=legend_fontsize, legend_fontweight=legend_fontweight, color_map=color_map, palette=palette, frameon=frameon, right_margin=right_margin, left_margin=left_margin, size=size, title=title, show=show, save=save, ax=ax) else: raise ValueError( '`x`, `y`, and potential `color` inputs must all come from either `.obs` or `.var`') else: raise ValueError('Either provide a `basis` or `x` and `y`.') return axs
https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/plotting/_anndata.py#L30-L179
scatter plot
python
def toplot(ts, filename=None, grid=True, legend=True, pargs=(), **kwargs): '''To plot formatter''' fig = plt.figure() ax = fig.add_subplot(111) dates = list(ts.dates()) ax.plot(dates, ts.values(), *pargs) ax.grid(grid) # rotates and right aligns the x labels, and moves the bottom of the # axes up to make room for them fig.autofmt_xdate() # add legend or title names = ts.name.split('__') if len(names) == 1: title = names[0] fontweight = kwargs.get('title_fontweight', 'bold') ax.set_title(title, fontweight=fontweight)#,fontsize=fontsize, elif legend: ##add legend loc = kwargs.get('legend_location','best') ncol = kwargs.get('legend_ncol', 2) ax.legend(names, loc=loc, ncol=ncol) return plt
https://github.com/quantmind/dynts/blob/21ac57c648bfec402fa6b1fe569496cf098fb5e8/dynts/formatters/tsplot.py#L4-L33
scatter plot
python
def plotcorr(X, plotargs=None, full=True, labels=None): """ Plots a scatterplot matrix of subplots. Usage: plotcorr(X) plotcorr(..., plotargs=...) # e.g., 'r*', 'bo', etc. plotcorr(..., full=...) # e.g., True or False plotcorr(..., labels=...) # e.g., ['label1', 'label2', ...] Each column of "X" is plotted against other columns, resulting in a ncols by ncols grid of subplots with the diagonal subplots labeled with "labels". "X" is an array of arrays (i.e., a 2d matrix), a 1d array of MCERP.UncertainFunction/Variable objects, or a mixture of the two. Additional keyword arguments are passed on to matplotlib's "plot" command. Returns the matplotlib figure object containing the subplot grid. """ import matplotlib.pyplot as plt X = [Xi._mcpts if isinstance(Xi, UncertainFunction) else Xi for Xi in X] X = np.atleast_2d(X) numvars, numdata = X.shape fig, axes = plt.subplots(nrows=numvars, ncols=numvars, figsize=(8, 8)) fig.subplots_adjust(hspace=0.0, wspace=0.0) for ax in axes.flat: # Hide all ticks and labels ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) # Set up ticks only on one side for the "edge" subplots... if full: if ax.is_first_col(): ax.yaxis.set_ticks_position("left") if ax.is_last_col(): ax.yaxis.set_ticks_position("right") if ax.is_first_row(): ax.xaxis.set_ticks_position("top") if ax.is_last_row(): ax.xaxis.set_ticks_position("bottom") else: if ax.is_first_row(): ax.xaxis.set_ticks_position("top") if ax.is_last_col(): ax.yaxis.set_ticks_position("right") # Label the diagonal subplots... if not labels: labels = ["x" + str(i) for i in range(numvars)] for i, label in enumerate(labels): axes[i, i].annotate( label, (0.5, 0.5), xycoords="axes fraction", ha="center", va="center" ) # Plot the data for i, j in zip(*np.triu_indices_from(axes, k=1)): if full: idx = [(i, j), (j, i)] else: idx = [(i, j)] for x, y in idx: # FIX #1: this needed to be changed from ...(data[x], data[y],...) if plotargs is None: if len(X[x]) > 100: plotargs = ",b" # pixel marker else: plotargs = ".b" # point marker axes[x, y].plot(X[y], X[x], plotargs) ylim = min(X[y]), max(X[y]) xlim = min(X[x]), max(X[x]) axes[x, y].set_ylim( xlim[0] - (xlim[1] - xlim[0]) * 0.1, xlim[1] + (xlim[1] - xlim[0]) * 0.1 ) axes[x, y].set_xlim( ylim[0] - (ylim[1] - ylim[0]) * 0.1, ylim[1] + (ylim[1] - ylim[0]) * 0.1 ) # Turn on the proper x or y axes ticks. if full: for i, j in zip(list(range(numvars)), itertools.cycle((-1, 0))): axes[j, i].xaxis.set_visible(True) axes[i, j].yaxis.set_visible(True) else: for i in range(numvars - 1): axes[0, i + 1].xaxis.set_visible(True) axes[i, -1].yaxis.set_visible(True) for i in range(1, numvars): for j in range(0, i): fig.delaxes(axes[i, j]) # FIX #2: if numvars is odd, the bottom right corner plot doesn't have the # correct axes limits, so we pull them from other axes if numvars % 2: xlimits = axes[0, -1].get_xlim() ylimits = axes[-1, 0].get_ylim() axes[-1, -1].set_xlim(xlimits) axes[-1, -1].set_ylim(ylimits) return fig
https://github.com/tisimst/mcerp/blob/2bb8260c9ad2d58a806847f1b627b6451e407de1/mcerp/correlate.py#L98-L201
scatter plot
python
def scatter_table(self, x, y, c, s, mark='*'): """Add a data series to the plot. :param x: array containing x-values. :param y: array containing y-values. :param c: array containing values for the color of the mark. :param s: array containing values for the size of the mark. :param mark: the symbol used to mark the data point. May be None, or any plot mark accepted by TikZ (e.g. ``*, x, +, o, square, triangle``). The dimensions of x, y, c and s should be equal. The c values will be mapped to a colormap. """ # clear the background of the marks # self._clear_plot_mark_background(x, y, mark, markstyle) # draw the plot series over the background options = self._parse_plot_options(mark) s = [sqrt(si) for si in s] plot_series = self._create_plot_tables_object(x, y, c, s, options) self.plot_table_list.append(plot_series)
https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/artist/plot.py#L460-L481
scatter plot
python
def _scatter_or_line(h1: Histogram1D, mark_template: list, kwargs: dict) -> dict: """Create shared properties for scatter / line plot.""" from physt.histogram_collection import HistogramCollection if isinstance(h1, HistogramCollection): collection = h1 h1 = h1[0] else: collection = HistogramCollection(h1) vega = _create_figure(kwargs) legend = kwargs.pop("legend", len(collection) > 1) vega["data"] = [ { "name": "table", "values": [] }, { "name": "labels", "values": [h.name for h in collection] }] for hist_i, histogram in enumerate(collection): centers = histogram.bin_centers.tolist() data = get_data(histogram, kwargs.pop("density", None), kwargs.pop("cumulative", None)).tolist() vega["data"][0]["values"] += [{"x": centers[i], "y": data[i], "c": hist_i} for i in range(histogram.bin_count)] _add_title(collection, vega, kwargs) _create_scales(collection, vega, kwargs) _create_axes(collection, vega, kwargs) _create_series_scales(vega) _create_series_faceted_marks(vega, mark_template) _create_tooltips(h1, vega, kwargs) # TODO: Make it work! if legend: _create_series_legend(vega) return vega
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/vega.py#L511-L548
scatter plot
python
def display_plots(filebase, directory=None, width=700, height=500, **kwargs): """Display a series of plots controlled by sliders. The function relies on Python string format functionality to index through a series of plots.""" def show_figure(filebase, directory, **kwargs): """Helper function to load in the relevant plot for display.""" filename = filebase.format(**kwargs) if directory is not None: filename = directory + '/' + filename display(HTML("<img src='{filename}'>".format(filename=filename))) interact(show_figure, filebase=fixed(filebase), directory=fixed(directory), **kwargs)
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/notebook.py#L198-L207
scatter plot
python
def create_plots(self): """Creates plots according to each plotting class. """ for i, axis in enumerate(self.ax): # plot everything. First check general dict for parameters related to plots. trans_plot_class_call = globals()[self.plot_types[i]] trans_plot_class = trans_plot_class_call(self.fig, axis, self.value_classes[i].x_arr_list, self.value_classes[i].y_arr_list, self.value_classes[i].z_arr_list, colorbar=( self.colorbar_classes[self.plot_types[i]]), **{**self.general, **self.figure, **self.plot_info[str(i)], **self.plot_info[str(i)]['limits'], **self.plot_info[str(i)]['label'], **self.plot_info[str(i)]['extra'], **self.plot_info[str(i)]['legend']}) # create the plot trans_plot_class.make_plot() # setup the plot trans_plot_class.setup_plot() # print("Axis", i, "Complete") return
https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/bowie/plotutils/makeprocess.py#L252-L280
scatter plot
python
def scatter(inputs, target_gpus, dim=0): """Scatter inputs to target gpus. The only difference from original :func:`scatter` is to add support for :type:`~mmcv.parallel.DataContainer`. """ def scatter_map(obj): if isinstance(obj, torch.Tensor): return OrigScatter.apply(target_gpus, None, dim, obj) if isinstance(obj, DataContainer): if obj.cpu_only: return obj.data else: return Scatter.forward(target_gpus, obj.data) if isinstance(obj, tuple) and len(obj) > 0: return list(zip(*map(scatter_map, obj))) if isinstance(obj, list) and len(obj) > 0: out = list(map(list, zip(*map(scatter_map, obj)))) return out if isinstance(obj, dict) and len(obj) > 0: out = list(map(type(obj), zip(*map(scatter_map, obj.items())))) return out return [obj for targets in target_gpus] # After scatter_map is called, a scatter_map cell will exist. This cell # has a reference to the actual function scatter_map, which has references # to a closure that has a reference to the scatter_map cell (because the # fn is recursive). To avoid this reference cycle, we set the function to # None, clearing the cell try: return scatter_map(inputs) finally: scatter_map = None
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/parallel/scatter_gather.py#L8-L41
scatter plot
python
def plot( self, ax: GeoAxesSubplot, cmap: str = "inferno", s: int = 5, **kwargs ) -> Artist: """Plotting function. All arguments are passed to ax.scatter""" return ax.scatter( self.df.longitude, self.df.latitude, s=s, transform=PlateCarree(), c=-self.df.altitude, cmap=cmap, **kwargs, )
https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/data/adsb/opensky.py#L32-L44
scatter plot
python
def scatter_matrix(frame, c=None, s=None, figsize=None, dpi=72.0, **kwds): """Draw a matrix of scatter plots. The result is an interactive pan/zoomable plot, with linked-brushing enabled by holding the shift key. Parameters ---------- frame : DataFrame The dataframe for which to draw the scatter matrix. c : string (optional) If specified, the name of the column to be used to determine the color of each point. s : string (optional) If specified, the name of the column to be used to determine the size of each point, figsize : tuple (optional) A length-2 tuple speficying the size of the figure in inches dpi : float (default=72) The dots (i.e. pixels) per inch used to convert the figure size from inches to pixels. Returns ------- chart: alt.Chart object The alt.Chart representation of the plot. See Also -------- pandas.plotting.scatter_matrix : matplotlib version of this routine """ if kwds: warnings.warn( "Unrecognized keywords in pdvega.scatter_matrix: {0}" "".format(list(kwds.keys())) ) cols = [ col for col in frame.columns if col not in [c, s] if infer_vegalite_type(frame[col], ordinal_threshold=0) == "quantitative" ] spec = { "$schema": "https://vega.github.io/schema/vega-lite/v2.json", "repeat": {"row": cols, "column": cols[::-1]}, "spec": { "mark": "point", "selection": { "brush": { "type": "interval", "resolve": "union", "on": "[mousedown[event.shiftKey], window:mouseup] > window:mousemove!", "translate": "[mousedown[event.shiftKey], window:mouseup] > window:mousemove!", "zoom": "wheel![event.shiftKey]", }, "grid": { "type": "interval", "resolve": "global", "bind": "scales", "translate": "[mousedown[!event.shiftKey], window:mouseup] > window:mousemove!", "zoom": "wheel![!event.shiftKey]", }, }, "encoding": { "x": {"field": {"repeat": "column"}, "type": "quantitative"}, "y": {"field": {"repeat": "row"}, "type": "quantitative"}, "color": {"condition": {"selection": "brush"}, "value": "grey"}, }, }, } if figsize is not None: width_inches, height_inches = figsize spec["spec"]["width"] = 0.8 * dpi * width_inches / len(cols) spec["spec"]["height"] = 0.8 * dpi * height_inches / len(cols) if s is not None: spec["spec"]["encoding"]["size"] = { "field": s, "type": infer_vegalite_type(frame[s]) } cond = spec["spec"]["encoding"]["color"]["condition"] if c is None: cond["value"] = "steelblue" else: cond["field"] = c cond["type"] = infer_vegalite_type(frame[c]) chart = alt.Chart().from_dict(spec) chart.data = frame return chart
https://github.com/altair-viz/pdvega/blob/e3f1fc9730f8cd9ad70e7ba0f0a557f41279839a/pdvega/plotting.py#L12-L104