def choose_qualitative(self, name, n, desat, as_cmap): if as_cmap: pal = [] pal[:] = color_palette(name, n, desat) self.cmap = ListedColormap(pal, N=self.n_colors.value) else: self.pal[:] = color_palette(name, n, desat)
def finalize_values(config: dict, key: str, values: typing.List[str]) -> typing.Any: """ Turns parsed values into final value(s) for the config at the given key, e.g. based on the previous type of that parameter or other constraints. """ if len(values) == 0: return None # Special treatment for plot_seaborn_palette is needed, see #359. if key == "plot_seaborn_palette": if len(values) > 1: return values from seaborn.palettes import color_palette try: color_palette(values[0]) return values[0] except ValueError: return values if isinstance(config[key], bool): value = values[-1] if isinstance(value, str) and value.lower() == "false": return False elif isinstance(value, str) and value.lower() == "true": return True else: return not config[key] if not isinstance(config[key], list): return values[0] if isinstance(values[0], str) and values[0].lower() in ("[]", "none"): return [] return values
def choose_diverging(self, name, n, desat, variant, as_cmap=False): if variant == "reverse": name += "_r" if as_cmap: colors = color_palette(name, 256, desat) self.cmap = self._init_mutable_colormap() self._update_lut(self.cmap, np.c_[colors, np.ones(256)]) else: self.pal[:] = color_palette(name, n, desat)
def test_set_palette(self): rcmod.set_palette("deep") assert utils.get_color_cycle() == palettes.color_palette("deep", 10) rcmod.set_palette("pastel6") assert utils.get_color_cycle() == palettes.color_palette("pastel6", 6) rcmod.set_palette("dark", 4) assert utils.get_color_cycle() == palettes.color_palette("dark", 4) rcmod.set_palette("Set2", color_codes=True) assert utils.get_color_cycle() == palettes.color_palette("Set2", 8)
def _init_mutable_colormap(): """Create a matplotlib colormap that will be updated by the widgets.""" greys = color_palette("Greys", 256) cmap = LinearSegmentedColormap.from_list("interactive", greys) cmap._init() cmap._set_extremes() return cmap
def test_palplot_size(self): pal4 = color_palette("husl", 4) misc.palplot(pal4) size4 = plt.gcf().get_size_inches() assert tuple(size4) == (4, 1) pal5 = color_palette("husl", 5) misc.palplot(pal5) size5 = plt.gcf().get_size_inches() assert tuple(size5) == (5, 1) palbig = color_palette("husl", 3) misc.palplot(palbig, 2) sizebig = plt.gcf().get_size_inches() assert tuple(sizebig) == (6, 2)
def test_color_numeric_int_float_mix(self): z = pd.Series([1, 2], name="z") s = Nominal(order=[1.0, 2])._setup(z, Color()) c1, c2 = color_palette(n_colors=2) null = (np.nan, np.nan, np.nan) assert_array_equal(s(z), [c1, null, c2])
def test_color_named_values(self, t, x): name = "viridis" cmap = color_palette(name, as_cmap=True) s = Temporal(name)._setup(t, Color()) normed = (x - x.min()) / (x.max() - x.min()) assert_array_equal(s(t), cmap(normed)[:, :3]) # FIXME RGBA
def test_set_palette(self): rcmod.set_palette("deep") assert utils.get_color_cycle() == palettes.color_palette("deep", 10) rcmod.set_palette("pastel6") assert utils.get_color_cycle() == palettes.color_palette("pastel6", 6) rcmod.set_palette("dark", 4) assert utils.get_color_cycle() == palettes.color_palette("dark", 4) rcmod.set_palette("Set2", color_codes=True) assert utils.get_color_cycle() == palettes.color_palette("Set2", 8) assert mpl.colors.same_color(mpl.rcParams["patch.facecolor"], palettes.color_palette()[0])
def test_lmplot_scatter_kws(self): g = lm.lmplot(x="x", y="y", hue="h", data=self.df, ci=None) red_scatter, blue_scatter = g.axes[0, 0].collections red, blue = color_palette(n_colors=2) npt.assert_array_equal(red, red_scatter.get_facecolors()[0, :3]) npt.assert_array_equal(blue, blue_scatter.get_facecolors()[0, :3])
def choose_matplotlib(self, name, n, desat, variant, as_cmap=False): is_variant = lambda x: x[-2:] in ['_d', '_r'] if not is_variant(name): if variant == "reverse": name += "_r" elif variant == "dark": name += "_d" if as_cmap: pal = [] pal[:] = color_palette(name, 256, desat) if variant == "reverse" and is_variant(name): self.pal = self.pal[::-1] self.cmap = getattr(cm, name) else: self.pal[:] = color_palette(name, n, desat) if variant == "reverse" and is_variant(name): self.pal = self.pal[::-1]
def _get_categorical_mapping(self, scale, data): """Define mapping as lookup in list of discrete color values.""" levels = categorical_order(data, scale.order) n = len(levels) values = scale.values if isinstance(values, dict): self._check_dict_entries(levels, values) # TODO where to ensure that dict values have consistent representation? colors = [values[x] for x in levels] elif isinstance(values, list): colors = self._check_list_length(levels, scale.values) elif isinstance(values, tuple): colors = blend_palette(values, n) elif isinstance(values, str): colors = color_palette(values, n) elif values is None: if n <= len(get_color_cycle()): # Use current (global) default palette colors = color_palette(n_colors=n) else: colors = color_palette("husl", n) else: scale_class = scale.__class__.__name__ msg = " ".join([ f"Scale values for {self.variable} with a {scale_class} mapping", f"must be string, list, tuple, or dict; not {type(scale.values)}." ]) raise TypeError(msg) # If color specified here has alpha channel, it will override alpha property colors = self._standardize_color_sequence(colors) def mapping(x): ixs = np.asarray(x, np.intp) use = np.isfinite(x) out = np.full((len(ixs), colors.shape[1]), np.nan) out[use] = np.take(colors, ixs[use], axis=0) return out return mapping
def get_mapping( self, scale: ScaleSpec, data: Series ) -> Callable[[ArrayLike], ArrayLike]: """Return a function that maps from data domain to color values.""" # TODO what is best way to do this conditional? # Should it be class-based or should classes have behavioral attributes? if isinstance(scale, Nominal): return self._get_categorical_mapping(scale, data) if scale.values is None: # TODO Rethink best default continuous color gradient mapping = color_palette("ch:", as_cmap=True) elif isinstance(scale.values, tuple): # TODO blend_palette will strip alpha, but we should support # interpolation on all four channels mapping = blend_palette(scale.values, as_cmap=True) elif isinstance(scale.values, str): # TODO for matplotlib colormaps this will clip extremes, which is # different from what using the named colormap directly would do # This may or may not be desireable. mapping = color_palette(scale.values, as_cmap=True) elif callable(scale.values): mapping = scale.values else: scale_class = scale.__class__.__name__ msg = " ".join([ f"Scale values for {self.variable} with a {scale_class} mapping", f"must be string, tuple, or callable; not {type(scale.values)}." ]) raise TypeError(msg) def _mapping(x): # Remove alpha channel so it does not override alpha property downstream # TODO this will need to be more flexible to support RGBA tuples (see above) invalid = ~np.isfinite(x) out = mapping(x)[:, :3] out[invalid] = np.nan return out return _mapping
def test_set_with_palette(self): rcmod.reset_orig() rcmod.set_theme(palette="deep") assert utils.get_color_cycle() == palettes.color_palette("deep", 10) rcmod.reset_orig() rcmod.set_theme(palette="deep", color_codes=False) assert utils.get_color_cycle() == palettes.color_palette("deep", 10) rcmod.reset_orig() pal = palettes.color_palette("deep") rcmod.set_theme(palette=pal) assert utils.get_color_cycle() == palettes.color_palette("deep", 10) rcmod.reset_orig() rcmod.set_theme(palette=pal, color_codes=False) assert utils.get_color_cycle() == palettes.color_palette("deep", 10) rcmod.reset_orig() rcmod.set_theme()
def _bivariate_kdeplot(x, y, filled, fill_lowest, kernel, bw, gridsize, cut, clip, axlabel, cbar, cbar_ax, cbar_kws, ax, **kwargs): """Plot a joint KDE estimate as a bivariate contour plot.""" # Determine the clipping if clip is None: clip = [(-np.inf, np.inf), (-np.inf, np.inf)] elif np.ndim(clip) == 1: clip = [clip, clip] # Calculate the KDE if sd._has_statsmodels: xx, yy, z = sd._statsmodels_bivariate_kde(x, y, bw, gridsize, cut, clip) else: xx, yy, z = sd._scipy_bivariate_kde(x, y, bw, gridsize, cut, clip) # Plot the contours n_levels = kwargs.pop("n_levels", 10) cmap = kwargs.get("cmap", "BuGn" if filled else "BuGn_d") if isinstance(cmap, string_types): if cmap.endswith("_d"): pal = ["#333333"] pal.extend(color_palette(cmap.replace("_d", "_r"), 2)) cmap = blend_palette(pal, as_cmap=True) else: cmap = plt.cm.get_cmap(cmap) kwargs["cmap"] = cmap contour_func = ax.contourf if filled else ax.contour cset = contour_func(xx, yy, z, n_levels, **kwargs) if filled and not fill_lowest: cset.collections[0].set_alpha(0) kwargs["n_levels"] = n_levels if cbar: cbar_kws = {} if cbar_kws is None else cbar_kws ax.figure.colorbar(cset, cbar_ax, ax, **cbar_kws) # Label the axes if hasattr(x, "name") and axlabel: ax.set_xlabel(x.name) if hasattr(y, "name") and axlabel: ax.set_ylabel(y.name) return ax, cset
def test_color_named_palette(self, x): pal = "flare" s = Nominal(pal)._setup(x, Color()) cs = color_palette(pal, 3) assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])
def test_color_named_values(self, x): cmap = color_palette("viridis", as_cmap=True) s = Continuous("viridis")._setup(x, Color()) assert_array_equal(s(x), cmap([0, .25, 1])[:, :3]) # FIXME RGBA
def test_color_defaults(self, x): cmap = color_palette("ch:", as_cmap=True) s = Continuous()._setup(x, Color()) assert_array_equal(s(x), cmap([0, .25, 1])[:, :3]) # FIXME RGBA
def jointplot_gmm( locs, covs, labels=None, out_file=None, xlims=None, ylims=None, xname="Image A", yname="Image B", size=20, ratio=5, space=0.2, ): import os.path as op import nibabel as nb import numpy as np import os import seaborn as sn from seaborn.palettes import color_palette, light_palette import pandas as pd import matplotlib.pyplot as plt import matplotlib.mlab as mlab from matplotlib import patches as mpatches from scipy.stats import multivariate_normal if len(locs) != len(covs): raise RuntimeError("Mixture model does not contain elements") ncomp = np.shape(locs)[1] f = plt.figure(figsize=(size, size)) gs = plt.GridSpec(ratio + 1, ratio + 1) sn.set_context("talk", font_scale=1.8) ax_joint = f.add_subplot(gs[1:, :-1]) ax_marg_x = f.add_subplot(gs[0, :-1], sharex=ax_joint) ax_marg_y = f.add_subplot(gs[1:, -1], sharey=ax_joint) # Turn off tick visibility for the measure axis on the marginal plots plt.setp(ax_marg_x.get_xticklabels(), visible=False) plt.setp(ax_marg_y.get_yticklabels(), visible=False) # Turn off the ticks on the density axis for the marginal plots plt.setp(ax_marg_x.yaxis.get_majorticklines(), visible=False) plt.setp(ax_marg_x.yaxis.get_minorticklines(), visible=False) plt.setp(ax_marg_y.xaxis.get_majorticklines(), visible=False) plt.setp(ax_marg_y.xaxis.get_minorticklines(), visible=False) plt.setp(ax_marg_x.get_yticklabels(), visible=False) plt.setp(ax_marg_y.get_xticklabels(), visible=False) plt.setp(ax_joint.get_yticklabels(), visible=False) plt.setp(ax_joint.get_xticklabels(), visible=False) ax_joint.set_xlabel(xname) ax_joint.set_ylabel(yname) ax_marg_x.yaxis.grid(False) ax_marg_y.xaxis.grid(False) palette = color_palette("husl", n_colors=len(locs)) # Make the grid look nice sn.utils.despine(f) sn.utils.despine(ax=ax_marg_x, left=True) sn.utils.despine(ax=ax_marg_y, bottom=True) f.tight_layout() f.subplots_adjust(hspace=space, wspace=space) if xlims is None: xlims = (0.0, 1.0) if ylims is None: ylims = (0.0, 1.0) xstep = (xlims[1] - xlims[0]) / 100 ystep = (ylims[1] - ylims[0]) / 100 X, Y = np.mgrid[xlims[0] : xlims[1] + xstep : xstep, ylims[0] : ylims[1] + ystep : ystep] pos = np.empty(X.shape + (2,)) pos[:, :, 0] = X pos[:, :, 1] = Y y = Y[0] x = pos.T[0][0] if labels is None: labels = [None] * len(locs) patches = [] for mu, cov, color, l in zip(locs, covs, palette, labels): cov = np.array(cov).reshape(ncomp, ncomp) mv = multivariate_normal(mu, cov) ZC = ax_joint.contour(X, Y, mv.pdf(pos), cmap=light_palette(color, as_cmap=True)) if l is not None: ax_joint.annotate( l, xy=(mu[0], mu[1]), xytext=(30, 20), textcoords="offset points", size=30, va="center", color="w", bbox=dict(boxstyle="round", fc=color, ec="none", alpha=0.9, color="w"), arrowprops=dict(arrowstyle="wedge,tail_width=0.7", fc=color, ec="none", alpha=0.6, relpos=(0.2, 0.5)), ) Zx = mlab.normpdf(x, mu[0], np.sqrt(cov[0][0])) ax_marg_x.plot(x, Zx, color=color, label=l) Zy = mlab.normpdf(y, mu[1], np.sqrt(cov[1][1])) ax_marg_y.plot(Zy, y, color=color) if out_file is None: out_file = op.abspath("jointplot.pdf") plt.savefig(out_file, dpi=300, bbox_inches="tight") return out_file
def test_color_defaults(self, t, x): cmap = color_palette("ch:", as_cmap=True) s = Temporal()._setup(t, Color()) normed = (x - x.min()) / (x.max() - x.min()) assert_array_equal(s(t), cmap(normed)[:, :3]) # FIXME RGBA
def test_color_numeric_with_order_subset(self, y): s = Nominal(order=[-1.5, 1])._setup(y, Color()) c1, c2 = color_palette(n_colors=2) null = (np.nan, np.nan, np.nan) assert_array_equal(s(y), [c2, c1, null, c1])
def test_color_dict_palette(self, x): cs = color_palette("crest", 3) pal = dict(zip("bac", cs)) s = Nominal(pal)._setup(x, Color()) assert_array_equal(s(x), [cs[1], cs[2], cs[0], cs[2]])
def test_color_numeric_data(self, y): s = Nominal()._setup(y, Color()) cs = color_palette() assert_array_equal(s(y), [cs[1], cs[0], cs[2], cs[0]])
def tsplot(data, time=None, unit=None, condition=None, value=None, err_style="ci_band", ci=68, interpolate=True, color=None, estimator=np.mean, n_boot=5000, err_palette=None, err_kws=None, legend=True, ax=None, **kwargs): """Plot one or more timeseries with flexible representation of uncertainty. This function can take data specified either as a long-form (tidy) DataFrame or as an ndarray with dimensions for sampling unit, time, and (optionally) condition. The interpretation of some of the other parameters changes depending on the type of object passed as data. Parameters ---------- data : DataFrame or ndarray Data for the plot. Should either be a "long form" dataframe or an array with dimensions (unit, time, condition). In both cases, the condition field/dimension is optional. The type of this argument determines the interpretation of the next few parameters. time : string or series-like Either the name of the field corresponding to time in the data DataFrame or x values for a plot when data is an array. If a Series, the name will be used to label the x axis. unit : string Field in the data DataFrame identifying the sampling unit (e.g. subject, neuron, etc.). The error representation will collapse over units at each time/condition observation. This has no role when data is an array. value : string Either the name of the field corresponding to the data values in the data DataFrame (i.e. the y coordinate) or a string that forms the y axis label when data is an array. condition : string or Series-like Either the name of the field identifying the condition an observation falls under in the data DataFrame, or a sequence of names with a length equal to the size of the third dimension of data. There will be a separate trace plotted for each condition. If condition is a Series with a name attribute, the name will form the title for the plot legend (unless legend is set to False). err_style : string or list of strings or None Names of ways to plot uncertainty across units from set of {ci_band, ci_bars, boot_traces, boot_kde, unit_traces, unit_points}. Can use one or more than one method. ci : float or list of floats in [0, 100] Confidence interaval size(s). If a list, it will stack the error plots for each confidence interval. Only relevant for error styles with "ci" in the name. interpolate : boolean Whether to do a linear interpolation between each timepoint when plotting. The value of this parameter also determines the marker used for the main plot traces, unless marker is specified as a keyword argument. color : seaborn palette or matplotlib color name or dictionary Palette or color for the main plots and error representation (unless plotting by unit, which can be separately controlled with err_palette). If a dictionary, should map condition name to color spec. estimator : callable Function to determine central tendency and to pass to bootstrap must take an ``axis`` argument. n_boot : int Number of bootstrap iterations. err_palette: seaborn palette Palette name or list of colors used when plotting data for each unit. err_kws : dict, optional Keyword argument dictionary passed through to matplotlib function generating the error plot, ax : axis object, optional Plot in given axis; if None creates a new figure kwargs : Other keyword arguments are passed to main plot() call Returns ------- ax : matplotlib axis axis with plot data """ # Sort out default values for the parameters if ax is None: ax = plt.gca() if err_kws is None: err_kws = {} # Handle different types of input data if isinstance(data, pd.DataFrame): xlabel = time ylabel = value # Condition is optional if condition is None: condition = pd.Series(np.ones(len(data))) legend = False legend_name = None n_cond = 1 else: legend = True and legend legend_name = condition n_cond = len(data[condition].unique()) else: data = np.asarray(data) # Data can be a timecourse from a single unit or # several observations in one condition if data.ndim == 1: data = data[np.newaxis, :, np.newaxis] elif data.ndim == 2: data = data[:, :, np.newaxis] n_unit, n_time, n_cond = data.shape # Units are experimental observations. Maybe subjects, or neurons if unit is None: units = np.arange(n_unit) unit = "unit" units = np.repeat(units, n_time * n_cond) ylabel = None # Time forms the xaxis of the plot if time is None: times = np.arange(n_time) else: times = np.asarray(time) xlabel = None if hasattr(time, "name"): xlabel = time.name time = "time" times = np.tile(np.repeat(times, n_cond), n_unit) # Conditions split the timeseries plots if condition is None: conds = list(range(n_cond)) legend = False if isinstance(color, dict): err = "Must have condition names if using color dict." raise ValueError(err) else: conds = np.asarray(condition) legend = True and legend if hasattr(condition, "name"): legend_name = condition.name else: legend_name = None condition = "cond" conds = np.tile(conds, n_unit * n_time) # Value forms the y value in the plot if value is None: ylabel = None else: ylabel = value value = "value" # Convert to long-form DataFrame data = pd.DataFrame( dict(value=data.ravel(), time=times, unit=units, cond=conds)) # Set up the err_style and ci arguments for teh loop below if isinstance(err_style, string_types): err_style = [err_style] elif err_style is None: err_style = [] if not hasattr(ci, "__iter__"): ci = [ci] # Set up the color palette if color is None: current_palette = mpl.rcParams["axes.color_cycle"] if len(current_palette) < n_cond: colors = color_palette("husl", n_cond) else: colors = color_palette(n_colors=n_cond) elif isinstance(color, dict): colors = [color[c] for c in data[condition].unique()] else: try: colors = color_palette(color, n_cond) except ValueError: color = mpl.colors.colorConverter.to_rgb(color) colors = [color] * n_cond # Do a groupby with condition and plot each trace for c, (cond, df_c) in enumerate(data.groupby(condition, sort=False)): df_c = df_c.pivot(unit, time, value) x = df_c.columns.values.astype(np.float) # Bootstrap the data for confidence intervals #boot_data = algo.bootstrap(df_c.values, n_boot=n_boot, # axis=0, func=estimator) boot_data = df_c.values cis = [utils.ci(boot_data, v, axis=0) for v in ci] central_data = estimator(df_c.values, axis=0) # Get the color for this condition color = colors[c] # Use subroutines to plot the uncertainty for style in err_style: # Allow for null style (only plot central tendency) if style is None: continue # Grab the function from the global environment try: plot_func = globals()["_plot_%s" % style] except KeyError: raise ValueError("%s is not a valid err_style" % style) # Possibly set up to plot each observation in a different color if err_palette is not None and "unit" in style: orig_color = color color = color_palette(err_palette, len(df_c.values)) # Pass all parameters to the error plotter as keyword args plot_kwargs = dict(ax=ax, x=x, data=df_c.values, boot_data=boot_data, central_data=central_data, color=color, err_kws=err_kws) # Plot the error representation, possibly for multiple cis for ci_i in cis: plot_kwargs["ci"] = ci_i plot_func(**plot_kwargs) if err_palette is not None and "unit" in style: color = orig_color # Plot the central trace kwargs.setdefault("marker", "" if interpolate else "o") ls = kwargs.pop("ls", "-" if interpolate else "") kwargs.setdefault("linestyle", ls) label = cond if legend else "_nolegend_" ax.plot(x, central_data, color=color, label=label, **kwargs) # Pad the sides of the plot only when not interpolating ax.set_xlim(x.min(), x.max()) x_diff = x[1] - x[0] if not interpolate: ax.set_xlim(x.min() - x_diff, x.max() + x_diff) # Add the plot labels if xlabel is not None: ax.set_xlabel(xlabel) if ylabel is not None: ax.set_ylabel(ylabel) if legend: ax.legend(loc=0, title=legend_name) return ax
def test_color_list_palette(self, x): cs = color_palette("crest", 3) s = Nominal(cs)._setup(x, Color()) assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])
def test_color_defaults(self, x): s = Nominal()._setup(x, Color()) cs = color_palette() assert_array_equal(s(x), [cs[0], cs[1], cs[2], cs[1]])
def test_color_with_transform(self, x): x = pd.Series([1, 10, 100], name="x", dtype=float) cmap = color_palette("ch:", as_cmap=True) s = Continuous(trans="log")._setup(x, Color()) assert_array_equal(s(x), cmap([0, .5, 1])[:, :3]) # FIXME RGBA
def test_color_with_norm(self, x): cmap = color_palette("ch:", as_cmap=True) s = Continuous(norm=(3, 7))._setup(x, Color()) assert_array_equal(s(x), cmap([-.5, 0, 1.5])[:, :3]) # FIXME RGBA
def test_color_callable_values(self, x): cmap = color_palette("light:r", as_cmap=True) s = Continuous(cmap)._setup(x, Color()) assert_array_equal(s(x), cmap([0, .25, 1])[:, :3]) # FIXME RGBA
def test_color_tuple_values(self, x): cmap = color_palette("blend:b,g", as_cmap=True) s = Continuous(("b", "g"))._setup(x, Color()) assert_array_equal(s(x), cmap([0, .25, 1])[:, :3]) # FIXME RGBA