index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
32,066
pingouin.parametric
welch_anova
One-way Welch ANOVA. Parameters ---------- data : :py:class:`pandas.DataFrame` DataFrame. Note that this function can also directly be used as a Pandas method, in which case this argument is no longer needed. dv : string Name of column containing the dependent variable. between : string Name of column containing the between factor. Returns ------- aov : :py:class:`pandas.DataFrame` ANOVA summary: * ``'Source'``: Factor names * ``'ddof1'``: Numerator degrees of freedom * ``'ddof2'``: Denominator degrees of freedom * ``'F'``: F-values * ``'p-unc'``: uncorrected p-values * ``'np2'``: Partial eta-squared See Also -------- anova : One-way and N-way ANOVA rm_anova : One-way and two-way repeated measures ANOVA mixed_anova : Two way mixed ANOVA kruskal : Non-parametric one-way ANOVA Notes ----- From Wikipedia: *It is named for its creator, Bernard Lewis Welch, and is an adaptation of Student's t-test, and is more reliable when the two samples have unequal variances and/or unequal sample sizes.* The classic ANOVA is very powerful when the groups are normally distributed and have equal variances. However, when the groups have unequal variances, it is best to use the Welch ANOVA that better controls for type I error (Liu 2015). The homogeneity of variances can be measured with the `homoscedasticity` function. The two other assumptions of normality and independance remain. The main idea of Welch ANOVA is to use a weight :math:`w_i` to reduce the effect of unequal variances. This weight is calculated using the sample size :math:`n_i` and variance :math:`s_i^2` of each group :math:`i=1,...,r`: .. math:: w_i = \frac{n_i}{s_i^2} Using these weights, the adjusted grand mean of the data is: .. math:: \overline{Y}_{\text{welch}} = \frac{\sum_{i=1}^r w_i\overline{Y}_i}{\sum w} where :math:`\overline{Y}_i` is the mean of the :math:`i` group. The effect sums of squares is defined as: .. math:: SS_{\text{effect}} = \sum_{i=1}^r w_i (\overline{Y}_i - \overline{Y}_{\text{welch}})^2 We then need to calculate a term lambda: .. math:: \Lambda = \frac{3\sum_{i=1}^r(\frac{1}{n_i-1}) (1 - \frac{w_i}{\sum w})^2}{r^2 - 1} from which the F-value can be calculated: .. math:: F_{\text{welch}} = \frac{SS_{\text{effect}} / (r-1)} {1 + \frac{2\Lambda(r-2)}{3}} and the p-value approximated using a F-distribution with :math:`(r-1, 1 / \Lambda)` degrees of freedom. When the groups are balanced and have equal variances, the optimal post-hoc test is the Tukey-HSD test (:py:func:`pingouin.pairwise_tukey`). If the groups have unequal variances, the Games-Howell test is more adequate (:py:func:`pingouin.pairwise_gameshowell`). Results have been tested against R. References ---------- .. [1] Liu, Hangcheng. "Comparing Welch's ANOVA, a Kruskal-Wallis test and traditional ANOVA in case of Heterogeneity of Variance." (2015). .. [2] Welch, Bernard Lewis. "On the comparison of several mean values: an alternative approach." Biometrika 38.3/4 (1951): 330-336. Examples -------- 1. One-way Welch ANOVA on the pain threshold dataset. >>> from pingouin import welch_anova, read_dataset >>> df = read_dataset('anova') >>> aov = welch_anova(dv='Pain threshold', between='Hair color', data=df) >>> aov Source ddof1 ddof2 F p-unc np2 0 Hair color 3 8.329841 5.890115 0.018813 0.575962
@pf.register_dataframe_method def welch_anova(data=None, dv=None, between=None): """One-way Welch ANOVA. Parameters ---------- data : :py:class:`pandas.DataFrame` DataFrame. Note that this function can also directly be used as a Pandas method, in which case this argument is no longer needed. dv : string Name of column containing the dependent variable. between : string Name of column containing the between factor. Returns ------- aov : :py:class:`pandas.DataFrame` ANOVA summary: * ``'Source'``: Factor names * ``'ddof1'``: Numerator degrees of freedom * ``'ddof2'``: Denominator degrees of freedom * ``'F'``: F-values * ``'p-unc'``: uncorrected p-values * ``'np2'``: Partial eta-squared See Also -------- anova : One-way and N-way ANOVA rm_anova : One-way and two-way repeated measures ANOVA mixed_anova : Two way mixed ANOVA kruskal : Non-parametric one-way ANOVA Notes ----- From Wikipedia: *It is named for its creator, Bernard Lewis Welch, and is an adaptation of Student's t-test, and is more reliable when the two samples have unequal variances and/or unequal sample sizes.* The classic ANOVA is very powerful when the groups are normally distributed and have equal variances. However, when the groups have unequal variances, it is best to use the Welch ANOVA that better controls for type I error (Liu 2015). The homogeneity of variances can be measured with the `homoscedasticity` function. The two other assumptions of normality and independance remain. The main idea of Welch ANOVA is to use a weight :math:`w_i` to reduce the effect of unequal variances. This weight is calculated using the sample size :math:`n_i` and variance :math:`s_i^2` of each group :math:`i=1,...,r`: .. math:: w_i = \\frac{n_i}{s_i^2} Using these weights, the adjusted grand mean of the data is: .. math:: \\overline{Y}_{\\text{welch}} = \\frac{\\sum_{i=1}^r w_i\\overline{Y}_i}{\\sum w} where :math:`\\overline{Y}_i` is the mean of the :math:`i` group. The effect sums of squares is defined as: .. math:: SS_{\\text{effect}} = \\sum_{i=1}^r w_i (\\overline{Y}_i - \\overline{Y}_{\\text{welch}})^2 We then need to calculate a term lambda: .. math:: \\Lambda = \\frac{3\\sum_{i=1}^r(\\frac{1}{n_i-1}) (1 - \\frac{w_i}{\\sum w})^2}{r^2 - 1} from which the F-value can be calculated: .. math:: F_{\\text{welch}} = \\frac{SS_{\\text{effect}} / (r-1)} {1 + \\frac{2\\Lambda(r-2)}{3}} and the p-value approximated using a F-distribution with :math:`(r-1, 1 / \\Lambda)` degrees of freedom. When the groups are balanced and have equal variances, the optimal post-hoc test is the Tukey-HSD test (:py:func:`pingouin.pairwise_tukey`). If the groups have unequal variances, the Games-Howell test is more adequate (:py:func:`pingouin.pairwise_gameshowell`). Results have been tested against R. References ---------- .. [1] Liu, Hangcheng. "Comparing Welch's ANOVA, a Kruskal-Wallis test and traditional ANOVA in case of Heterogeneity of Variance." (2015). .. [2] Welch, Bernard Lewis. "On the comparison of several mean values: an alternative approach." Biometrika 38.3/4 (1951): 330-336. Examples -------- 1. One-way Welch ANOVA on the pain threshold dataset. >>> from pingouin import welch_anova, read_dataset >>> df = read_dataset('anova') >>> aov = welch_anova(dv='Pain threshold', between='Hair color', data=df) >>> aov Source ddof1 ddof2 F p-unc np2 0 Hair color 3 8.329841 5.890115 0.018813 0.575962 """ # Check data data = _check_dataframe(dv=dv, between=between, data=data, effects="between") # Reset index (avoid duplicate axis error) data = data.reset_index(drop=True) # Number of groups r = data[between].nunique() ddof1 = r - 1 # Compute weights and ajusted means grp = data.groupby(between, observed=True, group_keys=False)[dv] weights = grp.count() / grp.var(numeric_only=True) adj_grandmean = (weights * grp.mean(numeric_only=True)).sum() / weights.sum() # Sums of squares (regular and adjusted) ss_res = grp.apply(lambda x: (x - x.mean()) ** 2).sum() ss_bet = ( (grp.mean(numeric_only=True) - data[dv].mean(numeric_only=True)) ** 2 * grp.count() ).sum() ss_betadj = np.sum(weights * np.square(grp.mean(numeric_only=True) - adj_grandmean)) ms_betadj = ss_betadj / ddof1 # Calculate lambda, F-value, p-value and np2 lamb = (3 * np.sum((1 / (grp.count() - 1)) * (1 - (weights / weights.sum())) ** 2)) / ( r**2 - 1 ) ddof2 = 1 / lamb fval = ms_betadj / (1 + (2 * lamb * (r - 2)) / 3) pval = f.sf(fval, ddof1, ddof2) np2 = ss_bet / (ss_bet + ss_res) # Create output dataframe aov = pd.DataFrame( { "Source": between, "ddof1": ddof1, "ddof2": ddof2, "F": fval, "p-unc": pval, "np2": np2, }, index=[0], ) return _postprocess_dataframe(aov)
(data=None, dv=None, between=None)
32,067
pingouin.nonparametric
wilcoxon
Wilcoxon signed-rank test. It is the non-parametric version of the paired T-test. Parameters ---------- x : array_like Either the first set of measurements (in which case y is the second set of measurements), or the differences between two sets of measurements (in which case y is not to be specified.) Must be one-dimensional. y : array_like Either the second set of measurements (if x is the first set of measurements), or not specified (if x is the differences between two sets of measurements.) Must be one-dimensional. alternative : string Defines the alternative hypothesis, or tail of the test. Must be one of "two-sided" (default), "greater" or "less". See :py:func:`scipy.stats.wilcoxon` for more details. **kwargs : dict Additional keywords arguments that are passed to :py:func:`scipy.stats.wilcoxon`. Returns ------- stats : :py:class:`pandas.DataFrame` * ``'W-val'``: W-value * ``'alternative'``: tail of the test * ``'p-val'``: p-value * ``'RBC'`` : matched pairs rank-biserial correlation (effect size) * ``'CLES'`` : common language effect size See also -------- scipy.stats.wilcoxon, mwu Notes ----- The Wilcoxon signed-rank test [1]_ tests the null hypothesis that two related paired samples come from the same distribution. In particular, it tests whether the distribution of the differences x - y is symmetric about zero. .. important:: Pingouin automatically applies a continuity correction. Therefore, the p-values will be slightly different than :py:func:`scipy.stats.wilcoxon` unless ``correction=True`` is explicitly passed to the latter. In addition to the test statistic and p-values, Pingouin also computes two measures of effect size. The matched pairs rank biserial correlation [2]_ is the simple difference between the proportion of favorable and unfavorable evidence; in the case of the Wilcoxon signed-rank test, the evidence consists of rank sums (Kerby 2014): .. math:: r = f - u The common language effect size is the proportion of pairs where ``x`` is higher than ``y``. It was first introduced by McGraw and Wong (1992) [3]_. Pingouin uses a brute-force version of the formula given by Vargha and Delaney 2000 [4]_: .. math:: \text{CL} = P(X > Y) + .5 \times P(X = Y) The advantage is of this method are twofold. First, the brute-force approach pairs each observation of ``x`` to its ``y`` counterpart, and therefore does not require normally distributed data. Second, the formula takes ties into account and therefore works with ordinal data. When tail is ``'less'``, the CLES is then set to :math:`1 - \text{CL}`, which gives the proportion of pairs where ``x`` is *lower* than ``y``. References ---------- .. [1] Wilcoxon, F. (1945). Individual comparisons by ranking methods. Biometrics bulletin, 1(6), 80-83. .. [2] Kerby, D. S. (2014). The simple difference formula: An approach to teaching nonparametric correlation. Comprehensive Psychology, 3, 11-IT. .. [3] McGraw, K. O., & Wong, S. P. (1992). A common language effect size statistic. Psychological bulletin, 111(2), 361. .. [4] Vargha, A., & Delaney, H. D. (2000). A Critique and Improvement of the “CL” Common Language Effect Size Statistics of McGraw and Wong. Journal of Educational and Behavioral Statistics: A Quarterly Publication Sponsored by the American Educational Research Association and the American Statistical Association, 25(2), 101–132. https://doi.org/10.2307/1165329 Examples -------- Wilcoxon test on two related samples. >>> import numpy as np >>> import pingouin as pg >>> x = np.array([20, 22, 19, 20, 22, 18, 24, 20, 19, 24, 26, 13]) >>> y = np.array([38, 37, 33, 29, 14, 12, 20, 22, 17, 25, 26, 16]) >>> pg.wilcoxon(x, y, alternative='two-sided') W-val alternative p-val RBC CLES Wilcoxon 20.5 two-sided 0.285765 -0.378788 0.395833 Same but using pre-computed differences. However, the CLES effect size cannot be computed as it requires the raw data. >>> pg.wilcoxon(x - y) W-val alternative p-val RBC CLES Wilcoxon 20.5 two-sided 0.285765 -0.378788 NaN Compare with SciPy >>> import scipy >>> scipy.stats.wilcoxon(x, y) WilcoxonResult(statistic=20.5, pvalue=0.2661660677806492) The p-value is not exactly similar to Pingouin. This is because Pingouin automatically applies a continuity correction. Disabling it gives the same p-value as scipy: >>> pg.wilcoxon(x, y, alternative='two-sided', correction=False) W-val alternative p-val RBC CLES Wilcoxon 20.5 two-sided 0.266166 -0.378788 0.395833 One-sided test >>> pg.wilcoxon(x, y, alternative='greater') W-val alternative p-val RBC CLES Wilcoxon 20.5 greater 0.876244 -0.378788 0.395833 >>> pg.wilcoxon(x, y, alternative='less') W-val alternative p-val RBC CLES Wilcoxon 20.5 less 0.142883 -0.378788 0.604167
def wilcoxon(x, y=None, alternative="two-sided", **kwargs): """ Wilcoxon signed-rank test. It is the non-parametric version of the paired T-test. Parameters ---------- x : array_like Either the first set of measurements (in which case y is the second set of measurements), or the differences between two sets of measurements (in which case y is not to be specified.) Must be one-dimensional. y : array_like Either the second set of measurements (if x is the first set of measurements), or not specified (if x is the differences between two sets of measurements.) Must be one-dimensional. alternative : string Defines the alternative hypothesis, or tail of the test. Must be one of "two-sided" (default), "greater" or "less". See :py:func:`scipy.stats.wilcoxon` for more details. **kwargs : dict Additional keywords arguments that are passed to :py:func:`scipy.stats.wilcoxon`. Returns ------- stats : :py:class:`pandas.DataFrame` * ``'W-val'``: W-value * ``'alternative'``: tail of the test * ``'p-val'``: p-value * ``'RBC'`` : matched pairs rank-biserial correlation (effect size) * ``'CLES'`` : common language effect size See also -------- scipy.stats.wilcoxon, mwu Notes ----- The Wilcoxon signed-rank test [1]_ tests the null hypothesis that two related paired samples come from the same distribution. In particular, it tests whether the distribution of the differences x - y is symmetric about zero. .. important:: Pingouin automatically applies a continuity correction. Therefore, the p-values will be slightly different than :py:func:`scipy.stats.wilcoxon` unless ``correction=True`` is explicitly passed to the latter. In addition to the test statistic and p-values, Pingouin also computes two measures of effect size. The matched pairs rank biserial correlation [2]_ is the simple difference between the proportion of favorable and unfavorable evidence; in the case of the Wilcoxon signed-rank test, the evidence consists of rank sums (Kerby 2014): .. math:: r = f - u The common language effect size is the proportion of pairs where ``x`` is higher than ``y``. It was first introduced by McGraw and Wong (1992) [3]_. Pingouin uses a brute-force version of the formula given by Vargha and Delaney 2000 [4]_: .. math:: \\text{CL} = P(X > Y) + .5 \\times P(X = Y) The advantage is of this method are twofold. First, the brute-force approach pairs each observation of ``x`` to its ``y`` counterpart, and therefore does not require normally distributed data. Second, the formula takes ties into account and therefore works with ordinal data. When tail is ``'less'``, the CLES is then set to :math:`1 - \\text{CL}`, which gives the proportion of pairs where ``x`` is *lower* than ``y``. References ---------- .. [1] Wilcoxon, F. (1945). Individual comparisons by ranking methods. Biometrics bulletin, 1(6), 80-83. .. [2] Kerby, D. S. (2014). The simple difference formula: An approach to teaching nonparametric correlation. Comprehensive Psychology, 3, 11-IT. .. [3] McGraw, K. O., & Wong, S. P. (1992). A common language effect size statistic. Psychological bulletin, 111(2), 361. .. [4] Vargha, A., & Delaney, H. D. (2000). A Critique and Improvement of the “CL” Common Language Effect Size Statistics of McGraw and Wong. Journal of Educational and Behavioral Statistics: A Quarterly Publication Sponsored by the American Educational Research Association and the American Statistical Association, 25(2), 101–132. https://doi.org/10.2307/1165329 Examples -------- Wilcoxon test on two related samples. >>> import numpy as np >>> import pingouin as pg >>> x = np.array([20, 22, 19, 20, 22, 18, 24, 20, 19, 24, 26, 13]) >>> y = np.array([38, 37, 33, 29, 14, 12, 20, 22, 17, 25, 26, 16]) >>> pg.wilcoxon(x, y, alternative='two-sided') W-val alternative p-val RBC CLES Wilcoxon 20.5 two-sided 0.285765 -0.378788 0.395833 Same but using pre-computed differences. However, the CLES effect size cannot be computed as it requires the raw data. >>> pg.wilcoxon(x - y) W-val alternative p-val RBC CLES Wilcoxon 20.5 two-sided 0.285765 -0.378788 NaN Compare with SciPy >>> import scipy >>> scipy.stats.wilcoxon(x, y) WilcoxonResult(statistic=20.5, pvalue=0.2661660677806492) The p-value is not exactly similar to Pingouin. This is because Pingouin automatically applies a continuity correction. Disabling it gives the same p-value as scipy: >>> pg.wilcoxon(x, y, alternative='two-sided', correction=False) W-val alternative p-val RBC CLES Wilcoxon 20.5 two-sided 0.266166 -0.378788 0.395833 One-sided test >>> pg.wilcoxon(x, y, alternative='greater') W-val alternative p-val RBC CLES Wilcoxon 20.5 greater 0.876244 -0.378788 0.395833 >>> pg.wilcoxon(x, y, alternative='less') W-val alternative p-val RBC CLES Wilcoxon 20.5 less 0.142883 -0.378788 0.604167 """ x = np.asarray(x) if y is not None: y = np.asarray(y) x, y = remove_na(x, y, paired=True) # Remove NA else: x = x[~np.isnan(x)] # Check tails assert alternative in [ "two-sided", "greater", "less", ], "Alternative must be one of 'two-sided' (default), 'greater' or 'less'." if "tail" in kwargs: raise ValueError( "Since Pingouin 0.4.0, the 'tail' argument has been renamed to 'alternative'." ) # Compute test if "correction" not in kwargs: kwargs["correction"] = True wval, pval = scipy.stats.wilcoxon(x=x, y=y, alternative=alternative, **kwargs) # Effect size 1: Common Language Effect Size # Since Pingouin v0.3.5, CLES is tail-specific and calculated # according to the formula given in Vargha and Delaney 2000 which # works with ordinal data. if y is not None: diff = x[:, None] - y # cles = max((diff < 0).sum(), (diff > 0).sum()) / diff.size # alternative = 'greater', with ties set to 0.5 # Note that alternative = 'two-sided' gives same output as alternative = 'greater' cles = np.where(diff == 0, 0.5, diff > 0).mean() cles = 1 - cles if alternative == "less" else cles else: # CLES cannot be computed if y is None cles = np.nan # Effect size 2: matched-pairs rank biserial correlation (Kerby 2014) if y is not None: d = x - y d = d[d != 0] else: d = x[x != 0] r = scipy.stats.rankdata(abs(d)) rsum = r.sum() r_plus = np.sum((d > 0) * r) r_minus = np.sum((d < 0) * r) rbc = r_plus / rsum - r_minus / rsum # Fill output DataFrame stats = pd.DataFrame( {"W-val": wval, "alternative": alternative, "p-val": pval, "RBC": rbc, "CLES": cles}, index=["Wilcoxon"], ) return _postprocess_dataframe(stats)
(x, y=None, alternative='two-sided', **kwargs)
32,068
bqplot.scales
Albers
A geographical scale which is an alias for a conic equal area projection. The Albers projection is a conic equal area map. It does not preserve scale or shape, though it is recommended for chloropleths since it preserves the relative areas of geographic features. Default values are US-centric. Attributes ---------- scale_factor: float (default: 250) Specifies the scale value for the projection rotate: tuple (default: (96, 0)) Degree of rotation in each axis. parallels: tuple (default: (29.5, 45.5)) Sets the two parallels for the conic projection. center: tuple (default: (0, 60)) Specifies the longitude and latitude where the map is centered. precision: float (default: 0.1) Specifies the threshold for the projections adaptive resampling to the specified value in pixels. rtype: (Number, Number) (class-level attribute) This attribute should not be modified. The range type of a geo scale is a tuple. dtype: type (class-level attribute) the associated data type / domain type
class Albers(GeoScale): """A geographical scale which is an alias for a conic equal area projection. The Albers projection is a conic equal area map. It does not preserve scale or shape, though it is recommended for chloropleths since it preserves the relative areas of geographic features. Default values are US-centric. Attributes ---------- scale_factor: float (default: 250) Specifies the scale value for the projection rotate: tuple (default: (96, 0)) Degree of rotation in each axis. parallels: tuple (default: (29.5, 45.5)) Sets the two parallels for the conic projection. center: tuple (default: (0, 60)) Specifies the longitude and latitude where the map is centered. precision: float (default: 0.1) Specifies the threshold for the projections adaptive resampling to the specified value in pixels. rtype: (Number, Number) (class-level attribute) This attribute should not be modified. The range type of a geo scale is a tuple. dtype: type (class-level attribute) the associated data type / domain type """ scale_factor = Float(250).tag(sync=True) rotate = Tuple((96, 0)).tag(sync=True) center = Tuple((0, 60)).tag(sync=True) parallels = Tuple((29.5, 45.5)).tag(sync=True) precision = Float(0.1).tag(sync=True) rtype = '(Number, Number)' dtype = np.number _view_name = Unicode('Albers').tag(sync=True) _model_name = Unicode('AlbersModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
32,125
bqplot.scales
AlbersUSA
A composite projection of four Albers projections meant specifically for the United States. Attributes ---------- scale_factor: float (default: 1200) Specifies the scale value for the projection translate: tuple (default: (600, 490)) rtype: (Number, Number) (class-level attribute) This attribute should not be modified. The range type of a geo scale is a tuple. dtype: type (class-level attribute) the associated data type / domain type
class AlbersUSA(GeoScale): """A composite projection of four Albers projections meant specifically for the United States. Attributes ---------- scale_factor: float (default: 1200) Specifies the scale value for the projection translate: tuple (default: (600, 490)) rtype: (Number, Number) (class-level attribute) This attribute should not be modified. The range type of a geo scale is a tuple. dtype: type (class-level attribute) the associated data type / domain type """ scale_factor = Float(1200).tag(sync=True) translate = Tuple((600, 490)).tag(sync=True) rtype = '(Number, Number)' dtype = np.number _view_name = Unicode('AlbersUSA').tag(sync=True) _model_name = Unicode('AlbersUSAModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
32,182
traittypes.traittypes
Array
A numpy array trait type.
class Array(SciType): """A numpy array trait type.""" info_text = 'a numpy array' dtype = None def validate(self, obj, value): if value is None and not self.allow_none: self.error(obj, value) if value is None or value is Undefined: return super(Array, self).validate(obj, value) try: r = np.asarray(value, dtype=self.dtype) if isinstance(value, np.ndarray) and r is not value: warnings.warn( 'Given trait value dtype "%s" does not match required type "%s". ' 'A coerced copy has been created.' % ( np.dtype(value.dtype).name, np.dtype(self.dtype).name)) value = r except (ValueError, TypeError) as e: raise TraitError(e) return super(Array, self).validate(obj, value) def set(self, obj, value): new_value = self._validate(obj, value) old_value = obj._trait_values.get(self.name, self.default_value) obj._trait_values[self.name] = new_value if not np.array_equal(old_value, new_value): obj._notify_trait(self.name, old_value, new_value) def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): self.dtype = dtype if default_value is Empty: default_value = np.array(0, dtype=self.dtype) elif default_value is not None and default_value is not Undefined: default_value = np.asarray(default_value, dtype=self.dtype) super(Array, self).__init__(default_value=default_value, allow_none=allow_none, **kwargs) def make_dynamic_default(self): if self.default_value is None or self.default_value is Undefined: return self.default_value else: return np.copy(self.default_value)
(default_value: Any = traittypes.Empty, allow_none: bool = False, dtype=None, **kwargs)
32,184
traittypes.traittypes
__init__
null
def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): self.dtype = dtype if default_value is Empty: default_value = np.array(0, dtype=self.dtype) elif default_value is not None and default_value is not Undefined: default_value = np.asarray(default_value, dtype=self.dtype) super(Array, self).__init__(default_value=default_value, allow_none=allow_none, **kwargs)
(self, default_value=traittypes.Empty, allow_none=False, dtype=None, **kwargs)
32,200
traittypes.traittypes
make_dynamic_default
null
def make_dynamic_default(self): if self.default_value is None or self.default_value is Undefined: return self.default_value else: return np.copy(self.default_value)
(self)
32,201
traittypes.traittypes
set
null
def set(self, obj, value): new_value = self._validate(obj, value) old_value = obj._trait_values.get(self.name, self.default_value) obj._trait_values[self.name] = new_value if not np.array_equal(old_value, new_value): obj._notify_trait(self.name, old_value, new_value)
(self, obj, value)
32,205
traittypes.traittypes
valid
Register new trait validators Validators are functions that take two arguments. - The trait instance - The proposed value Validators return the (potentially modified) value, which is either assigned to the HasTraits attribute or input into the next validator. They are evaluated in the order in which they are provided to the `valid` function. Example ------- .. code:: python # Test with a shape constraint def shape(*dimensions): def validator(trait, value): if value.shape != dimensions: raise TraitError('Expected an of shape %s and got and array with shape %s' % (dimensions, value.shape)) else: return value return validator class Foo(HasTraits): bar = Array(np.identity(2)).valid(shape(2, 2)) foo = Foo() foo.bar = [1, 2] # Should raise a TraitError
def valid(self, *validators): """ Register new trait validators Validators are functions that take two arguments. - The trait instance - The proposed value Validators return the (potentially modified) value, which is either assigned to the HasTraits attribute or input into the next validator. They are evaluated in the order in which they are provided to the `valid` function. Example ------- .. code:: python # Test with a shape constraint def shape(*dimensions): def validator(trait, value): if value.shape != dimensions: raise TraitError('Expected an of shape %s and got and array with shape %s' % (dimensions, value.shape)) else: return value return validator class Foo(HasTraits): bar = Array(np.identity(2)).valid(shape(2, 2)) foo = Foo() foo.bar = [1, 2] # Should raise a TraitError """ self.validators.extend(validators) return self
(self, *validators)
32,206
traittypes.traittypes
validate
null
def validate(self, obj, value): if value is None and not self.allow_none: self.error(obj, value) if value is None or value is Undefined: return super(Array, self).validate(obj, value) try: r = np.asarray(value, dtype=self.dtype) if isinstance(value, np.ndarray) and r is not value: warnings.warn( 'Given trait value dtype "%s" does not match required type "%s". ' 'A coerced copy has been created.' % ( np.dtype(value.dtype).name, np.dtype(self.dtype).name)) value = r except (ValueError, TypeError) as e: raise TraitError(e) return super(Array, self).validate(obj, value)
(self, obj, value)
32,207
bqplot.axes
Axis
A line axis. A line axis is the visual representation of a numerical or date scale. Attributes ---------- icon: string (class-level attribute) The font-awesome icon name for this object. axis_types: dict (class-level attribute) A registry of existing axis types. orientation: {'horizontal', 'vertical'} The orientation of the axis, either vertical or horizontal side: {'bottom', 'top', 'left', 'right'} or None (default: None) The side of the axis, either bottom, top, left or right. label: string (default: '') The axis label tick_format: string or None (default: '') The tick format for the axis, for dates use d3 string formatting. scale: Scale The scale represented by the axis num_ticks: int or None (default: None) If tick_values is None, number of ticks tick_values: numpy.ndarray or None (default: None) Tick values for the axis tick_labels: dict (default: None) Override the tick labels with a dictionary of {value: label}. Entries are optional, and if not provided, the default tick labels will be used. offset: dict (default: {}) Contains a scale and a value {'scale': scale or None, 'value': value of the offset} If offset['scale'] is None, the corresponding figure scale is used instead. label_location: {'middle', 'start', 'end'} The location of the label along the axis, one of 'start', 'end' or 'middle' label_color: Color or None (default: None) The color of the axis label grid_lines: {'none', 'solid', 'dashed'} The display of the grid lines grid_color: Color or None (default: None) The color of the grid lines color: Color or None (default: None) The color of the line label_offset: string or None (default: None) Label displacement from the axis line. Units allowed are 'em', 'px' and 'ex'. Positive values are away from the figure and negative values are towards the figure with respect to the axis line. visible: bool (default: True) A visibility toggle for the axis tick_style: Dict (default: {}) Dictionary containing the CSS-style of the text for the ticks. For example: font-size of the text can be changed by passing `{'font-size': 14}` tick_rotate: int (default: 0) Degrees to rotate tick labels by.
class Axis(BaseAxis): """A line axis. A line axis is the visual representation of a numerical or date scale. Attributes ---------- icon: string (class-level attribute) The font-awesome icon name for this object. axis_types: dict (class-level attribute) A registry of existing axis types. orientation: {'horizontal', 'vertical'} The orientation of the axis, either vertical or horizontal side: {'bottom', 'top', 'left', 'right'} or None (default: None) The side of the axis, either bottom, top, left or right. label: string (default: '') The axis label tick_format: string or None (default: '') The tick format for the axis, for dates use d3 string formatting. scale: Scale The scale represented by the axis num_ticks: int or None (default: None) If tick_values is None, number of ticks tick_values: numpy.ndarray or None (default: None) Tick values for the axis tick_labels: dict (default: None) Override the tick labels with a dictionary of {value: label}. Entries are optional, and if not provided, the default tick labels will be used. offset: dict (default: {}) Contains a scale and a value {'scale': scale or None, 'value': value of the offset} If offset['scale'] is None, the corresponding figure scale is used instead. label_location: {'middle', 'start', 'end'} The location of the label along the axis, one of 'start', 'end' or 'middle' label_color: Color or None (default: None) The color of the axis label grid_lines: {'none', 'solid', 'dashed'} The display of the grid lines grid_color: Color or None (default: None) The color of the grid lines color: Color or None (default: None) The color of the line label_offset: string or None (default: None) Label displacement from the axis line. Units allowed are 'em', 'px' and 'ex'. Positive values are away from the figure and negative values are towards the figure with respect to the axis line. visible: bool (default: True) A visibility toggle for the axis tick_style: Dict (default: {}) Dictionary containing the CSS-style of the text for the ticks. For example: font-size of the text can be changed by passing `{'font-size': 14}` tick_rotate: int (default: 0) Degrees to rotate tick labels by. """ icon = 'fa-arrows' orientation = Enum(['horizontal', 'vertical'], default_value='horizontal')\ .tag(sync=True) side = Enum(['bottom', 'top', 'left', 'right'], allow_none=True, default_value=None).tag(sync=True) label = Unicode().tag(sync=True) grid_lines = Enum(['none', 'solid', 'dashed'], default_value='solid')\ .tag(sync=True) tick_format = Unicode(None, allow_none=True).tag(sync=True) scale = Instance(Scale).tag(sync=True, **widget_serialization) num_ticks = Int(default_value=None, allow_none=True).tag(sync=True) tick_values = Array(None, allow_none=True)\ .tag(sync=True, **array_serialization)\ .valid(array_dimension_bounds(1, 1)) tick_labels = Dict(None, allow_none=True).tag(sync=True) offset = Dict().tag(sync=True, **widget_serialization) label_location = Enum(['middle', 'start', 'end'], default_value='middle').tag(sync=True) label_color = Color(None, allow_none=True).tag(sync=True) grid_color = Color(None, allow_none=True).tag(sync=True) color = Color(None, allow_none=True).tag(sync=True) label_offset = Unicode(default_value=None, allow_none=True).tag(sync=True) visible = Bool(True).tag(sync=True) tick_style = Dict().tag(sync=True) tick_rotate = Int(0).tag(sync=True) _view_name = Unicode('Axis').tag(sync=True) _model_name = Unicode('AxisModel').tag(sync=True) _ipython_display_ = None # We cannot display an axis outside of a figure.
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
32,264
bqplot.marks
Bars
Bar mark. In the case of the Bars mark, scales for 'x' and 'y' MUST be provided. The scales of other data attributes are optional. In the case where another data attribute than 'x' or 'y' is provided but the corresponding scale is missing, the data attribute is ignored. Attributes ---------- icon: string (class-level attribute) font-awesome icon for that mark name: string (class-level attribute) user-friendly name of the mark color_mode: {'auto', 'group', 'element', 'no_group'} Specify how default colors are applied to bars. The 'group' mode means colors are assigned per group. If the list of colors is shorter than the number of groups, colors are reused. The 'element' mode means colors are assigned per group element. If the list of colors is shorter than the number of bars in a group, colors are reused. The 'no_group' mode means colors are assigned per bar, discarding the fact that there are groups or stacks. If the list of colors is shorter than the total number of bars, colors are reused. opacity_mode: {'auto', 'group', 'element', 'no_group'} Same as the `color_mode` attribute, but for the opacity. type: {'stacked', 'grouped'} whether 2-dimensional bar charts should appear grouped or stacked. colors: list of colors (default: ['steelblue']) list of colors for the bars. orientation: {'horizontal', 'vertical'} Specifies whether the bar chart is drawn horizontally or vertically. If a horizontal bar chart is drawn, the x data is drawn vertically. padding: float (default: 0.05) Attribute to control the spacing between the bars value is specified as a percentage of the width of the bar fill: Bool (default: True) Whether to fill the bars or not stroke: Color or None (default: None) Stroke color for the bars stroke_width: Float (default: 0.) Stroke width of the bars opacities: list of floats (default: []) Opacities for the bars. Defaults to 1 when the list is too short, or the element of the list is set to None. base: float (default: 0.0) reference value from which the bars are drawn. defaults to 0.0 align: {'center', 'left', 'right'} alignment of bars with respect to the tick value label_display: bool (default: False) whether or not to display bar data labels label_display_format: string (default: .2f) format for displaying values. label_font_style: dict CSS style for the text of each cell label_display_vertical_offset: float vertical offset value for the label display label_display_horizontal_offset: float horizontal offset value for the label display Data Attributes x: numpy.ndarray (default: []) abscissas of the data points (1d array) y: numpy.ndarray (default: []) ordinates of the values for the data points color: numpy.ndarray or None (default: None) color of the data points (1d array). Defaults to default_color when not provided or when a value is NaN Notes ----- The fields which can be passed to the default tooltip are: All the data attributes index: index of the bar being hovered on sub_index: if data is two dimensional, this is the minor index
class Bars(Mark): """Bar mark. In the case of the Bars mark, scales for 'x' and 'y' MUST be provided. The scales of other data attributes are optional. In the case where another data attribute than 'x' or 'y' is provided but the corresponding scale is missing, the data attribute is ignored. Attributes ---------- icon: string (class-level attribute) font-awesome icon for that mark name: string (class-level attribute) user-friendly name of the mark color_mode: {'auto', 'group', 'element', 'no_group'} Specify how default colors are applied to bars. The 'group' mode means colors are assigned per group. If the list of colors is shorter than the number of groups, colors are reused. The 'element' mode means colors are assigned per group element. If the list of colors is shorter than the number of bars in a group, colors are reused. The 'no_group' mode means colors are assigned per bar, discarding the fact that there are groups or stacks. If the list of colors is shorter than the total number of bars, colors are reused. opacity_mode: {'auto', 'group', 'element', 'no_group'} Same as the `color_mode` attribute, but for the opacity. type: {'stacked', 'grouped'} whether 2-dimensional bar charts should appear grouped or stacked. colors: list of colors (default: ['steelblue']) list of colors for the bars. orientation: {'horizontal', 'vertical'} Specifies whether the bar chart is drawn horizontally or vertically. If a horizontal bar chart is drawn, the x data is drawn vertically. padding: float (default: 0.05) Attribute to control the spacing between the bars value is specified as a percentage of the width of the bar fill: Bool (default: True) Whether to fill the bars or not stroke: Color or None (default: None) Stroke color for the bars stroke_width: Float (default: 0.) Stroke width of the bars opacities: list of floats (default: []) Opacities for the bars. Defaults to 1 when the list is too short, or the element of the list is set to None. base: float (default: 0.0) reference value from which the bars are drawn. defaults to 0.0 align: {'center', 'left', 'right'} alignment of bars with respect to the tick value label_display: bool (default: False) whether or not to display bar data labels label_display_format: string (default: .2f) format for displaying values. label_font_style: dict CSS style for the text of each cell label_display_vertical_offset: float vertical offset value for the label display label_display_horizontal_offset: float horizontal offset value for the label display Data Attributes x: numpy.ndarray (default: []) abscissas of the data points (1d array) y: numpy.ndarray (default: []) ordinates of the values for the data points color: numpy.ndarray or None (default: None) color of the data points (1d array). Defaults to default_color when not provided or when a value is NaN Notes ----- The fields which can be passed to the default tooltip are: All the data attributes index: index of the bar being hovered on sub_index: if data is two dimensional, this is the minor index """ # Mark decoration icon = 'fa-bar-chart' name = 'Bar chart' # Scaled attributes x = Array([]).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) y = Array([]).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_dimension_bounds(1, 2), array_supported_kinds()) color = Array(None, allow_none=True)\ .tag(sync=True, scaled=True, rtype='Color', atype='bqplot.ColorAxis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) # Bar text labels attributes -- add default values. # Add bool for displaying a label or not. Add d3 formatting in docstring label_display = Bool(default_value=False).tag(sync=True) label_display_format = Unicode(default_value=".2f", allow_none=False).tag(sync=True) label_font_style = Dict().tag(sync=True) label_display_vertical_offset = Float(default_value=0.0, allow_none=False).tag(sync=True) label_display_horizontal_offset = Float(default_value=0.0, allow_none=False).tag(sync=True) # Other attributes scales_metadata = Dict({ 'x': {'orientation': 'horizontal', 'dimension': 'x'}, 'y': {'orientation': 'vertical', 'dimension': 'y'}, 'color': {'dimension': 'color'} }).tag(sync=True) color_mode = Enum(['auto', 'group', 'element', 'no_group'], default_value='auto')\ .tag(sync=True) opacity_mode = Enum(['auto', 'group', 'element', 'no_group'], default_value='auto')\ .tag(sync=True) type = Enum(['stacked', 'grouped'], default_value='stacked')\ .tag(sync=True, display_name='Type') colors = List(trait=Color(default_value=None, allow_none=True), default_value=['steelblue'])\ .tag(sync=True, display_name='Colors') padding = Float(0.05).tag(sync=True) fill = Bool(True).tag(sync=True) stroke = Color(None, allow_none=True).tag(sync=True) stroke_width = Float(1.).tag(sync=True, display_name='Stroke width') base = Float().tag(sync=True) opacities = List(trait=Float(1.0, min=0, max=1, allow_none=True))\ .tag(sync=True, display_name='Opacities') align = Enum(['center', 'left', 'right'], default_value='center')\ .tag(sync=True) orientation = Enum(['vertical', 'horizontal'], default_value='vertical')\ .tag(sync=True) @validate('orientation') def _validate_orientation(self, proposal): value = proposal['value'] x_orient = "horizontal" if value == "vertical" else "vertical" self.scales_metadata = {'x': {'orientation': x_orient, 'dimension': 'x'}, 'y': {'orientation': value, 'dimension': 'y'}} return value _view_name = Unicode('Bars').tag(sync=True) _model_name = Unicode('BarsModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
32,269
bqplot.marks
__init__
null
def __init__(self, **kwargs): super(Mark, self).__init__(**kwargs) self._hover_handlers = CallbackDispatcher() self._click_handlers = CallbackDispatcher() self._legend_click_handlers = CallbackDispatcher() self._legend_hover_handlers = CallbackDispatcher() self._element_click_handlers = CallbackDispatcher() self._bg_click_handlers = CallbackDispatcher() self._name_to_handler = { 'hover': self._hover_handlers, 'click': self._click_handlers, 'legend_click': self._legend_click_handlers, 'legend_hover': self._legend_hover_handlers, 'element_click': self._element_click_handlers, 'background_click': self._bg_click_handlers } self.on_msg(self._handle_custom_msgs)
(self, **kwargs)
32,277
bqplot.marks
_get_dimension_scales
Return the list of scales corresponding to a given dimension. The preserve_domain optional argument specifies whether one should filter out the scales for which preserve_domain is set to True.
def _get_dimension_scales(self, dimension, preserve_domain=False): """ Return the list of scales corresponding to a given dimension. The preserve_domain optional argument specifies whether one should filter out the scales for which preserve_domain is set to True. """ if preserve_domain: return [ self.scales[k] for k in self.scales if ( k in self.scales_metadata and self.scales_metadata[k].get('dimension') == dimension and not self.preserve_domain.get(k) ) ] else: return [ self.scales[k] for k in self.scales if ( k in self.scales_metadata and self.scales_metadata[k].get('dimension') == dimension ) ]
(self, dimension, preserve_domain=False)
32,281
bqplot.marks
_handle_custom_msgs
null
def _handle_custom_msgs(self, _, content, buffers=None): try: handler = self._name_to_handler[content['event']] except KeyError: return handler(self, content)
(self, _, content, buffers=None)
32,306
bqplot.marks
on_background_click
null
def on_background_click(self, callback, remove=False): self._bg_click_handlers.register_callback(callback, remove=remove)
(self, callback, remove=False)
32,307
bqplot.marks
on_click
null
def on_click(self, callback, remove=False): self._click_handlers.register_callback(callback, remove=remove)
(self, callback, remove=False)
32,308
bqplot.marks
on_element_click
null
def on_element_click(self, callback, remove=False): self._element_click_handlers.register_callback(callback, remove=remove)
(self, callback, remove=False)
32,309
bqplot.marks
on_hover
null
def on_hover(self, callback, remove=False): self._hover_handlers.register_callback(callback, remove=remove)
(self, callback, remove=False)
32,310
bqplot.marks
on_legend_click
null
def on_legend_click(self, callback, remove=False): self._legend_click_handlers.register_callback(callback, remove=remove)
(self, callback, remove=False)
32,311
bqplot.marks
on_legend_hover
null
def on_legend_hover(self, callback, remove=False): self._legend_hover_handlers.register_callback(callback, remove=remove)
(self, callback, remove=False)
32,329
bqplot.axes
BaseAxis
null
class BaseAxis(Widget): axis_types = {} _view_module = Unicode('bqplot').tag(sync=True) _model_module = Unicode('bqplot').tag(sync=True) _view_module_version = Unicode(__frontend_version__).tag(sync=True) _model_module_version = Unicode(__frontend_version__).tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
32,386
bqplot.marks
Bins
Backend histogram mark. A `Bars` instance that bins sample data. It is very similar in purpose to the `Hist` mark, the difference being that the binning is done in the backend (python), which avoids large amounts of data being shipped back and forth to the frontend. It should therefore be preferred for large data. The binning method is the numpy `histogram` method. The following documentation is in part taken from the numpy documentation. Attributes ---------- icon: string (class-level attribute) font-awesome icon for that mark name: string (class-level attribute) user-friendly name of the mark bins: nonnegative int (default: 10) or {'auto', 'fd', 'doane', 'scott', 'rice', 'sturges', 'sqrt'} If `bins` is an int, it defines the number of equal-width bins in the given range (10, by default). If `bins` is a string (method name), `histogram` will use the method chosen to calculate the optimal bin width and consequently the number of bins (see `Notes` for more detail on the estimators) from the data that falls within the requested range. density : bool (default: `False`) If `False`, the height of each bin is the number of samples in it. If `True`, the height of each bin is the value of the probability *density* function at the bin, normalized such that the *integral* over the range is 1. Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability *mass* function. min : float (default: None) The lower range of the bins. If not provided, lower range is simply `x.min()`. max : float (default: None) The upper range of the bins. If not provided, lower range is simply `x.max()`. Data Attributes sample: numpy.ndarray (default: []) sample of which the histogram must be computed. Notes ----- The fields which can be passed to the default tooltip are: All the `Bars` data attributes (`x`, `y`, `color`) index: index of the bin
class Bins(Bars): """Backend histogram mark. A `Bars` instance that bins sample data. It is very similar in purpose to the `Hist` mark, the difference being that the binning is done in the backend (python), which avoids large amounts of data being shipped back and forth to the frontend. It should therefore be preferred for large data. The binning method is the numpy `histogram` method. The following documentation is in part taken from the numpy documentation. Attributes ---------- icon: string (class-level attribute) font-awesome icon for that mark name: string (class-level attribute) user-friendly name of the mark bins: nonnegative int (default: 10) or {'auto', 'fd', 'doane', 'scott', 'rice', 'sturges', 'sqrt'} If `bins` is an int, it defines the number of equal-width bins in the given range (10, by default). If `bins` is a string (method name), `histogram` will use the method chosen to calculate the optimal bin width and consequently the number of bins (see `Notes` for more detail on the estimators) from the data that falls within the requested range. density : bool (default: `False`) If `False`, the height of each bin is the number of samples in it. If `True`, the height of each bin is the value of the probability *density* function at the bin, normalized such that the *integral* over the range is 1. Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability *mass* function. min : float (default: None) The lower range of the bins. If not provided, lower range is simply `x.min()`. max : float (default: None) The upper range of the bins. If not provided, lower range is simply `x.max()`. Data Attributes sample: numpy.ndarray (default: []) sample of which the histogram must be computed. Notes ----- The fields which can be passed to the default tooltip are: All the `Bars` data attributes (`x`, `y`, `color`) index: index of the bin """ # Mark decoration icon = 'fa-signal' name = 'Backend Histogram' # Scaled Attributes sample = Array([]).tag( sync=False, display_name='Sample', rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) # Binning options min = Float(None, allow_none=True).tag(sync=True) max = Float(None, allow_none=True).tag(sync=True) density = Bool().tag(sync=True) bins = (Int(10) | List() | Enum(['auto', 'fd', 'doane', 'scott', 'rice', 'sturges', 'sqrt']))\ .tag(sync=True, display_name='Number of bins') def __init__(self, **kwargs): ''' Sets listeners on the data and the binning parameters. Adjusts `Bars` defaults to suit a histogram better. ''' self.observe(self.bin_data, names=['sample', 'bins', 'density', 'min', 'max']) # One unique color by default kwargs.setdefault('colors', [CATEGORY10[0]]) # No spacing between bars kwargs.setdefault('padding', 0.) super(Bins, self).__init__(**kwargs) def bin_data(self, *args): ''' Performs the binning of `sample` data, and draws the corresponding bars ''' # Get range _min = self.sample.min() if self.min is None else self.min _max = self.sample.max() if self.max is None else self.max _range = (min(_min, _max), max(_min, _max)) # Bin the samples counts, bin_edges = histogram(self.sample, bins=self.bins, range=_range, density=self.density) midpoints = (bin_edges[:-1] + bin_edges[1:]) / 2 # Redraw the underlying Bars with self.hold_sync(): self.x, self.y = midpoints, counts
(**kwargs)
32,391
bqplot.marks
__init__
Sets listeners on the data and the binning parameters. Adjusts `Bars` defaults to suit a histogram better.
def __init__(self, **kwargs): ''' Sets listeners on the data and the binning parameters. Adjusts `Bars` defaults to suit a histogram better. ''' self.observe(self.bin_data, names=['sample', 'bins', 'density', 'min', 'max']) # One unique color by default kwargs.setdefault('colors', [CATEGORY10[0]]) # No spacing between bars kwargs.setdefault('padding', 0.) super(Bins, self).__init__(**kwargs)
(self, **kwargs)
32,418
bqplot.marks
bin_data
Performs the binning of `sample` data, and draws the corresponding bars
def bin_data(self, *args): ''' Performs the binning of `sample` data, and draws the corresponding bars ''' # Get range _min = self.sample.min() if self.min is None else self.min _max = self.sample.max() if self.max is None else self.max _range = (min(_min, _max), max(_min, _max)) # Bin the samples counts, bin_edges = histogram(self.sample, bins=self.bins, range=_range, density=self.density) midpoints = (bin_edges[:-1] + bin_edges[1:]) / 2 # Redraw the underlying Bars with self.hold_sync(): self.x, self.y = midpoints, counts
(self, *args)
32,476
bqplot.marks
Boxplot
Boxplot marks. Attributes ---------- stroke: Color or None stroke color of the marker color: Color fill color of the box opacities: list of floats (default: []) Opacities for the markers of the boxplot. Defaults to 1 when the list is too short, or the element of the list is set to None. outlier-color: color color for the outlier box_width: int (default: None) width of the box in pixels. The minimum value is 5. If set to None, box_with is auto calculated auto_detect_outliers: bool (default: True) Flag to toggle outlier auto-detection Data Attributes x: numpy.ndarray (default: []) abscissas of the data points (1d array) y: numpy.ndarray (default: [[]]) Sample data points (2d array)
class Boxplot(Mark): """Boxplot marks. Attributes ---------- stroke: Color or None stroke color of the marker color: Color fill color of the box opacities: list of floats (default: []) Opacities for the markers of the boxplot. Defaults to 1 when the list is too short, or the element of the list is set to None. outlier-color: color color for the outlier box_width: int (default: None) width of the box in pixels. The minimum value is 5. If set to None, box_with is auto calculated auto_detect_outliers: bool (default: True) Flag to toggle outlier auto-detection Data Attributes x: numpy.ndarray (default: []) abscissas of the data points (1d array) y: numpy.ndarray (default: [[]]) Sample data points (2d array) """ # Mark decoration icon = 'fa-birthday-cake' name = 'Boxplot chart' # Scaled attributes x = Array([]).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) # Second dimension must contain OHLC data, otherwise the behavior # is undefined. y = Array([[]]).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_dimension_bounds(1, 2), array_supported_kinds()) # Other attributes scales_metadata = Dict({ 'x': {'orientation': 'horizontal', 'dimension': 'x'}, 'y': {'orientation': 'vertical', 'dimension': 'y'} }).tag(sync=True) stroke = Color(None, allow_none=True)\ .tag(sync=True, display_name='Stroke color') box_fill_color = Color('steelblue')\ .tag(sync=True, display_name='Fill color for the box') outlier_fill_color = Color('gray').tag(sync=True, display_name='Outlier fill color') opacities = List(trait=Float(1.0, min=0, max=1, allow_none=True))\ .tag(sync=True, display_name='Opacities') box_width = Int(None, min=5, allow_none=True).tag(sync=True, display_name='Box Width') auto_detect_outliers = Bool(True).tag(sync=True, display_name='Auto-detect Outliers') _view_name = Unicode('Boxplot').tag(sync=True) _model_name = Unicode('BoxplotModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
32,593
bqplot.axes
ColorAxis
A colorbar axis. A color axis is the visual representation of a color scale. Attributes ---------- scale: ColorScale The scale represented by the axis
class ColorAxis(Axis): """A colorbar axis. A color axis is the visual representation of a color scale. Attributes ---------- scale: ColorScale The scale represented by the axis """ orientation = Enum(['horizontal', 'vertical'], default_value='horizontal').tag(sync=True) side = Enum(['bottom', 'top', 'left', 'right'], default_value='bottom').tag(sync=True) label = Unicode().tag(sync=True) scale = Instance(ColorScale).tag(sync=True, **widget_serialization) _view_name = Unicode('ColorAxis').tag(sync=True) _model_name = Unicode('ColorAxisModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
32,650
bqplot.scales
ColorScale
A color scale. A mapping from numbers to colors. The relation is affine by part. Attributes ---------- scale_type: {'linear'} scale type colors: list of colors (default: []) list of colors min: float or None (default: None) if not None, min is the minimal value of the domain max: float or None (default: None) if not None, max is the maximal value of the domain mid: float or None (default: None) if not None, mid is the value corresponding to the mid color. scheme: string (default: 'RdYlGn') Colorbrewer color scheme of the color scale. extrapolation: {'constant', 'linear'} (default: 'constant') How to extrapolate values outside the [min, max] domain. rtype: string (class-level attribute) The range type of a color scale is 'Color'. This should not be modified. dtype: type (class-level attribute) the associated data type / domain type
class ColorScale(Scale): """A color scale. A mapping from numbers to colors. The relation is affine by part. Attributes ---------- scale_type: {'linear'} scale type colors: list of colors (default: []) list of colors min: float or None (default: None) if not None, min is the minimal value of the domain max: float or None (default: None) if not None, max is the maximal value of the domain mid: float or None (default: None) if not None, mid is the value corresponding to the mid color. scheme: string (default: 'RdYlGn') Colorbrewer color scheme of the color scale. extrapolation: {'constant', 'linear'} (default: 'constant') How to extrapolate values outside the [min, max] domain. rtype: string (class-level attribute) The range type of a color scale is 'Color'. This should not be modified. dtype: type (class-level attribute) the associated data type / domain type """ rtype = 'Color' dtype = np.number scale_type = Enum(['linear'], default_value='linear').tag(sync=True) colors = List(trait=Color(default_value=None, allow_none=True))\ .tag(sync=True) min = Float(None, allow_none=True).tag(sync=True) max = Float(None, allow_none=True).tag(sync=True) mid = Float(None, allow_none=True).tag(sync=True) scheme = Unicode('RdYlGn').tag(sync=True) extrapolation = Enum(['constant', 'linear'], default_value='constant').tag(sync=True) _view_name = Unicode('ColorScale').tag(sync=True) _model_name = Unicode('ColorScaleModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
32,768
traittypes.traittypes
DataFrame
A pandas dataframe trait type.
class DataFrame(PandasType): """A pandas dataframe trait type.""" info_text = 'a pandas dataframe' def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): if 'klass' not in kwargs and self.klass is None: import pandas as pd kwargs['klass'] = pd.DataFrame super(DataFrame, self).__init__( default_value=default_value, allow_none=allow_none, dtype=dtype, **kwargs)
(default_value: Any = traittypes.Empty, allow_none: bool = False, dtype=None, **kwargs)
32,770
traittypes.traittypes
__init__
null
def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): if 'klass' not in kwargs and self.klass is None: import pandas as pd kwargs['klass'] = pd.DataFrame super(DataFrame, self).__init__( default_value=default_value, allow_none=allow_none, dtype=dtype, **kwargs)
(self, default_value=traittypes.Empty, allow_none=False, dtype=None, **kwargs)
32,786
traittypes.traittypes
make_dynamic_default
null
def make_dynamic_default(self): if self.default_value is None or self.default_value is Undefined: return self.default_value else: return self.default_value.copy()
(self)
32,787
traittypes.traittypes
set
null
def set(self, obj, value): new_value = self._validate(obj, value) old_value = obj._trait_values.get(self.name, self.default_value) obj._trait_values[self.name] = new_value if ((old_value is None and new_value is not None) or (old_value is Undefined and new_value is not Undefined) or not old_value.equals(new_value)): obj._notify_trait(self.name, old_value, new_value)
(self, obj, value)
32,792
traittypes.traittypes
validate
null
def validate(self, obj, value): if value is None and not self.allow_none: self.error(obj, value) if value is None or value is Undefined: return super(PandasType, self).validate(obj, value) try: value = self.klass(value) except (ValueError, TypeError) as e: raise TraitError(e) return super(PandasType, self).validate(obj, value)
(self, obj, value)
32,793
bqplot.traits
Date
A datetime trait type. Converts the passed date into a string format that can be used to construct a JavaScript datetime.
class Date(TraitType): """ A datetime trait type. Converts the passed date into a string format that can be used to construct a JavaScript datetime. """ def validate(self, obj, value): try: if isinstance(value, dt.datetime): return value if isinstance(value, dt.date): return dt.datetime(value.year, value.month, value.day) if np.issubdtype(np.dtype(value), np.datetime64): # TODO: Fix this. Right now, we have to limit the precision # of time to microseconds because np.datetime64.astype(datetime) # returns date values only for precision <= 'us' value_truncated = np.datetime64(value, 'us') return value_truncated.astype(dt.datetime) except Exception: self.error(obj, value) self.error(obj, value) def __init__(self, default_value=dt.datetime.today(), **kwargs): super(Date, self).__init__(default_value=default_value, **kwargs) self.tag(**date_serialization)
(default_value: Any = datetime.datetime(2024, 5, 12, 8, 41, 20, 704540), **kwargs)
32,795
bqplot.traits
__init__
null
def __init__(self, default_value=dt.datetime.today(), **kwargs): super(Date, self).__init__(default_value=default_value, **kwargs) self.tag(**date_serialization)
(self, default_value=datetime.datetime(2024, 5, 12, 8, 41, 20, 704540), **kwargs)
32,815
bqplot.traits
validate
null
def validate(self, obj, value): try: if isinstance(value, dt.datetime): return value if isinstance(value, dt.date): return dt.datetime(value.year, value.month, value.day) if np.issubdtype(np.dtype(value), np.datetime64): # TODO: Fix this. Right now, we have to limit the precision # of time to microseconds because np.datetime64.astype(datetime) # returns date values only for precision <= 'us' value_truncated = np.datetime64(value, 'us') return value_truncated.astype(dt.datetime) except Exception: self.error(obj, value) self.error(obj, value)
(self, obj, value)
32,816
bqplot.scales
DateColorScale
A date color scale. A mapping from dates to a numerical domain. Attributes ---------- min: Date or None (default: None) if not None, min is the minimal value of the domain max: Date or None (default: None) if not None, max is the maximal value of the domain mid: Date or None (default: None) if not None, mid is the value corresponding to the mid color. rtype: string (class-level attribute) This attribute should not be modified by the user. The range type of a color scale is 'Color'. dtype: type (class-level attribute) the associated data type / domain type
class DateColorScale(ColorScale): """A date color scale. A mapping from dates to a numerical domain. Attributes ---------- min: Date or None (default: None) if not None, min is the minimal value of the domain max: Date or None (default: None) if not None, max is the maximal value of the domain mid: Date or None (default: None) if not None, mid is the value corresponding to the mid color. rtype: string (class-level attribute) This attribute should not be modified by the user. The range type of a color scale is 'Color'. dtype: type (class-level attribute) the associated data type / domain type """ dtype = np.datetime64 domain_class = Type(Date) min = Date(default_value=None, allow_none=True).tag(sync=True) mid = Date(default_value=None, allow_none=True).tag(sync=True) max = Date(default_value=None, allow_none=True).tag(sync=True) _view_name = Unicode('DateColorScale').tag(sync=True) _model_name = Unicode('DateColorScaleModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
32,873
bqplot.scales
DateScale
A date scale, with customizable formatting. An affine mapping from dates to a numerical range. Attributes ---------- min: Date or None (default: None) if not None, min is the minimal value of the domain max: Date (default: None) if not None, max is the maximal value of the domain domain_class: type (default: Date) traitlet type used to validate values in of the domain of the scale. rtype: string (class-level attribute) This attribute should not be modified by the user. The range type of a linear scale is numerical. dtype: type (class-level attribute) the associated data type / domain type
class DateScale(Scale): """A date scale, with customizable formatting. An affine mapping from dates to a numerical range. Attributes ---------- min: Date or None (default: None) if not None, min is the minimal value of the domain max: Date (default: None) if not None, max is the maximal value of the domain domain_class: type (default: Date) traitlet type used to validate values in of the domain of the scale. rtype: string (class-level attribute) This attribute should not be modified by the user. The range type of a linear scale is numerical. dtype: type (class-level attribute) the associated data type / domain type """ rtype = 'Number' dtype = np.datetime64 domain_class = Type(Date) min = Date(default_value=None, allow_none=True).tag(sync=True) max = Date(default_value=None, allow_none=True).tag(sync=True) _view_name = Unicode('DateScale').tag(sync=True) _model_name = Unicode('DateScaleModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
32,987
bqplot.scales
EquiRectangular
An elementary projection that uses the identity function. The projection is neither equal-area nor conformal. Attributes ---------- scale_factor: float (default: 145) Specifies the scale value for the projection center: tuple (default: (0, 60)) Specifies the longitude and latitude where the map is centered.
class EquiRectangular(GeoScale): """An elementary projection that uses the identity function. The projection is neither equal-area nor conformal. Attributes ---------- scale_factor: float (default: 145) Specifies the scale value for the projection center: tuple (default: (0, 60)) Specifies the longitude and latitude where the map is centered. """ scale_factor = Float(145.0).tag(sync=True) center = Tuple((0, 60)).tag(sync=True) rtype = '(Number, Number)' dtype = np.number _view_name = Unicode('EquiRectangular').tag(sync=True) _model_name = Unicode('EquiRectangularModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
33,044
bqplot.figure
Figure
Main canvas for drawing a chart. The Figure object holds the list of Marks and Axes. It also holds an optional Interaction object that is responsible for figure-level mouse interactions, the "interaction layer". Besides, the Figure object has two reference scales, for positioning items in an absolute fashion in the figure canvas. Attributes ---------- title: string (default: '') title of the figure axes: List of Axes (default: []) list containing the instances of the axes for the figure marks: List of Marks (default: []) list containing the marks which are to be appended to the figure interaction: Interaction or None (default: None) optional interaction layer for the figure scale_x: Scale Scale representing the x values of the figure scale_y: Scale Scale representing the y values of the figure padding_x: Float (default: 0.0) Padding to be applied in the horizontal direction of the figure around the data points, proportion of the horizontal length padding_y: Float (default: 0.025) Padding to be applied in the vertical direction of the figure around the data points, proportion of the vertical length legend_location: {'top-right', 'top', 'top-left', 'left', 'bottom-left', 'bottom', 'bottom-right', 'right'} location of the legend relative to the center of the figure background_style: Dict (default: {}) CSS style to be applied to the background of the figure legend_style: Dict (default: {}) CSS style to be applied to the SVG legend e.g, {'fill': 'white'} legend_text: Dict (default: {}) CSS style to be applied to the legend text e.g., {'font-size': 20} title_style: Dict (default: {}) CSS style to be applied to the title of the figure animation_duration: nonnegative int (default: 0) Duration of transition on change of data attributes, in milliseconds. pixel_ratio: Pixel ratio of the WebGL canvas (2 on retina screens). Set to 1 for better performance, but less crisp edges. If set to None it will use the browser's window.devicePixelRatio. Layout Attributes fig_margin: dict (default: {top=60, bottom=60, left=60, right=60}) Dictionary containing the top, bottom, left and right margins. The user is responsible for making sure that the width and height are greater than the sum of the margins. min_aspect_ratio: float minimum width / height ratio of the figure max_aspect_ratio: float maximum width / height ratio of the figure Methods ------- save_png: Saves the figure as a PNG file save_svg: Saves the figure as an SVG file Note ---- The aspect ratios stand for width / height ratios. - If the available space is within bounds in terms of min and max aspect ratio, we use the entire available space. - If the available space is too oblong horizontally, we use the client height and the width that corresponds max_aspect_ratio (maximize width under the constraints). - If the available space is too oblong vertically, we use the client width and the height that corresponds to min_aspect_ratio (maximize height under the constraint). This corresponds to maximizing the area under the constraints. Default min and max aspect ratio are both equal to 16 / 9.
class Figure(DOMWidget): """Main canvas for drawing a chart. The Figure object holds the list of Marks and Axes. It also holds an optional Interaction object that is responsible for figure-level mouse interactions, the "interaction layer". Besides, the Figure object has two reference scales, for positioning items in an absolute fashion in the figure canvas. Attributes ---------- title: string (default: '') title of the figure axes: List of Axes (default: []) list containing the instances of the axes for the figure marks: List of Marks (default: []) list containing the marks which are to be appended to the figure interaction: Interaction or None (default: None) optional interaction layer for the figure scale_x: Scale Scale representing the x values of the figure scale_y: Scale Scale representing the y values of the figure padding_x: Float (default: 0.0) Padding to be applied in the horizontal direction of the figure around the data points, proportion of the horizontal length padding_y: Float (default: 0.025) Padding to be applied in the vertical direction of the figure around the data points, proportion of the vertical length legend_location: {'top-right', 'top', 'top-left', 'left', 'bottom-left', 'bottom', 'bottom-right', 'right'} location of the legend relative to the center of the figure background_style: Dict (default: {}) CSS style to be applied to the background of the figure legend_style: Dict (default: {}) CSS style to be applied to the SVG legend e.g, {'fill': 'white'} legend_text: Dict (default: {}) CSS style to be applied to the legend text e.g., {'font-size': 20} title_style: Dict (default: {}) CSS style to be applied to the title of the figure animation_duration: nonnegative int (default: 0) Duration of transition on change of data attributes, in milliseconds. pixel_ratio: Pixel ratio of the WebGL canvas (2 on retina screens). Set to 1 for better performance, but less crisp edges. If set to None it will use the browser's window.devicePixelRatio. Layout Attributes fig_margin: dict (default: {top=60, bottom=60, left=60, right=60}) Dictionary containing the top, bottom, left and right margins. The user is responsible for making sure that the width and height are greater than the sum of the margins. min_aspect_ratio: float minimum width / height ratio of the figure max_aspect_ratio: float maximum width / height ratio of the figure Methods ------- save_png: Saves the figure as a PNG file save_svg: Saves the figure as an SVG file Note ---- The aspect ratios stand for width / height ratios. - If the available space is within bounds in terms of min and max aspect ratio, we use the entire available space. - If the available space is too oblong horizontally, we use the client height and the width that corresponds max_aspect_ratio (maximize width under the constraints). - If the available space is too oblong vertically, we use the client width and the height that corresponds to min_aspect_ratio (maximize height under the constraint). This corresponds to maximizing the area under the constraints. Default min and max aspect ratio are both equal to 16 / 9. """ title = Unicode().tag(sync=True, display_name='Title') axes = List(Instance(Axis)).tag(sync=True, **widget_serialization) marks = List(Instance(Mark)).tag(sync=True, **widget_serialization) interaction = Instance(Interaction, default_value=None, allow_none=True).tag(sync=True, **widget_serialization) scale_x = Instance(Scale).tag(sync=True, **widget_serialization) scale_y = Instance(Scale).tag(sync=True, **widget_serialization) title_style = Dict(value_trait=Unicode()).tag(sync=True) background_style = Dict().tag(sync=True) legend_style = Dict().tag(sync=True) legend_text = Dict().tag(sync=True) theme = Enum(['classic', 'gg'], default_value='classic').tag(sync=True) min_aspect_ratio = Float(0.01).tag(sync=True) max_aspect_ratio = Float(100).tag(sync=True) pixel_ratio = Float(None, allow_none=True).tag(sync=True) fig_margin = Dict(dict(top=60, bottom=60, left=60, right=60))\ .tag(sync=True) padding_x = Float(0.0, min=0.0, max=1.0).tag(sync=True) padding_y = Float(0.025, min=0.0, max=1.0).tag(sync=True) legend_location = Enum(['top-right', 'top', 'top-left', 'left', 'bottom-left', 'bottom', 'bottom-right', 'right'], default_value='top-right')\ .tag(sync=True, display_name='Legend position') animation_duration = Int().tag(sync=True, display_name='Animation duration') def __init__(self, **kwargs): super(Figure, self).__init__(**kwargs) self._upload_png_callback = None self.on_msg(self._handle_custom_msgs) @default('scale_x') def _default_scale_x(self): return LinearScale(min=0, max=1, allow_padding=False) @default('scale_y') def _default_scale_y(self): return LinearScale(min=0, max=1, allow_padding=False) def save_png(self, filename='bqplot.png', scale=None): ''' Saves the Figure as a PNG file Parameters ---------- filename: str (default: 'bqplot.png') name of the saved file scale: float (default: None) Scale up the png resolution when scale > 1, when not given base this on the screen pixel ratio. ''' self.send({'type': 'save_png', 'filename': filename, 'scale': scale}) def save_svg(self, filename='bqplot.svg'): ''' Saves the Figure as an SVG file Parameters ---------- filename: str (default: 'bqplot.svg') name of the saved file ''' self.send({"type": "save_svg", "filename": filename}) def get_png_data(self, callback, scale=None): ''' Gets the Figure as a PNG memory view Parameters ---------- callback: callable Called with the PNG data as the only positional argument. scale: float (default: None) Scale up the png resolution when scale > 1, when not given base this on the screen pixel ratio. ''' if self._upload_png_callback: raise Exception('get_png_data already in progress') self._upload_png_callback = callback self.send({'type': 'upload_png', 'scale': scale}) @validate('min_aspect_ratio', 'max_aspect_ratio') def _validate_aspect_ratio(self, proposal): value = proposal['value'] if proposal['trait'].name == 'min_aspect_ratio' and \ value > self.max_aspect_ratio: raise TraitError('setting min_aspect_ratio > max_aspect_ratio') if proposal['trait'].name == 'max_aspect_ratio' and \ value < self.min_aspect_ratio: raise TraitError('setting max_aspect_ratio < min_aspect_ratio') return value def _handle_custom_msgs(self, _, content, buffers=None): if content.get('event') == 'upload_png': try: self._upload_png_callback(buffers[0]) finally: self._upload_png_callback = None _view_name = Unicode('Figure').tag(sync=True) _model_name = Unicode('FigureModel').tag(sync=True) _view_module = Unicode('bqplot').tag(sync=True) _model_module = Unicode('bqplot').tag(sync=True) _view_module_version = Unicode(__frontend_version__).tag(sync=True) _model_module_version = Unicode(__frontend_version__).tag(sync=True)
(**kwargs)
33,049
bqplot.figure
__init__
null
def __init__(self, **kwargs): super(Figure, self).__init__(**kwargs) self._upload_png_callback = None self.on_msg(self._handle_custom_msgs)
(self, **kwargs)
33,060
bqplot.figure
_handle_custom_msgs
null
def _handle_custom_msgs(self, _, content, buffers=None): if content.get('event') == 'upload_png': try: self._upload_png_callback(buffers[0]) finally: self._upload_png_callback = None
(self, _, content, buffers=None)
33,080
bqplot.figure
get_png_data
Gets the Figure as a PNG memory view Parameters ---------- callback: callable Called with the PNG data as the only positional argument. scale: float (default: None) Scale up the png resolution when scale > 1, when not given base this on the screen pixel ratio.
def get_png_data(self, callback, scale=None): ''' Gets the Figure as a PNG memory view Parameters ---------- callback: callable Called with the PNG data as the only positional argument. scale: float (default: None) Scale up the png resolution when scale > 1, when not given base this on the screen pixel ratio. ''' if self._upload_png_callback: raise Exception('get_png_data already in progress') self._upload_png_callback = callback self.send({'type': 'upload_png', 'scale': scale})
(self, callback, scale=None)
33,094
bqplot.figure
save_png
Saves the Figure as a PNG file Parameters ---------- filename: str (default: 'bqplot.png') name of the saved file scale: float (default: None) Scale up the png resolution when scale > 1, when not given base this on the screen pixel ratio.
def save_png(self, filename='bqplot.png', scale=None): ''' Saves the Figure as a PNG file Parameters ---------- filename: str (default: 'bqplot.png') name of the saved file scale: float (default: None) Scale up the png resolution when scale > 1, when not given base this on the screen pixel ratio. ''' self.send({'type': 'save_png', 'filename': filename, 'scale': scale})
(self, filename='bqplot.png', scale=None)
33,095
bqplot.figure
save_svg
Saves the Figure as an SVG file Parameters ---------- filename: str (default: 'bqplot.svg') name of the saved file
def save_svg(self, filename='bqplot.svg'): ''' Saves the Figure as an SVG file Parameters ---------- filename: str (default: 'bqplot.svg') name of the saved file ''' self.send({"type": "save_svg", "filename": filename})
(self, filename='bqplot.svg')
33,109
bqplot.marks
FlexLine
Flexible Lines mark. In the case of the FlexLines mark, scales for 'x' and 'y' MUST be provided. Scales for the color and width data attributes are optional. In the case where another data attribute than 'x' or 'y' is provided but the corresponding scale is missing, the data attribute is ignored. Attributes ---------- name: string (class-level attributes) user-friendly name of the mark colors: list of colors (default: CATEGORY10) List of colors for the Lines stroke_width: float (default: 1.5) Default stroke width of the Lines Data Attributes x: numpy.ndarray (default: []) abscissas of the data points (1d array) y: numpy.ndarray (default: []) ordinates of the data points (1d array) color: numpy.ndarray or None (default: None) Array controlling the color of the data points width: numpy.ndarray or None (default: None) Array controlling the widths of the Lines.
class FlexLine(Mark): """Flexible Lines mark. In the case of the FlexLines mark, scales for 'x' and 'y' MUST be provided. Scales for the color and width data attributes are optional. In the case where another data attribute than 'x' or 'y' is provided but the corresponding scale is missing, the data attribute is ignored. Attributes ---------- name: string (class-level attributes) user-friendly name of the mark colors: list of colors (default: CATEGORY10) List of colors for the Lines stroke_width: float (default: 1.5) Default stroke width of the Lines Data Attributes x: numpy.ndarray (default: []) abscissas of the data points (1d array) y: numpy.ndarray (default: []) ordinates of the data points (1d array) color: numpy.ndarray or None (default: None) Array controlling the color of the data points width: numpy.ndarray or None (default: None) Array controlling the widths of the Lines. """ # Mark decoration icon = 'fa-line-chart' name = 'Flexible lines' # Scaled attributes x = Array([]).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) y = Array([]).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) color = Array(None, allow_none=True)\ .tag(sync=True, scaled=True, rtype='Color', atype='bqplot.ColorAxis', **array_serialization).valid(array_squeeze) width = Array(None, allow_none=True)\ .tag(sync=True, scaled=True, rtype='Number', **array_serialization).valid(array_squeeze) # Other attributes scales_metadata = Dict({ 'x': {'orientation': 'horizontal', 'dimension': 'x'}, 'y': {'orientation': 'vertical', 'dimension': 'y'}, 'color': {'dimension': 'color'} }).tag(sync=True) stroke_width = Float(1.5).tag(sync=True, display_name='Stroke width') colors = List(trait=Color(default_value=None, allow_none=True), default_value=CATEGORY10).tag(sync=True) _view_name = Unicode('FlexLine').tag(sync=True) _model_name = Unicode('FlexLineModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
33,197
bqplot.scales
GeoScale
The base projection scale class for Map marks. The GeoScale represents a mapping between topographic data and a 2d visual representation.
class GeoScale(Scale): """The base projection scale class for Map marks. The GeoScale represents a mapping between topographic data and a 2d visual representation. """ _view_name = Unicode('GeoScale').tag(sync=True) _model_name = Unicode('GeoScaleModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
33,254
bqplot.scales
Gnomonic
A perspective projection which displays great circles as straight lines. The projection is neither equal-area nor conformal. Attributes ---------- scale_factor: float (default: 145) Specifies the scale value for the projection center: tuple (default: (0, 60)) Specifies the longitude and latitude where the map is centered. precision: float (default: 0.1) Specifies the threshold for the projections adaptive resampling to the specified value in pixels. clip_angle: float (default: 89.999) Specifies the clipping circle radius to the specified angle in degrees.
class Gnomonic(GeoScale): """A perspective projection which displays great circles as straight lines. The projection is neither equal-area nor conformal. Attributes ---------- scale_factor: float (default: 145) Specifies the scale value for the projection center: tuple (default: (0, 60)) Specifies the longitude and latitude where the map is centered. precision: float (default: 0.1) Specifies the threshold for the projections adaptive resampling to the specified value in pixels. clip_angle: float (default: 89.999) Specifies the clipping circle radius to the specified angle in degrees. """ scale_factor = Float(145.0).tag(sync=True) center = Tuple((0, 60)).tag(sync=True) precision = Float(0.1).tag(sync=True) clip_angle = Float(89.999, min=0.0, max=360.0).tag(sync=True) rtype = '(Number, Number)' dtype = np.number _view_name = Unicode('Gnomonic').tag(sync=True) _model_name = Unicode('GnomonicModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
33,311
bqplot.marks
Graph
Graph with nodes and links. Attributes ---------- node_data: List list of node attributes for the graph link_matrix: numpy.ndarray of shape(len(nodes), len(nodes)) link data passed as 2d matrix link_data: List list of link attributes for the graph charge: int (default: -600) charge of force layout. Will be ignored when x and y data attributes are set static: bool (default: False) whether the graph is static or not link_distance: float (default: 100) link distance in pixels between nodes. Will be ignored when x and y data attributes are set link_type: {'arc', 'line', 'slant_line'} (default: 'arc') Enum representing link type directed: bool (default: True) directed or undirected graph highlight_links: bool (default: True) highlights incoming and outgoing links when hovered on a node colors: list (default: CATEGORY10) list of node colors Data Attributes x: numpy.ndarray (default: []) abscissas of the node data points (1d array) y: numpy.ndarray (default: []) ordinates of the node data points (1d array) color: numpy.ndarray or None (default: None) color of the node data points (1d array). link_color: numpy.ndarray of shape(len(nodes), len(nodes)) link data passed as 2d matrix
class Graph(Mark): """Graph with nodes and links. Attributes ---------- node_data: List list of node attributes for the graph link_matrix: numpy.ndarray of shape(len(nodes), len(nodes)) link data passed as 2d matrix link_data: List list of link attributes for the graph charge: int (default: -600) charge of force layout. Will be ignored when x and y data attributes are set static: bool (default: False) whether the graph is static or not link_distance: float (default: 100) link distance in pixels between nodes. Will be ignored when x and y data attributes are set link_type: {'arc', 'line', 'slant_line'} (default: 'arc') Enum representing link type directed: bool (default: True) directed or undirected graph highlight_links: bool (default: True) highlights incoming and outgoing links when hovered on a node colors: list (default: CATEGORY10) list of node colors Data Attributes x: numpy.ndarray (default: []) abscissas of the node data points (1d array) y: numpy.ndarray (default: []) ordinates of the node data points (1d array) color: numpy.ndarray or None (default: None) color of the node data points (1d array). link_color: numpy.ndarray of shape(len(nodes), len(nodes)) link data passed as 2d matrix """ charge = Int(-600).tag(sync=True) static = Bool(False).tag(sync=True) link_distance = Float(100).tag(sync=True) node_data = List().tag(sync=True) link_data = List().tag(sync=True) link_matrix = Array([]).tag(sync=True, rtype='Number', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 2)) link_type = Enum(['arc', 'line', 'slant_line'], default_value='arc').tag(sync=True) directed = Bool(True).tag(sync=True) colors = List(trait=Color(default_value=None, allow_none=True), default_value=CATEGORY10).tag(sync=True, display_name='Colors') interactions = Dict({'hover': 'tooltip', 'click': 'select'}).tag(sync=True) highlight_links = Bool(True).tag(sync=True) # Scaled attributes x = Array([], allow_none=True).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_dimension_bounds(1, 1)) y = Array([], allow_none=True).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_dimension_bounds(1, 1)) color = Array(None, allow_none=True).tag(sync=True, scaled=True, rtype='Color', atype='bqplot.ColorAxis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) link_color = Array([]).tag(sync=True, rtype='Color', atype='bqplot.ColorAxis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 2)) hovered_style = Dict().tag(sync=True) unhovered_style = Dict().tag(sync=True) hovered_point = Int(None, allow_none=True).tag(sync=True) # Other attributes scales_metadata = Dict({ 'x': {'orientation': 'horizontal', 'dimension': 'x'}, 'y': {'orientation': 'vertical', 'dimension': 'y'}, 'color': {'dimension': 'color'}, 'link_color': {'dimension': 'link_color'} }).tag(sync=True) _model_name = Unicode('GraphModel').tag(sync=True) _view_name = Unicode('Graph').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
33,376
bqplot.marks
GridHeatMap
GridHeatMap mark. Alignment: The tiles can be aligned so that the data matches either the start, the end or the midpoints of the tiles. This is controlled by the align attribute. Suppose the data passed is a m-by-n matrix. If the scale for the rows is Ordinal, then alignment is by default the mid points. For a non-ordinal scale, the data cannot be aligned to the mid points of the rectangles. If it is not ordinal, then two cases arise. If the number of rows passed is m, then align attribute can be used. If the number of rows passed is m+1, then the data are the boundaries of the m rectangles. If rows and columns are not passed, and scales for them are also not passed, then ordinal scales are generated for the rows and columns. Attributes ---------- row_align: Enum(['start', 'end']) This is only valid if the number of entries in `row` exactly match the number of rows in `color` and the `row_scale` is not `OrdinalScale`. `start` aligns the row values passed to be aligned with the start of the tiles and `end` aligns the row values to the end of the tiles. column_align: Enum(['start', end']) This is only valid if the number of entries in `column` exactly match the number of columns in `color` and the `column_scale` is not `OrdinalScale`. `start` aligns the column values passed to be aligned with the start of the tiles and `end` aligns the column values to the end of the tiles. anchor_style: dict (default: {}) Controls the style for the element which serves as the anchor during selection. display_format: string (default: None) format for displaying values. If None, then values are not displayed font_style: dict CSS style for the text of each cell Data Attributes color: numpy.ndarray or None (default: None) color of the data points (2d array). The number of elements in this array correspond to the number of cells created in the heatmap. row: numpy.ndarray or None (default: None) labels for the rows of the `color` array passed. The length of this can be no more than 1 away from the number of rows in `color`. This is a scaled attribute and can be used to affect the height of the cells as the entries of `row` can indicate the start or the end points of the cells. Refer to the property `row_align`. If this property is None, then a uniformly spaced grid is generated in the row direction. column: numpy.ndarray or None (default: None) labels for the columns of the `color` array passed. The length of this can be no more than 1 away from the number of columns in `color` This is a scaled attribute and can be used to affect the width of the cells as the entries of `column` can indicate the start or the end points of the cells. Refer to the property `column_align`. If this property is None, then a uniformly spaced grid is generated in the column direction.
class GridHeatMap(Mark): """GridHeatMap mark. Alignment: The tiles can be aligned so that the data matches either the start, the end or the midpoints of the tiles. This is controlled by the align attribute. Suppose the data passed is a m-by-n matrix. If the scale for the rows is Ordinal, then alignment is by default the mid points. For a non-ordinal scale, the data cannot be aligned to the mid points of the rectangles. If it is not ordinal, then two cases arise. If the number of rows passed is m, then align attribute can be used. If the number of rows passed is m+1, then the data are the boundaries of the m rectangles. If rows and columns are not passed, and scales for them are also not passed, then ordinal scales are generated for the rows and columns. Attributes ---------- row_align: Enum(['start', 'end']) This is only valid if the number of entries in `row` exactly match the number of rows in `color` and the `row_scale` is not `OrdinalScale`. `start` aligns the row values passed to be aligned with the start of the tiles and `end` aligns the row values to the end of the tiles. column_align: Enum(['start', end']) This is only valid if the number of entries in `column` exactly match the number of columns in `color` and the `column_scale` is not `OrdinalScale`. `start` aligns the column values passed to be aligned with the start of the tiles and `end` aligns the column values to the end of the tiles. anchor_style: dict (default: {}) Controls the style for the element which serves as the anchor during selection. display_format: string (default: None) format for displaying values. If None, then values are not displayed font_style: dict CSS style for the text of each cell Data Attributes color: numpy.ndarray or None (default: None) color of the data points (2d array). The number of elements in this array correspond to the number of cells created in the heatmap. row: numpy.ndarray or None (default: None) labels for the rows of the `color` array passed. The length of this can be no more than 1 away from the number of rows in `color`. This is a scaled attribute and can be used to affect the height of the cells as the entries of `row` can indicate the start or the end points of the cells. Refer to the property `row_align`. If this property is None, then a uniformly spaced grid is generated in the row direction. column: numpy.ndarray or None (default: None) labels for the columns of the `color` array passed. The length of this can be no more than 1 away from the number of columns in `color` This is a scaled attribute and can be used to affect the width of the cells as the entries of `column` can indicate the start or the end points of the cells. Refer to the property `column_align`. If this property is None, then a uniformly spaced grid is generated in the column direction. """ # Scaled attributes row = Array(None, allow_none=True).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) column = Array(None, allow_none=True).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) color = Array(None, allow_none=True).tag(sync=True, scaled=True, rtype='Color', atype='bqplot.ColorAxis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 2)) # Other attributes scales_metadata = Dict({ 'row': {'orientation': 'vertical', 'dimension': 'y'}, 'column': {'orientation': 'horizontal', 'dimension': 'x'}, 'color': {'dimension': 'color'} }).tag(sync=True) row_align = Enum(['start', 'end'], default_value='start').tag(sync=True) column_align = Enum(['start', 'end'], default_value='start').tag(sync=True) null_color = Color('black', allow_none=True).tag(sync=True) stroke = Color('black', allow_none=True).tag(sync=True) opacity = Float(1.0, min=0.2, max=1).tag(sync=True, display_name='Opacity') anchor_style = Dict().tag(sync=True) display_format = Unicode(default_value=None, allow_none=True)\ .tag(sync=True) font_style = Dict().tag(sync=True) def __init__(self, **kwargs): # Adding scales in case they are not passed too. scales = kwargs.pop('scales', {}) if scales.get('row', None) is None: row_scale = OrdinalScale(reverse=True) scales['row'] = row_scale if scales.get('column', None) is None: column_scale = OrdinalScale() scales['column'] = column_scale kwargs['scales'] = scales super(GridHeatMap, self).__init__(**kwargs) @validate('row') def _validate_row(self, proposal): row = proposal.value if row is None: return row color = np.asarray(self.color) n_rows = color.shape[0] if len(row) != n_rows and len(row) != n_rows + 1 and len(row) != n_rows - 1: raise TraitError('row must be an array of size color.shape[0]') return row @validate('column') def _validate_column(self, proposal): column = proposal.value if column is None: return column color = np.asarray(self.color) n_columns = color.shape[1] if len(column) != n_columns and len(column) != n_columns + 1 and len(column) != n_columns - 1: raise TraitError('column must be an array of size color.shape[1]') return column _view_name = Unicode('GridHeatMap').tag(sync=True) _model_name = Unicode('GridHeatMapModel').tag(sync=True)
(**kwargs)
33,381
bqplot.marks
__init__
null
def __init__(self, **kwargs): # Adding scales in case they are not passed too. scales = kwargs.pop('scales', {}) if scales.get('row', None) is None: row_scale = OrdinalScale(reverse=True) scales['row'] = row_scale if scales.get('column', None) is None: column_scale = OrdinalScale() scales['column'] = column_scale kwargs['scales'] = scales super(GridHeatMap, self).__init__(**kwargs)
(self, **kwargs)
33,441
bqplot.marks
HeatMap
HeatMap mark. Attributes ---------- Data Attributes color: numpy.ndarray or None (default: None) color of the data points (2d array). x: numpy.ndarray or None (default: None) labels for the columns of the `color` array passed. The length of this has to be the number of columns in `color`. This is a scaled attribute. y: numpy.ndarray or None (default: None) labels for the rows of the `color` array passed. The length of this has to be the number of rows in `color`. This is a scaled attribute.
class HeatMap(Mark): """HeatMap mark. Attributes ---------- Data Attributes color: numpy.ndarray or None (default: None) color of the data points (2d array). x: numpy.ndarray or None (default: None) labels for the columns of the `color` array passed. The length of this has to be the number of columns in `color`. This is a scaled attribute. y: numpy.ndarray or None (default: None) labels for the rows of the `color` array passed. The length of this has to be the number of rows in `color`. This is a scaled attribute. """ # Scaled attributes x = Array(None, allow_none=True).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) y = Array(None, allow_none=True).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) color = Array(None, allow_none=True).tag(sync=True, scaled=True, rtype='Color', atype='bqplot.ColorAxis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(2, 2)) # Other attributes scales_metadata = Dict({ 'x': {'orientation': 'horizontal', 'dimension': 'x'}, 'y': {'orientation': 'vertical', 'dimension': 'y'}, 'color': {'dimension': 'color'} }).tag(sync=True) null_color = Color('black', allow_none=True).tag(sync=True) def __init__(self, **kwargs): data = kwargs['color'] kwargs.setdefault('x', range(data.shape[1])) kwargs.setdefault('y', range(data.shape[0])) scales = kwargs.pop('scales', {}) # Adding default x and y data if they are not passed. # Adding scales in case they are not passed too. if scales.get('x', None) is None: x_scale = LinearScale() scales['x'] = x_scale if scales.get('y', None) is None: y_scale = LinearScale() scales['y'] = y_scale kwargs['scales'] = scales super(HeatMap, self).__init__(**kwargs) _view_name = Unicode('HeatMap').tag(sync=True) _model_name = Unicode('HeatMapModel').tag(sync=True)
(**kwargs)
33,446
bqplot.marks
__init__
null
def __init__(self, **kwargs): data = kwargs['color'] kwargs.setdefault('x', range(data.shape[1])) kwargs.setdefault('y', range(data.shape[0])) scales = kwargs.pop('scales', {}) # Adding default x and y data if they are not passed. # Adding scales in case they are not passed too. if scales.get('x', None) is None: x_scale = LinearScale() scales['x'] = x_scale if scales.get('y', None) is None: y_scale = LinearScale() scales['y'] = y_scale kwargs['scales'] = scales super(HeatMap, self).__init__(**kwargs)
(self, **kwargs)
33,506
bqplot.marks
Hist
Histogram mark. In the case of the Hist mark, scales for 'sample' and 'count' MUST be provided. Attributes ---------- icon: string (class-level attribute) font-awesome icon for that mark name: string (class-level attribute) user-friendly name of the mark bins: nonnegative int (default: 10) number of bins in the histogram normalized: bool (default: False) Boolean attribute to return normalized values which sum to 1 or direct counts for the `count` attribute. The scale of `count` attribute is determined by the value of this flag. colors: list of colors (default: ['steelblue']) List of colors of the Histogram. If the list is shorter than the number of bins, the colors are reused. stroke: Color or None (default: None) Stroke color of the histogram opacities: list of floats (default: []) Opacity for the bins of the histogram. Defaults to 1 when the list is too short, or the element of the list is set to None. midpoints: list (default: []) midpoints of the bins of the histogram. It is a read-only attribute. Data Attributes sample: numpy.ndarray (default: []) sample of which the histogram must be computed. count: numpy.ndarray (read-only) number of sample points per bin. It is a read-only attribute. Notes ----- The fields which can be passed to the default tooltip are: midpoint: mid-point of the bin related to the rectangle hovered on count: number of elements in the bin hovered on bin_start: start point of the bin bin-end: end point of the bin index: index of the bin
class Hist(Mark): """Histogram mark. In the case of the Hist mark, scales for 'sample' and 'count' MUST be provided. Attributes ---------- icon: string (class-level attribute) font-awesome icon for that mark name: string (class-level attribute) user-friendly name of the mark bins: nonnegative int (default: 10) number of bins in the histogram normalized: bool (default: False) Boolean attribute to return normalized values which sum to 1 or direct counts for the `count` attribute. The scale of `count` attribute is determined by the value of this flag. colors: list of colors (default: ['steelblue']) List of colors of the Histogram. If the list is shorter than the number of bins, the colors are reused. stroke: Color or None (default: None) Stroke color of the histogram opacities: list of floats (default: []) Opacity for the bins of the histogram. Defaults to 1 when the list is too short, or the element of the list is set to None. midpoints: list (default: []) midpoints of the bins of the histogram. It is a read-only attribute. Data Attributes sample: numpy.ndarray (default: []) sample of which the histogram must be computed. count: numpy.ndarray (read-only) number of sample points per bin. It is a read-only attribute. Notes ----- The fields which can be passed to the default tooltip are: midpoint: mid-point of the bin related to the rectangle hovered on count: number of elements in the bin hovered on bin_start: start point of the bin bin-end: end point of the bin index: index of the bin """ # Mark decoration icon = 'fa-signal' name = 'Histogram' # Scaled attributes sample = Array([]).tag(sync=True, display_name='Sample', scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) count = Array([], read_only=True).tag(sync=True, display_name='Count', scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze) normalized = Bool().tag(sync=True) # Other attributes scales_metadata = Dict({ 'sample': {'orientation': 'horizontal', 'dimension': 'x'}, 'count': {'orientation': 'vertical', 'dimension': 'y'} }).tag(sync=True) bins = Int(10).tag(sync=True, display_name='Number of bins') midpoints = List(read_only=True).tag(sync=True, display_name='Mid points') # midpoints is a read-only attribute that is set when the mark is drawn colors = List(trait=Color(default_value=None, allow_none=True), default_value=['steelblue'])\ .tag(sync=True, display_name='Colors') stroke = Color(None, allow_none=True).tag(sync=True) opacities = List(trait=Float(1.0, min=0, max=1, allow_none=True))\ .tag(sync=True, display_name='Opacities') _view_name = Unicode('Hist').tag(sync=True) _model_name = Unicode('HistModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
33,571
bqplot.marks
Image
Image mark, based on the ipywidgets image If no scales are passed, uses the parent Figure scales. Attributes ---------- image: Instance of ipywidgets.Image Image to be displayed Data Attributes x: tuple (default: (0, 1)) abscissas of the left and right-hand side of the image in the format (x0, x1) y: tuple (default: (0, 1)) ordinates of the bottom and top side of the image in the format (y0, y1)
class Image(Mark): """Image mark, based on the ipywidgets image If no scales are passed, uses the parent Figure scales. Attributes ---------- image: Instance of ipywidgets.Image Image to be displayed Data Attributes x: tuple (default: (0, 1)) abscissas of the left and right-hand side of the image in the format (x0, x1) y: tuple (default: (0, 1)) ordinates of the bottom and top side of the image in the format (y0, y1) """ _view_name = Unicode('Image').tag(sync=True) _model_name = Unicode('ImageModel').tag(sync=True) image = Instance(widgets.Image).tag(sync=True, **widget_serialization) pixelated = Bool(True).tag(sync=True) x = Array(default_value=(0, 1)).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, shape(2)) y = Array(default_value=(0, 1)).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, shape(2)) scales_metadata = Dict({ 'x': {'orientation': 'horizontal', 'dimension': 'x'}, 'y': {'orientation': 'vertical', 'dimension': 'y'}, }).tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
33,685
bqplot.interacts
Interaction
The base interaction class. An interaction is a mouse interaction layer for a figure that requires the capture of all mouse events on the plot area. A consequence is that one can allow only one interaction at any time on a figure. An interaction can be associated with features such as selection or manual change of specific mark. Although, they differ from the so called 'mark interactions' in that they do not rely on knowing whether a specific element of the mark are hovered by the mouse. Attributes ---------- types: dict (class-level attribute) representing interaction types A registry of existing interaction types.
class Interaction(Widget): """The base interaction class. An interaction is a mouse interaction layer for a figure that requires the capture of all mouse events on the plot area. A consequence is that one can allow only one interaction at any time on a figure. An interaction can be associated with features such as selection or manual change of specific mark. Although, they differ from the so called 'mark interactions' in that they do not rely on knowing whether a specific element of the mark are hovered by the mouse. Attributes ---------- types: dict (class-level attribute) representing interaction types A registry of existing interaction types. """ types = {} _view_name = Unicode('Interaction').tag(sync=True) _model_name = Unicode('BaseModel').tag(sync=True) _view_module = Unicode('bqplot').tag(sync=True) _model_module = Unicode('bqplot').tag(sync=True) _view_module_version = Unicode(__frontend_version__).tag(sync=True) _model_module_version = Unicode(__frontend_version__).tag(sync=True) # We cannot display an interaction outside of a figure _ipython_display_ = None
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
33,742
bqplot.marks
Label
Label mark. Attributes ---------- x_offset: int (default: 0) horizontal offset in pixels from the stated x location y_offset: int (default: 0) vertical offset in pixels from the stated y location text: string (default: '') text to be displayed default_size: string (default: '14px') font size in px, em or ex font_weight: {'bold', 'normal', 'bolder'} font weight of the caption drag_size: nonnegative float (default: 1.) Ratio of the size of the dragged label font size to the default label font size. align: {'start', 'middle', 'end'} alignment of the text with respect to the provided location enable_move: Bool (default: False) Enable the label to be moved by dragging. Refer to restrict_x, restrict_y for more options. restrict_x: bool (default: False) Restricts movement of the label to only along the x axis. This is valid only when enable_move is set to True. If both restrict_x and restrict_y are set to True, the label cannot be moved. restrict_y: bool (default: False) Restricts movement of the label to only along the y axis. This is valid only when enable_move is set to True. If both restrict_x and restrict_y are set to True, the label cannot be moved. Data Attributes x: numpy.ndarray (default: []) horizontal position of the labels, in data coordinates or in figure coordinates y: numpy.ndarray (default: []) vertical position of the labels, in data coordinates or in figure coordinates color: numpy.ndarray or None (default: None) label colors size: numpy.ndarray or None (default: None) label sizes rotation: numpy.ndarray or None (default: None) label rotations opacity: numpy.ndarray or None (default: None) label opacities
class Label(_ScatterBase): """Label mark. Attributes ---------- x_offset: int (default: 0) horizontal offset in pixels from the stated x location y_offset: int (default: 0) vertical offset in pixels from the stated y location text: string (default: '') text to be displayed default_size: string (default: '14px') font size in px, em or ex font_weight: {'bold', 'normal', 'bolder'} font weight of the caption drag_size: nonnegative float (default: 1.) Ratio of the size of the dragged label font size to the default label font size. align: {'start', 'middle', 'end'} alignment of the text with respect to the provided location enable_move: Bool (default: False) Enable the label to be moved by dragging. Refer to restrict_x, restrict_y for more options. restrict_x: bool (default: False) Restricts movement of the label to only along the x axis. This is valid only when enable_move is set to True. If both restrict_x and restrict_y are set to True, the label cannot be moved. restrict_y: bool (default: False) Restricts movement of the label to only along the y axis. This is valid only when enable_move is set to True. If both restrict_x and restrict_y are set to True, the label cannot be moved. Data Attributes x: numpy.ndarray (default: []) horizontal position of the labels, in data coordinates or in figure coordinates y: numpy.ndarray (default: []) vertical position of the labels, in data coordinates or in figure coordinates color: numpy.ndarray or None (default: None) label colors size: numpy.ndarray or None (default: None) label sizes rotation: numpy.ndarray or None (default: None) label rotations opacity: numpy.ndarray or None (default: None) label opacities """ # Mark decoration icon = 'fa-font' name = 'Labels' # Other attributes x_offset = Int(0).tag(sync=True) y_offset = Int(0).tag(sync=True) colors = List(trait=Color(default_value=None, allow_none=True), default_value=CATEGORY10)\ .tag(sync=True, display_name='Colors') rotate_angle = Float(0.0).tag(sync=True) text = Array(None, allow_none=True)\ .tag(sync=True, **array_serialization).valid(array_squeeze) default_size = Float(16.).tag(sync=True) drag_size = Float(1.).tag(sync=True) font_unit = Enum(['px', 'em', 'pt', '%'], default_value='px').tag(sync=True) font_weight = Enum(['bold', 'normal', 'bolder'], default_value='bold').tag(sync=True) align = Enum(['start', 'middle', 'end'], default_value='start').tag(sync=True) _view_name = Unicode('Label').tag(sync=True) _model_name = Unicode('LabelModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
33,747
bqplot.marks
__init__
null
def __init__(self, **kwargs): self._drag_start_handlers = CallbackDispatcher() self._drag_handlers = CallbackDispatcher() self._drag_end_handlers = CallbackDispatcher() super(_ScatterBase, self).__init__(**kwargs) self._name_to_handler.update({ 'drag_start': self._drag_start_handlers, 'drag_end': self._drag_end_handlers, 'drag': self._drag_handlers })
(self, **kwargs)
33,786
bqplot.marks
on_drag
null
def on_drag(self, callback, remove=False): self._drag_handlers.register_callback(callback, remove=remove)
(self, callback, remove=False)
33,787
bqplot.marks
on_drag_end
null
def on_drag_end(self, callback, remove=False): self._drag_end_handlers.register_callback(callback, remove=remove)
(self, callback, remove=False)
33,788
bqplot.marks
on_drag_start
null
def on_drag_start(self, callback, remove=False): self._drag_start_handlers.register_callback(callback, remove=remove)
(self, callback, remove=False)
33,810
ipywidgets.widgets.widget_layout
Layout
Layout specification Defines a layout that can be expressed using CSS. Supports a subset of https://developer.mozilla.org/en-US/docs/Web/CSS/Reference When a property is also accessible via a shorthand property, we only expose the shorthand. For example: - ``flex-grow``, ``flex-shrink`` and ``flex-basis`` are bound to ``flex``. - ``flex-wrap`` and ``flex-direction`` are bound to ``flex-flow``. - ``margin-[top/bottom/left/right]`` values are bound to ``margin``, etc.
class Layout(Widget): """Layout specification Defines a layout that can be expressed using CSS. Supports a subset of https://developer.mozilla.org/en-US/docs/Web/CSS/Reference When a property is also accessible via a shorthand property, we only expose the shorthand. For example: - ``flex-grow``, ``flex-shrink`` and ``flex-basis`` are bound to ``flex``. - ``flex-wrap`` and ``flex-direction`` are bound to ``flex-flow``. - ``margin-[top/bottom/left/right]`` values are bound to ``margin``, etc. """ _view_name = Unicode('LayoutView').tag(sync=True) _view_module = Unicode('@jupyter-widgets/base').tag(sync=True) _view_module_version = Unicode(__jupyter_widgets_base_version__).tag(sync=True) _model_name = Unicode('LayoutModel').tag(sync=True) # Keys align_content = CaselessStrEnum(['flex-start', 'flex-end', 'center', 'space-between', 'space-around', 'space-evenly', 'stretch'] + CSS_PROPERTIES, allow_none=True, help="The align-content CSS attribute.").tag(sync=True) align_items = CaselessStrEnum(['flex-start', 'flex-end', 'center', 'baseline', 'stretch'] + CSS_PROPERTIES, allow_none=True, help="The align-items CSS attribute.").tag(sync=True) align_self = CaselessStrEnum(['auto', 'flex-start', 'flex-end', 'center', 'baseline', 'stretch'] + CSS_PROPERTIES, allow_none=True, help="The align-self CSS attribute.").tag(sync=True) border_top = Unicode(None, allow_none=True, help="The border top CSS attribute.").tag(sync=True) border_right = Unicode(None, allow_none=True, help="The border right CSS attribute.").tag(sync=True) border_bottom = Unicode(None, allow_none=True, help="The border bottom CSS attribute.").tag(sync=True) border_left = Unicode(None, allow_none=True, help="The border left CSS attribute.").tag(sync=True) bottom = Unicode(None, allow_none=True, help="The bottom CSS attribute.").tag(sync=True) display = Unicode(None, allow_none=True, help="The display CSS attribute.").tag(sync=True) flex = Unicode(None, allow_none=True, help="The flex CSS attribute.").tag(sync=True) flex_flow = Unicode(None, allow_none=True, help="The flex-flow CSS attribute.").tag(sync=True) height = Unicode(None, allow_none=True, help="The height CSS attribute.").tag(sync=True) justify_content = CaselessStrEnum(['flex-start', 'flex-end', 'center', 'space-between', 'space-around'] + CSS_PROPERTIES, allow_none=True, help="The justify-content CSS attribute.").tag(sync=True) justify_items = CaselessStrEnum(['flex-start', 'flex-end', 'center'] + CSS_PROPERTIES, allow_none=True, help="The justify-items CSS attribute.").tag(sync=True) left = Unicode(None, allow_none=True, help="The left CSS attribute.").tag(sync=True) margin = Unicode(None, allow_none=True, help="The margin CSS attribute.").tag(sync=True) max_height = Unicode(None, allow_none=True, help="The max-height CSS attribute.").tag(sync=True) max_width = Unicode(None, allow_none=True, help="The max-width CSS attribute.").tag(sync=True) min_height = Unicode(None, allow_none=True, help="The min-height CSS attribute.").tag(sync=True) min_width = Unicode(None, allow_none=True, help="The min-width CSS attribute.").tag(sync=True) overflow = Unicode(None, allow_none=True, help="The overflow CSS attribute.").tag(sync=True) order = Unicode(None, allow_none=True, help="The order CSS attribute.").tag(sync=True) padding = Unicode(None, allow_none=True, help="The padding CSS attribute.").tag(sync=True) right = Unicode(None, allow_none=True, help="The right CSS attribute.").tag(sync=True) top = Unicode(None, allow_none=True, help="The top CSS attribute.").tag(sync=True) visibility = CaselessStrEnum(['visible', 'hidden']+CSS_PROPERTIES, allow_none=True, help="The visibility CSS attribute.").tag(sync=True) width = Unicode(None, allow_none=True, help="The width CSS attribute.").tag(sync=True) object_fit = CaselessStrEnum(['contain', 'cover', 'fill', 'scale-down', 'none'], allow_none=True, help="The object-fit CSS attribute.").tag(sync=True) object_position = Unicode(None, allow_none=True, help="The object-position CSS attribute.").tag(sync=True) grid_auto_columns = Unicode(None, allow_none=True, help="The grid-auto-columns CSS attribute.").tag(sync=True) grid_auto_flow = CaselessStrEnum(['column','row','row dense','column dense']+ CSS_PROPERTIES, allow_none=True, help="The grid-auto-flow CSS attribute.").tag(sync=True) grid_auto_rows = Unicode(None, allow_none=True, help="The grid-auto-rows CSS attribute.").tag(sync=True) grid_gap = Unicode(None, allow_none=True, help="The grid-gap CSS attribute.").tag(sync=True) grid_template_rows = Unicode(None, allow_none=True, help="The grid-template-rows CSS attribute.").tag(sync=True) grid_template_columns = Unicode(None, allow_none=True, help="The grid-template-columns CSS attribute.").tag(sync=True) grid_template_areas = Unicode(None, allow_none=True, help="The grid-template-areas CSS attribute.").tag(sync=True) grid_row = Unicode(None, allow_none=True, help="The grid-row CSS attribute.").tag(sync=True) grid_column = Unicode(None, allow_none=True, help="The grid-column CSS attribute.").tag(sync=True) grid_area = Unicode(None, allow_none=True, help="The grid-area CSS attribute.").tag(sync=True) def __init__(self, **kwargs): if 'border' in kwargs: border = kwargs.pop('border') for side in ['top', 'right', 'bottom', 'left']: kwargs.setdefault(f'border_{side}', border) super().__init__(**kwargs) def _get_border(self): """ `border` property getter. Return the common value of all side borders if they are identical. Otherwise return None. """ found = None for side in ['top', 'right', 'bottom', 'left']: if not hasattr(self, "border_" + side): return old, found = found, getattr(self, "border_" + side) if found is None or (old is not None and found != old): return return found def _set_border(self, border): """ `border` property setter. Set all 4 sides to `border` string. """ for side in ['top', 'right', 'bottom', 'left']: setattr(self, "border_" + side, border) border = property(_get_border, _set_border)
(**kwargs)
33,815
ipywidgets.widgets.widget_layout
__init__
null
def __init__(self, **kwargs): if 'border' in kwargs: border = kwargs.pop('border') for side in ['top', 'right', 'bottom', 'left']: kwargs.setdefault(f'border_{side}', border) super().__init__(**kwargs)
(self, **kwargs)
33,823
ipywidgets.widgets.widget_layout
_get_border
`border` property getter. Return the common value of all side borders if they are identical. Otherwise return None.
def _get_border(self): """ `border` property getter. Return the common value of all side borders if they are identical. Otherwise return None. """ found = None for side in ['top', 'right', 'bottom', 'left']: if not hasattr(self, "border_" + side): return old, found = found, getattr(self, "border_" + side) if found is None or (old is not None and found != old): return return found
(self)
33,837
ipywidgets.widgets.widget_layout
_set_border
`border` property setter. Set all 4 sides to `border` string.
def _set_border(self, border): """ `border` property setter. Set all 4 sides to `border` string. """ for side in ['top', 'right', 'bottom', 'left']: setattr(self, "border_" + side, border)
(self, border)
33,869
bqplot.scales
LinearScale
A linear scale. An affine mapping from a numerical domain to a numerical range. Attributes ---------- min: float or None (default: None) if not None, min is the minimal value of the domain max: float or None (default: None) if not None, max is the maximal value of the domain rtype: string (class-level attribute) This attribute should not be modified. The range type of a linear scale is numerical. dtype: type (class-level attribute) the associated data type / domain type precedence: int (class-level attribute, default_value=2) attribute used to determine which scale takes precedence in cases when two or more scales have the same rtype and dtype. default_value is 2 because for the same range and domain types, LinearScale should take precedence. stabilized: bool (default: False) if set to False, the domain of the scale is tied to the data range if set to True, the domain of the scale is updated only when the data range is beyond certain thresholds, given by the attributes mid_range and min_range. mid_range: float (default: 0.8) Proportion of the range that is spanned initially. Used only if stabilized is True. min_range: float (default: 0.6) Minimum proportion of the range that should be spanned by the data. If the data span falls beneath that level, the scale is reset. min_range must be <= mid_range. Used only if stabilized is True.
class LinearScale(Scale): """A linear scale. An affine mapping from a numerical domain to a numerical range. Attributes ---------- min: float or None (default: None) if not None, min is the minimal value of the domain max: float or None (default: None) if not None, max is the maximal value of the domain rtype: string (class-level attribute) This attribute should not be modified. The range type of a linear scale is numerical. dtype: type (class-level attribute) the associated data type / domain type precedence: int (class-level attribute, default_value=2) attribute used to determine which scale takes precedence in cases when two or more scales have the same rtype and dtype. default_value is 2 because for the same range and domain types, LinearScale should take precedence. stabilized: bool (default: False) if set to False, the domain of the scale is tied to the data range if set to True, the domain of the scale is updated only when the data range is beyond certain thresholds, given by the attributes mid_range and min_range. mid_range: float (default: 0.8) Proportion of the range that is spanned initially. Used only if stabilized is True. min_range: float (default: 0.6) Minimum proportion of the range that should be spanned by the data. If the data span falls beneath that level, the scale is reset. min_range must be <= mid_range. Used only if stabilized is True. """ rtype = 'Number' dtype = np.number precedence = 2 min = Float(None, allow_none=True).tag(sync=True) max = Float(None, allow_none=True).tag(sync=True) stabilized = Bool(False).tag(sync=True) min_range = Float(0.6, min=0.0, max=1.0).tag(sync=True) mid_range = Float(0.8, min=0.1, max=1.0).tag(sync=True) _view_name = Unicode('LinearScale').tag(sync=True) _model_name = Unicode('LinearScaleModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
33,926
bqplot.marks
Lines
Lines mark. In the case of the Lines mark, scales for 'x' and 'y' MUST be provided. Attributes ---------- icon: string (class-level attribute) Font-awesome icon for the respective mark name: string (class-level attribute) User-friendly name of the mark colors: list of colors (default: CATEGORY10) List of colors of the Lines. If the list is shorter than the number of lines, the colors are reused. close_path: bool (default: False) Whether to close the paths or not. fill: {'none', 'bottom', 'top', 'inside', 'between'} Fill in the area defined by the curves fill_colors: list of colors (default: []) Fill colors for the areas. Defaults to stroke-colors when no color provided opacities: list of floats (default: []) Opacity for the lines and patches. Defaults to 1 when the list is too short, or the element of the list is set to None. fill_opacities: list of floats (default: []) Opacity for the areas. Defaults to 1 when the list is too short, or the element of the list is set to None. stroke_width: float (default: 2) Stroke width of the Lines labels_visibility: {'none', 'label'} Visibility of the curve labels curves_subset: list of integers or None (default: []) If set to None, all the lines are displayed. Otherwise, only the items in the list will have full opacity, while others will be faded. line_style: {'solid', 'dashed', 'dotted', 'dash_dotted'} Line style. interpolation: {'linear', 'basis', 'basis-open', 'basis-closed', 'bundle', 'cardinal', 'cardinal-open', 'cardinal-closed', 'monotone', 'step-before', 'step-after'} Interpolation scheme used for interpolation between the data points provided. Please refer to the svg interpolate documentation for details about the different interpolation schemes. marker: {'circle', 'cross', 'diamond', 'square', 'triangle-down', 'triangle-up', 'arrow', 'rectangle', 'ellipse', 'plus', 'crosshair', 'point'} Marker shape marker_size: nonnegative int (default: 64) Default marker size in pixels Data Attributes x: numpy.ndarray (default: []) abscissas of the data points (1d or 2d array) y: numpy.ndarray (default: []) ordinates of the data points (1d or 2d array) color: numpy.ndarray (default: None) colors of the different lines based on data. If it is [], then the colors from the colors attribute are used. Each line has a single color and if the size of colors is less than the number of lines, the remaining lines are given the default colors. Notes ----- The fields which can be passed to the default tooltip are: name: label of the line index: index of the line being hovered on color: data attribute for the color of the line The following are the events which can trigger interactions: click: left click of the mouse hover: mouse-over an element The following are the interactions which can be linked to the above events: tooltip: display tooltip
class Lines(Mark): """Lines mark. In the case of the Lines mark, scales for 'x' and 'y' MUST be provided. Attributes ---------- icon: string (class-level attribute) Font-awesome icon for the respective mark name: string (class-level attribute) User-friendly name of the mark colors: list of colors (default: CATEGORY10) List of colors of the Lines. If the list is shorter than the number of lines, the colors are reused. close_path: bool (default: False) Whether to close the paths or not. fill: {'none', 'bottom', 'top', 'inside', 'between'} Fill in the area defined by the curves fill_colors: list of colors (default: []) Fill colors for the areas. Defaults to stroke-colors when no color provided opacities: list of floats (default: []) Opacity for the lines and patches. Defaults to 1 when the list is too short, or the element of the list is set to None. fill_opacities: list of floats (default: []) Opacity for the areas. Defaults to 1 when the list is too short, or the element of the list is set to None. stroke_width: float (default: 2) Stroke width of the Lines labels_visibility: {'none', 'label'} Visibility of the curve labels curves_subset: list of integers or None (default: []) If set to None, all the lines are displayed. Otherwise, only the items in the list will have full opacity, while others will be faded. line_style: {'solid', 'dashed', 'dotted', 'dash_dotted'} Line style. interpolation: {'linear', 'basis', 'basis-open', 'basis-closed', 'bundle', 'cardinal', 'cardinal-open', 'cardinal-closed', 'monotone', 'step-before', 'step-after'} Interpolation scheme used for interpolation between the data points provided. Please refer to the svg interpolate documentation for details about the different interpolation schemes. marker: {'circle', 'cross', 'diamond', 'square', 'triangle-down', 'triangle-up', 'arrow', 'rectangle', 'ellipse', 'plus', 'crosshair', 'point'} Marker shape marker_size: nonnegative int (default: 64) Default marker size in pixels Data Attributes x: numpy.ndarray (default: []) abscissas of the data points (1d or 2d array) y: numpy.ndarray (default: []) ordinates of the data points (1d or 2d array) color: numpy.ndarray (default: None) colors of the different lines based on data. If it is [], then the colors from the colors attribute are used. Each line has a single color and if the size of colors is less than the number of lines, the remaining lines are given the default colors. Notes ----- The fields which can be passed to the default tooltip are: name: label of the line index: index of the line being hovered on color: data attribute for the color of the line The following are the events which can trigger interactions: click: left click of the mouse hover: mouse-over an element The following are the interactions which can be linked to the above events: tooltip: display tooltip """ # Mark decoration icon = 'fa-line-chart' name = 'Lines' # Scaled attributes x = Array([]).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 2), array_supported_kinds()) y = Array([]).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 2), array_supported_kinds()) color = Array(None, allow_none=True).tag(sync=True, scaled=True, rtype='Color', atype='bqplot.ColorAxis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) # Other attributes scales_metadata = Dict({ 'x': {'orientation': 'horizontal', 'dimension': 'x'}, 'y': {'orientation': 'vertical', 'dimension': 'y'}, 'color': {'dimension': 'color'} }).tag(sync=True) colors = List(trait=Color(default_value=None, allow_none=True), default_value=CATEGORY10)\ .tag(sync=True, display_name='Colors') fill_colors = List(trait=Color(default_value=None, allow_none=True))\ .tag(sync=True, display_name='Fill colors') stroke_width = Float(2.0).tag(sync=True, display_name='Stroke width') labels_visibility = Enum(['none', 'label'], default_value='none')\ .tag(sync=True, display_name='Labels visibility') curves_subset = List().tag(sync=True) line_style = Enum(['solid', 'dashed', 'dotted', 'dash_dotted'], default_value='solid')\ .tag(sync=True, display_name='Line style') # TODO: Only Lines have interpolatoin but we can extend for other types of graphs interpolation = Enum(['linear', 'basis', 'basis-open', 'basis-closed', 'bundle', 'cardinal', 'cardinal-open', 'cardinal-closed', 'monotone', 'step-before', 'step-after'], default_value='linear')\ .tag(sync=True, display_name='Interpolation') close_path = Bool().tag(sync=True, display_name='Close path') fill = Enum(['none', 'bottom', 'top', 'inside', 'between'], default_value='none')\ .tag(sync=True, display_name='Fill') marker = Enum(['circle', 'cross', 'diamond', 'square', 'triangle-down', 'triangle-up', 'arrow', 'rectangle', 'ellipse', 'plus', 'crosshair', 'point'], default_value=None, allow_none=True)\ .tag(sync=True, display_name='Marker') marker_size = Int(64).tag(sync=True, display_name='Default size') opacities = List().tag(sync=True, display_name='Opacity') fill_opacities = List().tag(sync=True, display_name='Fill Opacity') _view_name = Unicode('Lines').tag(sync=True) _model_name = Unicode('LinesModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
34,021
bqplot.scales
LogScale
A log scale. A logarithmic mapping from a numerical domain to a numerical range. Attributes ---------- min: float or None (default: None) if not None, min is the minimal value of the domain max: float or None (default: None) if not None, max is the maximal value of the domain rtype: string (class-level attribute) This attribute should not be modified by the user. The range type of a linear scale is numerical. dtype: type (class-level attribute) the associated data type / domain type
class LogScale(Scale): """A log scale. A logarithmic mapping from a numerical domain to a numerical range. Attributes ---------- min: float or None (default: None) if not None, min is the minimal value of the domain max: float or None (default: None) if not None, max is the maximal value of the domain rtype: string (class-level attribute) This attribute should not be modified by the user. The range type of a linear scale is numerical. dtype: type (class-level attribute) the associated data type / domain type """ rtype = 'Number' dtype = np.number min = Float(None, allow_none=True).tag(sync=True) max = Float(None, allow_none=True).tag(sync=True) _view_name = Unicode('LogScale').tag(sync=True) _model_name = Unicode('LogScaleModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
34,078
bqplot.marks
Map
Map mark. Attributes ---------- colors: Dict (default: {}) default colors for items of the map when no color data is passed. The dictionary should be indexed by the id of the element and have the corresponding colors as values. The key `default_color` controls the items for which no color is specified. selected_styles: Dict (default: {'selected_fill': 'Red', 'selected_stroke': None, 'selected_stroke_width': 2.0}) Dictionary containing the styles for selected subunits hovered_styles: Dict (default: {'hovered_fill': 'Orange', 'hovered_stroke': None, 'hovered_stroke_width': 2.0}) Dictionary containing the styles for hovered subunits hover_highlight: bool (default: True) boolean to control if the map should be aware of which country is being hovered on. map_data: dict (default: topo_load("map_data/WorldMap.json")) a topojson-formatted dictionary with the objects to map under the key 'subunits'. Data Attributes color: Dict or None (default: None) dictionary containing the data associated with every country for the color scale
class Map(Mark): """Map mark. Attributes ---------- colors: Dict (default: {}) default colors for items of the map when no color data is passed. The dictionary should be indexed by the id of the element and have the corresponding colors as values. The key `default_color` controls the items for which no color is specified. selected_styles: Dict (default: {'selected_fill': 'Red', 'selected_stroke': None, 'selected_stroke_width': 2.0}) Dictionary containing the styles for selected subunits hovered_styles: Dict (default: {'hovered_fill': 'Orange', 'hovered_stroke': None, 'hovered_stroke_width': 2.0}) Dictionary containing the styles for hovered subunits hover_highlight: bool (default: True) boolean to control if the map should be aware of which country is being hovered on. map_data: dict (default: topo_load("map_data/WorldMap.json")) a topojson-formatted dictionary with the objects to map under the key 'subunits'. Data Attributes color: Dict or None (default: None) dictionary containing the data associated with every country for the color scale """ # Mark decoration icon = 'fa-globe' name = 'Map' # Scaled attributes color = Dict(allow_none=True).tag(sync=True, scaled=True, rtype='Color', atype='bqplot.ColorAxis') # Other attributes scales_metadata = Dict({'color': {'dimension': 'color'}}).tag(sync=True) hover_highlight = Bool(True).tag(sync=True) hovered_styles = Dict({ 'hovered_fill': 'Orange', 'hovered_stroke': None, 'hovered_stroke_width': 2.0}, allow_none=True).tag(sync=True) stroke_color = Color(default_value=None, allow_none=True).tag(sync=True) colors = Dict().tag(sync=True, display_name='Colors') scales_metadata = Dict({'color': {'dimension': 'color'}, 'projection': {'dimension': 'geo'}}).tag(sync=True) selected_styles = Dict({ 'selected_fill': 'Red', 'selected_stroke': None, 'selected_stroke_width': 2.0 }).tag(sync=True) map_data = Dict(topo_load('map_data/WorldMap.json')).tag(sync=True) _view_name = Unicode('Map').tag(sync=True) _model_name = Unicode('MapModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
34,143
bqplot.marks
Mark
The base mark class. Traitlet mark attributes may be decorated with metadata. **Data Attribute Decoration** Data attributes are decorated with the following values: scaled: bool Indicates whether the considered attribute is a data attribute which must be associated with a scale in order to be taken into account. rtype: string Range type of the associated scale. atype: string Key in bqplot's axis registry of the recommended axis type to represent this scale. When not specified, the default is 'bqplot.Axis'. Attributes ---------- display_name: string Holds a user-friendly name for the trait attribute. mark_types: dict (class-level attribute) A registry of existing mark types. scales: Dict of scales (default: {}) A dictionary of scales holding scales for each data attribute. - If a mark holds a scaled attribute named 'x', the scales dictionary must have a corresponding scale for the key 'x'. - The scale's range type should be equal to the scaled attribute's range type (rtype). scales_metadata: Dict (default: {}) A dictionary of dictionaries holding metadata on the way scales are used by the mark. For example, a linear scale may be used to count pixels horizontally or vertically. The content of this dictionary may change dynamically. It is an instance-level attribute. preserve_domain: dict (default: {}) Indicates if this mark affects the domain(s) of the specified scale(s). The keys of this dictionary are the same as the ones of the "scales" attribute, and values are boolean. If a key is missing, it is considered as False. display_legend: bool (default: False) Display toggle for the mark legend in the general figure legend labels: list of unicode strings (default: []) Labels of the items of the mark. This attribute has different meanings depending on the type of mark. apply_clip: bool (default: True) Indicates whether the items that are beyond the limits of the chart should be clipped. visible: bool (default: True) Visibility toggle for the mark. selected_style: dict (default: {}) CSS style to be applied to selected items in the mark. unselected_style: dict (default: {}) CSS style to be applied to items that are not selected in the mark, when a selection exists. selected: list of integers or None (default: None) Indices of the selected items in the mark. tooltip: DOMWidget or None (default: None) Widget to be displayed as tooltip when elements of the scatter are hovered on tooltip_style: Dictionary (default: {'opacity': 0.9}) Styles to be applied to the tooltip widget enable_hover: Bool (default: True) Boolean attribute to control the hover interaction for the scatter. If this is false, the on_hover custom mssg is not sent back to the python side interactions: Dictionary (default: {'hover': 'tooltip'}) Dictionary listing the different interactions for each mark. The key is the event which triggers the interaction and the value is the kind of interactions. Keys and values can only take strings from separate enums for each mark. tooltip_location : {'mouse', 'center'} (default: 'mouse') Enum specifying the location of the tooltip. 'mouse' places the tooltip at the location of the mouse when the tooltip is activated and 'center' places the tooltip at the center of the figure. If tooltip is linked to a click event, 'mouse' places the tooltip at the location of the click that triggered the tooltip to be visible.
class Mark(Widget): """The base mark class. Traitlet mark attributes may be decorated with metadata. **Data Attribute Decoration** Data attributes are decorated with the following values: scaled: bool Indicates whether the considered attribute is a data attribute which must be associated with a scale in order to be taken into account. rtype: string Range type of the associated scale. atype: string Key in bqplot's axis registry of the recommended axis type to represent this scale. When not specified, the default is 'bqplot.Axis'. Attributes ---------- display_name: string Holds a user-friendly name for the trait attribute. mark_types: dict (class-level attribute) A registry of existing mark types. scales: Dict of scales (default: {}) A dictionary of scales holding scales for each data attribute. - If a mark holds a scaled attribute named 'x', the scales dictionary must have a corresponding scale for the key 'x'. - The scale's range type should be equal to the scaled attribute's range type (rtype). scales_metadata: Dict (default: {}) A dictionary of dictionaries holding metadata on the way scales are used by the mark. For example, a linear scale may be used to count pixels horizontally or vertically. The content of this dictionary may change dynamically. It is an instance-level attribute. preserve_domain: dict (default: {}) Indicates if this mark affects the domain(s) of the specified scale(s). The keys of this dictionary are the same as the ones of the "scales" attribute, and values are boolean. If a key is missing, it is considered as False. display_legend: bool (default: False) Display toggle for the mark legend in the general figure legend labels: list of unicode strings (default: []) Labels of the items of the mark. This attribute has different meanings depending on the type of mark. apply_clip: bool (default: True) Indicates whether the items that are beyond the limits of the chart should be clipped. visible: bool (default: True) Visibility toggle for the mark. selected_style: dict (default: {}) CSS style to be applied to selected items in the mark. unselected_style: dict (default: {}) CSS style to be applied to items that are not selected in the mark, when a selection exists. selected: list of integers or None (default: None) Indices of the selected items in the mark. tooltip: DOMWidget or None (default: None) Widget to be displayed as tooltip when elements of the scatter are hovered on tooltip_style: Dictionary (default: {'opacity': 0.9}) Styles to be applied to the tooltip widget enable_hover: Bool (default: True) Boolean attribute to control the hover interaction for the scatter. If this is false, the on_hover custom mssg is not sent back to the python side interactions: Dictionary (default: {'hover': 'tooltip'}) Dictionary listing the different interactions for each mark. The key is the event which triggers the interaction and the value is the kind of interactions. Keys and values can only take strings from separate enums for each mark. tooltip_location : {'mouse', 'center'} (default: 'mouse') Enum specifying the location of the tooltip. 'mouse' places the tooltip at the location of the mouse when the tooltip is activated and 'center' places the tooltip at the center of the figure. If tooltip is linked to a click event, 'mouse' places the tooltip at the location of the click that triggered the tooltip to be visible. """ mark_types = {} scales = Dict(value_trait=Instance(Scale)).tag(sync=True, **widget_serialization) scales_metadata = Dict().tag(sync=True) preserve_domain = Dict().tag(sync=True) display_legend = Bool().tag(sync=True, display_name='Display legend') labels = List(trait=Unicode()).tag(sync=True, display_name='Labels') apply_clip = Bool(True).tag(sync=True) visible = Bool(True).tag(sync=True) selected_style = Dict().tag(sync=True) unselected_style = Dict().tag(sync=True) selected = Array(None, allow_none=True).tag(sync=True, **array_serialization) enable_hover = Bool(True).tag(sync=True) tooltip = Instance(DOMWidget, allow_none=True, default_value=None)\ .tag(sync=True, **widget_serialization) tooltip_style = Dict({'opacity': 0.9}).tag(sync=True) interactions = Dict({'hover': 'tooltip'}).tag(sync=True) tooltip_location = Enum(['mouse', 'center'], default_value='mouse')\ .tag(sync=True) _model_name = Unicode('MarkModel').tag(sync=True) _model_module = Unicode('bqplot').tag(sync=True) _view_module = Unicode('bqplot').tag(sync=True) _view_module_version = Unicode(__frontend_version__).tag(sync=True) _model_module_version = Unicode(__frontend_version__).tag(sync=True) _ipython_display_ = None def _get_dimension_scales(self, dimension, preserve_domain=False): """ Return the list of scales corresponding to a given dimension. The preserve_domain optional argument specifies whether one should filter out the scales for which preserve_domain is set to True. """ if preserve_domain: return [ self.scales[k] for k in self.scales if ( k in self.scales_metadata and self.scales_metadata[k].get('dimension') == dimension and not self.preserve_domain.get(k) ) ] else: return [ self.scales[k] for k in self.scales if ( k in self.scales_metadata and self.scales_metadata[k].get('dimension') == dimension ) ] @validate('scales') def _validate_scales(self, proposal): """ Validates the `scales` based on the mark's scaled attributes metadata. First checks for missing scale and then for 'rtype' compatibility. """ # Validate scales' 'rtype' versus data attribute 'rtype' decoration # At this stage it is already validated that all values in self.scales # are instances of Scale. scales = proposal.value for name in self.trait_names(scaled=True): trait = self.traits()[name] if name not in scales: # Check for missing scale if not trait.allow_none: raise TraitError("Missing scale for data attribute %s." % name) else: # Check scale range type compatibility if scales[name].rtype != trait.metadata['rtype']: raise TraitError("Range type mismatch for scale %s." % name) return scales def __init__(self, **kwargs): super(Mark, self).__init__(**kwargs) self._hover_handlers = CallbackDispatcher() self._click_handlers = CallbackDispatcher() self._legend_click_handlers = CallbackDispatcher() self._legend_hover_handlers = CallbackDispatcher() self._element_click_handlers = CallbackDispatcher() self._bg_click_handlers = CallbackDispatcher() self._name_to_handler = { 'hover': self._hover_handlers, 'click': self._click_handlers, 'legend_click': self._legend_click_handlers, 'legend_hover': self._legend_hover_handlers, 'element_click': self._element_click_handlers, 'background_click': self._bg_click_handlers } self.on_msg(self._handle_custom_msgs) def on_hover(self, callback, remove=False): self._hover_handlers.register_callback(callback, remove=remove) def on_click(self, callback, remove=False): self._click_handlers.register_callback(callback, remove=remove) def on_legend_click(self, callback, remove=False): self._legend_click_handlers.register_callback(callback, remove=remove) def on_legend_hover(self, callback, remove=False): self._legend_hover_handlers.register_callback(callback, remove=remove) def on_element_click(self, callback, remove=False): self._element_click_handlers.register_callback(callback, remove=remove) def on_background_click(self, callback, remove=False): self._bg_click_handlers.register_callback(callback, remove=remove) def _handle_custom_msgs(self, _, content, buffers=None): try: handler = self._name_to_handler[content['event']] except KeyError: return handler(self, content)
(**kwargs)
34,208
bqplot.scales
Mercator
A geographical projection scale commonly used for world maps. The Mercator projection is a cylindrical map projection which ensures that any course of constant bearing is a straight line. Attributes ---------- scale_factor: float (default: 190) Specifies the scale value for the projection center: tuple (default: (0, 60)) Specifies the longitude and latitude where the map is centered. rotate: tuple (default: (0, 0)) Degree of rotation in each axis. rtype: (Number, Number) (class-level attribute) This attribute should not be modified. The range type of a geo scale is a tuple. dtype: type (class-level attribute) the associated data type / domain type
class Mercator(GeoScale): """A geographical projection scale commonly used for world maps. The Mercator projection is a cylindrical map projection which ensures that any course of constant bearing is a straight line. Attributes ---------- scale_factor: float (default: 190) Specifies the scale value for the projection center: tuple (default: (0, 60)) Specifies the longitude and latitude where the map is centered. rotate: tuple (default: (0, 0)) Degree of rotation in each axis. rtype: (Number, Number) (class-level attribute) This attribute should not be modified. The range type of a geo scale is a tuple. dtype: type (class-level attribute) the associated data type / domain type """ scale_factor = Float(190).tag(sync=True) center = Tuple((0, 60)).tag(sync=True) rotate = Tuple((0, 0)).tag(sync=True) rtype = '(Number, Number)' dtype = np.number _view_name = Unicode('Mercator').tag(sync=True) _model_name = Unicode('MercatorModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
34,265
bqplot.marks
OHLC
Open/High/Low/Close marks. Attributes ---------- icon: string (class-level attribute) font-awesome icon for that mark name: string (class-level attribute) user-friendly name of the mark marker: {'candle', 'bar'} marker type stroke: color (default: None) stroke color of the marker stroke_width: float (default: 1.0) stroke width of the marker colors: List of colors (default: ['limegreen', 'red']) fill colors for the markers (up/down) opacities: list of floats (default: []) Opacities for the markers of the OHLC mark. Defaults to 1 when the list is too short, or the element of the list is set to None. format: string (default: 'ohlc') description of y data being passed supports all permutations of the strings 'ohlc', 'oc', and 'hl' Data Attributes x: numpy.ndarray abscissas of the data points (1d array) y: numpy.ndarrays Open/High/Low/Close ordinates of the data points (2d array) Notes ----- The fields which can be passed to the default tooltip are: x: the x value associated with the bar/candle open: open value for the bar/candle high: high value for the bar/candle low: low value for the bar/candle close: close value for the bar/candle index: index of the bar/candle being hovered on
class OHLC(Mark): """Open/High/Low/Close marks. Attributes ---------- icon: string (class-level attribute) font-awesome icon for that mark name: string (class-level attribute) user-friendly name of the mark marker: {'candle', 'bar'} marker type stroke: color (default: None) stroke color of the marker stroke_width: float (default: 1.0) stroke width of the marker colors: List of colors (default: ['limegreen', 'red']) fill colors for the markers (up/down) opacities: list of floats (default: []) Opacities for the markers of the OHLC mark. Defaults to 1 when the list is too short, or the element of the list is set to None. format: string (default: 'ohlc') description of y data being passed supports all permutations of the strings 'ohlc', 'oc', and 'hl' Data Attributes x: numpy.ndarray abscissas of the data points (1d array) y: numpy.ndarrays Open/High/Low/Close ordinates of the data points (2d array) Notes ----- The fields which can be passed to the default tooltip are: x: the x value associated with the bar/candle open: open value for the bar/candle high: high value for the bar/candle low: low value for the bar/candle close: close value for the bar/candle index: index of the bar/candle being hovered on """ # Mark decoration icon = 'fa-birthday-cake' name = 'OHLC chart' # Scaled attributes x = Array([]).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) y = Array([[]]).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization)\ .valid(array_dimension_bounds(1, 2)) # Other attributes scales_metadata = Dict({ 'x': {'orientation': 'horizontal', 'dimension': 'x'}, 'y': {'orientation': 'vertical', 'dimension': 'y'} }).tag(sync=True) marker = Enum(['candle', 'bar'], default_value='candle')\ .tag(sync=True, display_name='Marker') stroke = Color(None, allow_none=True)\ .tag(sync=True, display_name='Stroke color') stroke_width = Float(1.0).tag(sync=True, display_name='Stroke Width') colors = List(trait=Color(default_value=None, allow_none=True), default_value=['green', 'red'])\ .tag(sync=True, display_name='Colors') opacities = List(trait=Float(1.0, min=0, max=1, allow_none=True))\ .tag(sync=True, display_name='Opacities') format = Unicode('ohlc').tag(sync=True, display_name='Format') _view_name = Unicode('OHLC').tag(sync=True) _model_name = Unicode('OHLCModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
34,330
bqplot.scales
OrdinalColorScale
An ordinal color scale. A mapping from a discrete set of values to colors. Attributes ---------- domain: list (default: []) The discrete values mapped by the ordinal scales. rtype: string (class-level attribute) This attribute should not be modified by the user. The range type of a color scale is 'color'. dtype: type (class-level attribute) the associated data type / domain type
class OrdinalColorScale(ColorScale): """An ordinal color scale. A mapping from a discrete set of values to colors. Attributes ---------- domain: list (default: []) The discrete values mapped by the ordinal scales. rtype: string (class-level attribute) This attribute should not be modified by the user. The range type of a color scale is 'color'. dtype: type (class-level attribute) the associated data type / domain type """ rtype = 'Color' dtype = np.str_ domain = List().tag(sync=True) _view_name = Unicode('OrdinalColorScale').tag(sync=True) _model_name = Unicode('OrdinalColorScaleModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
34,387
bqplot.scales
OrdinalScale
An ordinal scale. A mapping from a discrete set of values to a numerical range. Attributes ---------- domain: list (default: []) The discrete values mapped by the ordinal scale rtype: string (class-level attribute) This attribute should not be modified by the user. The range type of a linear scale is numerical. dtype: type (class-level attribute) the associated data type / domain type
class OrdinalScale(Scale): """An ordinal scale. A mapping from a discrete set of values to a numerical range. Attributes ---------- domain: list (default: []) The discrete values mapped by the ordinal scale rtype: string (class-level attribute) This attribute should not be modified by the user. The range type of a linear scale is numerical. dtype: type (class-level attribute) the associated data type / domain type """ rtype = 'Number' dtype = np.str_ domain = List().tag(sync=True) _view_name = Unicode('OrdinalScale').tag(sync=True) _model_name = Unicode('OrdinalScaleModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
34,444
bqplot.scales
Orthographic
A perspective projection that depicts a hemisphere as it appears from outer space. The projection is neither equal-area nor conformal. Attributes ---------- scale_factor: float (default: 145) Specifies the scale value for the projection center: tuple (default: (0, 60)) Specifies the longitude and latitude where the map is centered. rotate: tuple (default: (96, 0)) Degree of rotation in each axis. clip_angle: float (default: 90.) Specifies the clipping circle radius to the specified angle in degrees. precision: float (default: 0.1) Specifies the threshold for the projections adaptive resampling to the specified value in pixels.
class Orthographic(GeoScale): """A perspective projection that depicts a hemisphere as it appears from outer space. The projection is neither equal-area nor conformal. Attributes ---------- scale_factor: float (default: 145) Specifies the scale value for the projection center: tuple (default: (0, 60)) Specifies the longitude and latitude where the map is centered. rotate: tuple (default: (96, 0)) Degree of rotation in each axis. clip_angle: float (default: 90.) Specifies the clipping circle radius to the specified angle in degrees. precision: float (default: 0.1) Specifies the threshold for the projections adaptive resampling to the specified value in pixels. """ scale_factor = Float(145.0).tag(sync=True) center = Tuple((0, 60)).tag(sync=True) rotate = Tuple((0, 0)).tag(sync=True) clip_angle = Float(90.0, min=0.0, max=360.0).tag(sync=True) precision = Float(0.1).tag(sync=True) rtype = '(Number, Number)' dtype = np.number _view_name = Unicode('Orthographic').tag(sync=True) _model_name = Unicode('OrthographicModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
34,501
bqplot.interacts
PanZoom
An interaction to pan and zoom wrt scales. Attributes ---------- allow_pan: bool (default: True) Toggle the ability to pan. allow_zoom: bool (default: True) Toggle the ability to zoom. scales: Dictionary of lists of Scales (default: {}) Dictionary with keys such as 'x' and 'y' and values being the scales in the corresponding direction (dimensions) which should be panned or zoomed.
class PanZoom(Interaction): """An interaction to pan and zoom wrt scales. Attributes ---------- allow_pan: bool (default: True) Toggle the ability to pan. allow_zoom: bool (default: True) Toggle the ability to zoom. scales: Dictionary of lists of Scales (default: {}) Dictionary with keys such as 'x' and 'y' and values being the scales in the corresponding direction (dimensions) which should be panned or zoomed. """ allow_pan = Bool(True).tag(sync=True) allow_zoom = Bool(True).tag(sync=True) scales = Dict(value_trait=List(trait=Instance(Scale)))\ .tag(sync=True, **widget_serialization) _view_name = Unicode('PanZoom').tag(sync=True) _model_name = Unicode('PanZoomModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
34,558
bqplot.marks
Pie
Piechart mark. Attributes ---------- colors: list of colors (default: CATEGORY10) list of colors for the slices. stroke: color (default: 'white') stroke color for the marker opacities: list of floats (default: []) Opacities for the slices of the Pie mark. Defaults to 1 when the list is too short, or the element of the list is set to None. sort: bool (default: False) sort the pie slices by descending sizes x: Float (default: 0.5) or Date horizontal position of the pie center, in data coordinates or in figure coordinates y: Float (default: 0.5) vertical y position of the pie center, in data coordinates or in figure coordinates radius: Float radius of the pie, in pixels inner_radius: Float inner radius of the pie, in pixels start_angle: Float (default: 0.0) start angle of the pie (from top), in degrees end_angle: Float (default: 360.0) end angle of the pie (from top), in degrees display_labels: {'none', 'inside', 'outside'} (default: 'inside') label display options display_values: bool (default: False) if True show values along with labels values_format: string (default: '.2f') format for displaying values label_color: Color or None (default: None) color of the labels font_size: string (default: '14px') label font size in px, em or ex font_weight: {'bold', 'normal', 'bolder'} (default: 'normal') label font weight Data Attributes sizes: numpy.ndarray (default: []) proportions of the pie slices color: numpy.ndarray or None (default: None) color of the data points. Defaults to colors when not provided. Notes ----- The fields which can be passed to the default tooltip are: : the x value associated with the bar/candle open: open value for the bar/candle high: high value for the bar/candle low: low value for the bar/candle close: close value for the bar/candle index: index of the bar/candle being hovered on
class Pie(Mark): """Piechart mark. Attributes ---------- colors: list of colors (default: CATEGORY10) list of colors for the slices. stroke: color (default: 'white') stroke color for the marker opacities: list of floats (default: []) Opacities for the slices of the Pie mark. Defaults to 1 when the list is too short, or the element of the list is set to None. sort: bool (default: False) sort the pie slices by descending sizes x: Float (default: 0.5) or Date horizontal position of the pie center, in data coordinates or in figure coordinates y: Float (default: 0.5) vertical y position of the pie center, in data coordinates or in figure coordinates radius: Float radius of the pie, in pixels inner_radius: Float inner radius of the pie, in pixels start_angle: Float (default: 0.0) start angle of the pie (from top), in degrees end_angle: Float (default: 360.0) end angle of the pie (from top), in degrees display_labels: {'none', 'inside', 'outside'} (default: 'inside') label display options display_values: bool (default: False) if True show values along with labels values_format: string (default: '.2f') format for displaying values label_color: Color or None (default: None) color of the labels font_size: string (default: '14px') label font size in px, em or ex font_weight: {'bold', 'normal', 'bolder'} (default: 'normal') label font weight Data Attributes sizes: numpy.ndarray (default: []) proportions of the pie slices color: numpy.ndarray or None (default: None) color of the data points. Defaults to colors when not provided. Notes ----- The fields which can be passed to the default tooltip are: : the x value associated with the bar/candle open: open value for the bar/candle high: high value for the bar/candle low: low value for the bar/candle close: close value for the bar/candle index: index of the bar/candle being hovered on """ # Mark decoration icon = 'fa-pie-chart' name = 'Pie chart' # Scaled attributes sizes = Array([]).tag(sync=True, rtype='Number', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) color = Array(None, allow_none=True).tag(sync=True, scaled=True, rtype='Color', atype='bqplot.ColorAxis', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) # Other attributes x = (Float(0.5) | Date() | Unicode()).tag(sync=True) y = (Float(0.5) | Date() | Unicode()).tag(sync=True) scales_metadata = Dict({'color': {'dimension': 'color'}}).tag(sync=True) sort = Bool().tag(sync=True) colors = List(trait=Color(default_value=None, allow_none=True), default_value=CATEGORY10).tag(sync=True, display_name='Colors') stroke = Color(None, allow_none=True).tag(sync=True) opacities = List(trait=Float(1.0, min=0, max=1, allow_none=True))\ .tag(sync=True, display_name='Opacities') radius = Float(180.0, min=0.0, max=float('inf')).tag(sync=True) inner_radius = Float(0.1, min=0.0, max=float('inf')).tag(sync=True) start_angle = Float().tag(sync=True) end_angle = Float(360.0).tag(sync=True) display_labels = Enum(['none', 'inside', 'outside'], default_value='inside').tag(sync=True) display_values = Bool(False).tag(sync=True) values_format = Unicode(default_value='.1f').tag(sync=True) label_color = Color(None, allow_none=True).tag(sync=True) font_size = Unicode(default_value='12px').tag(sync=True) font_weight = Enum(['bold', 'normal', 'bolder'], default_value='normal').tag(sync=True) _view_name = Unicode('Pie').tag(sync=True) _model_name = Unicode('PieModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
34,623
bqplot.plotting_widgets
Radar
Radar chart created from a pandas Dataframe. Each column of the df will be represented as a loop in the radar chart. Each row of the df will be represented as a spoke of the radar chart Attributes ---------- data: DataFrame data for the radar band_type: {"circle", "polygon"} (default: "circle") type of bands to display in the radar num_bands: Int (default: 5) number of bands on the radar. As of now, this attribute is not dynamic and it has to set in the constructor data_range: List (default: [0, 1]) range of data fill: Bool(default: True) flag which lets us fill the radar loops or not
class Radar(Figure): """ Radar chart created from a pandas Dataframe. Each column of the df will be represented as a loop in the radar chart. Each row of the df will be represented as a spoke of the radar chart Attributes ---------- data: DataFrame data for the radar band_type: {"circle", "polygon"} (default: "circle") type of bands to display in the radar num_bands: Int (default: 5) number of bands on the radar. As of now, this attribute is not dynamic and it has to set in the constructor data_range: List (default: [0, 1]) range of data fill: Bool(default: True) flag which lets us fill the radar loops or not """ data = DataFrame() data_range = List([0, 1]).tag(sync=True) band_type = Enum( ["circle", "polygon"], default_value="circle", allow_none=True ).tag(sync=True) colors = List(default_value=CATEGORY10).tag(sync=True) num_bands = Int(default_value=5).tag(sync=True) fill = Bool(default_value=False).tag(sync=True) def __init__(self, **kwargs): super(Radar, self).__init__(**kwargs) self.scales = {"x": LinearScale(), "y": LinearScale()} # set some defaults for the figure self.layout = Layout(min_width="600px", min_height="600px") self.max_aspect_ratio = 1 self.preserve_aspect = True # marks for the radar figure # spokes (straight lines going away from the center) self.spokes = Lines( scales=self.scales, colors=["#ccc"], stroke_width=0.5 ) # bands self.bands = Lines( colors=["#ccc"], scales=self.scales, stroke_width=0.5 ) # loops of the radar self.loops = Lines( scales=self.scales, display_legend=True, colors=self.colors, stroke_width=2, fill="inside" if self.fill else "none", marker="circle", marker_size=50, ) self.band_labels = Label( scales=self.scales, default_size=12, font_weight="normal", apply_clip=False, colors=["#ccc"], align="middle", ) self.spoke_labels = Label( scales=self.scales, default_size=14, font_weight="bold", apply_clip=False, colors=["#ccc"], align="middle", ) self.marks = [ self.spokes, self.bands, self.loops, self.band_labels, self.spoke_labels, ] # handlers for data updates self.observe(self.update_data, "data") self.observe(self.update_bands, ["band_type", "num_bands"]) self.observe(self.update_fill, "fill") self.loops.on_legend_click(self.on_legend_click) self.loops.on_background_click(self.reset) self.update_bands(None) self.update_data(None) def update_bands(self, *args): band_data = np.linspace( self.data_range[0], self.data_range[1], self.num_bands + 1 ) self.scaled_band_data = ( (band_data - self.data_range[0]) / (self.data_range[1] - self.data_range[0]) )[:, np.newaxis] n = len(self.data.index) if self.band_type == "circle": t = np.linspace(0, 2 * np.pi, 1000) band_data_x, band_data_y = ( self.scaled_band_data * np.cos(t), self.scaled_band_data * np.sin(t), ) elif self.band_type == "polygon": t = np.linspace(0, 2 * np.pi, n + 1) band_data_x, band_data_y = ( self.scaled_band_data * np.sin(t), self.scaled_band_data * np.cos(t), ) with self.bands.hold_sync(): self.bands.x = band_data_x self.bands.y = band_data_y with self.band_labels.hold_sync(): self.band_labels.x = self.scaled_band_data[:, 0] self.band_labels.y = [0.0] * (self.num_bands + 1) self.band_labels.text = ["{:.0%}".format(b) for b in band_data] def update_data(self, *args): self.update_bands(None) rows = list(self.data.index) n = len(rows) # spokes representing each data set self.spoke_data_t = np.linspace(0, 2 * np.pi, n + 1)[:-1] spoke_data_x, spoke_data_y = ( np.sin(self.spoke_data_t), np.cos(self.spoke_data_t), ) # Update mark data based on data changes with self.spokes.hold_sync(): self.spokes.x = np.column_stack( [self.scaled_band_data[1] * spoke_data_x, spoke_data_x] ) self.spokes.y = np.column_stack( [self.scaled_band_data[1] * spoke_data_y, spoke_data_y] ) scaled_data = (self.data.values - self.data_range[0]) / ( self.data_range[1] - self.data_range[0] ) data_x = scaled_data * np.sin(self.spoke_data_t)[:, np.newaxis] data_y = scaled_data * np.cos(self.spoke_data_t)[:, np.newaxis] # update data lines with self.loops.hold_sync(): self.loops.x = np.column_stack([data_x.T, data_x.T[:, 0]]) self.loops.y = np.column_stack([data_y.T, data_y.T[:, 0]]) if self.fill: self.loops.fill = "inside" self.loops.fill_opacities = [0.2] * len(self.loops.y) else: self.loops.fill = "none" self.loops.fill_opacities = [0.0] * len(self.loops.y) self.loops.labels = [str(c) for c in self.data.columns] # update spoke labels t = np.linspace(0, 2 * np.pi, n + 1) with self.spoke_labels.hold_sync(): self.spoke_labels.text = [str(row) for row in rows] self.spoke_labels.x = np.sin(t) self.spoke_labels.y = np.cos(t) def update_fill(self, *args): if self.fill: with self.loops.hold_sync(): self.loops.fill = "inside" self.loops.fill_opacities = [0.2] * len(self.loops.y) else: self.loops.fill = "none" self.loops.fill_opacities = [0.0] * len(self.loops.y) def on_legend_click(self, line, target): selected_ix = target["data"]["index"] n = len(line.y) opacities = line.opacities if opacities is None or len(opacities) == 0: opacities = [1.0] * n new_opacities = [0.1] * n new_opacities[selected_ix] = 1 line.opacities = new_opacities def reset(self, line, target): line.opacities = [1.0] * len(line.y)
(**kwargs)
34,628
bqplot.plotting_widgets
__init__
null
def __init__(self, **kwargs): super(Radar, self).__init__(**kwargs) self.scales = {"x": LinearScale(), "y": LinearScale()} # set some defaults for the figure self.layout = Layout(min_width="600px", min_height="600px") self.max_aspect_ratio = 1 self.preserve_aspect = True # marks for the radar figure # spokes (straight lines going away from the center) self.spokes = Lines( scales=self.scales, colors=["#ccc"], stroke_width=0.5 ) # bands self.bands = Lines( colors=["#ccc"], scales=self.scales, stroke_width=0.5 ) # loops of the radar self.loops = Lines( scales=self.scales, display_legend=True, colors=self.colors, stroke_width=2, fill="inside" if self.fill else "none", marker="circle", marker_size=50, ) self.band_labels = Label( scales=self.scales, default_size=12, font_weight="normal", apply_clip=False, colors=["#ccc"], align="middle", ) self.spoke_labels = Label( scales=self.scales, default_size=14, font_weight="bold", apply_clip=False, colors=["#ccc"], align="middle", ) self.marks = [ self.spokes, self.bands, self.loops, self.band_labels, self.spoke_labels, ] # handlers for data updates self.observe(self.update_data, "data") self.observe(self.update_bands, ["band_type", "num_bands"]) self.observe(self.update_fill, "fill") self.loops.on_legend_click(self.on_legend_click) self.loops.on_background_click(self.reset) self.update_bands(None) self.update_data(None)
(self, **kwargs)
34,668
bqplot.plotting_widgets
on_legend_click
null
def on_legend_click(self, line, target): selected_ix = target["data"]["index"] n = len(line.y) opacities = line.opacities if opacities is None or len(opacities) == 0: opacities = [1.0] * n new_opacities = [0.1] * n new_opacities[selected_ix] = 1 line.opacities = new_opacities
(self, line, target)
34,674
bqplot.plotting_widgets
reset
null
def reset(self, line, target): line.opacities = [1.0] * len(line.y)
(self, line, target)
34,690
bqplot.plotting_widgets
update_bands
null
def update_bands(self, *args): band_data = np.linspace( self.data_range[0], self.data_range[1], self.num_bands + 1 ) self.scaled_band_data = ( (band_data - self.data_range[0]) / (self.data_range[1] - self.data_range[0]) )[:, np.newaxis] n = len(self.data.index) if self.band_type == "circle": t = np.linspace(0, 2 * np.pi, 1000) band_data_x, band_data_y = ( self.scaled_band_data * np.cos(t), self.scaled_band_data * np.sin(t), ) elif self.band_type == "polygon": t = np.linspace(0, 2 * np.pi, n + 1) band_data_x, band_data_y = ( self.scaled_band_data * np.sin(t), self.scaled_band_data * np.cos(t), ) with self.bands.hold_sync(): self.bands.x = band_data_x self.bands.y = band_data_y with self.band_labels.hold_sync(): self.band_labels.x = self.scaled_band_data[:, 0] self.band_labels.y = [0.0] * (self.num_bands + 1) self.band_labels.text = ["{:.0%}".format(b) for b in band_data]
(self, *args)
34,691
bqplot.plotting_widgets
update_data
null
def update_data(self, *args): self.update_bands(None) rows = list(self.data.index) n = len(rows) # spokes representing each data set self.spoke_data_t = np.linspace(0, 2 * np.pi, n + 1)[:-1] spoke_data_x, spoke_data_y = ( np.sin(self.spoke_data_t), np.cos(self.spoke_data_t), ) # Update mark data based on data changes with self.spokes.hold_sync(): self.spokes.x = np.column_stack( [self.scaled_band_data[1] * spoke_data_x, spoke_data_x] ) self.spokes.y = np.column_stack( [self.scaled_band_data[1] * spoke_data_y, spoke_data_y] ) scaled_data = (self.data.values - self.data_range[0]) / ( self.data_range[1] - self.data_range[0] ) data_x = scaled_data * np.sin(self.spoke_data_t)[:, np.newaxis] data_y = scaled_data * np.cos(self.spoke_data_t)[:, np.newaxis] # update data lines with self.loops.hold_sync(): self.loops.x = np.column_stack([data_x.T, data_x.T[:, 0]]) self.loops.y = np.column_stack([data_y.T, data_y.T[:, 0]]) if self.fill: self.loops.fill = "inside" self.loops.fill_opacities = [0.2] * len(self.loops.y) else: self.loops.fill = "none" self.loops.fill_opacities = [0.0] * len(self.loops.y) self.loops.labels = [str(c) for c in self.data.columns] # update spoke labels t = np.linspace(0, 2 * np.pi, n + 1) with self.spoke_labels.hold_sync(): self.spoke_labels.text = [str(row) for row in rows] self.spoke_labels.x = np.sin(t) self.spoke_labels.y = np.cos(t)
(self, *args)
34,692
bqplot.plotting_widgets
update_fill
null
def update_fill(self, *args): if self.fill: with self.loops.hold_sync(): self.loops.fill = "inside" self.loops.fill_opacities = [0.2] * len(self.loops.y) else: self.loops.fill = "none" self.loops.fill_opacities = [0.0] * len(self.loops.y)
(self, *args)
34,693
bqplot.scales
Scale
The base scale class. Scale objects represent a mapping between data (the domain) and a visual quantity (The range). Attributes ---------- scale_types: dict (class-level attribute) A registry of existing scale types. domain_class: type (default: Float) traitlet type used to validate values in of the domain of the scale. reverse: bool (default: False) whether the scale should be reversed. allow_padding: bool (default: True) indicates whether figures are allowed to add data padding to this scale or not. precedence: int (class-level attribute) attribute used to determine which scale takes precedence in cases when two or more scales have the same rtype and dtype.
class Scale(Widget): """The base scale class. Scale objects represent a mapping between data (the domain) and a visual quantity (The range). Attributes ---------- scale_types: dict (class-level attribute) A registry of existing scale types. domain_class: type (default: Float) traitlet type used to validate values in of the domain of the scale. reverse: bool (default: False) whether the scale should be reversed. allow_padding: bool (default: True) indicates whether figures are allowed to add data padding to this scale or not. precedence: int (class-level attribute) attribute used to determine which scale takes precedence in cases when two or more scales have the same rtype and dtype. """ scale_types = {} precedence = 1 domain_class = Type(Float) reverse = Bool().tag(sync=True) allow_padding = Bool(True).tag(sync=True) _view_name = Unicode('Scale').tag(sync=True) _model_name = Unicode('ScaleModel').tag(sync=True) _view_module = Unicode('bqplot').tag(sync=True) _model_module = Unicode('bqplot').tag(sync=True) _view_module_version = Unicode(__frontend_version__).tag(sync=True) _model_module_version = Unicode(__frontend_version__).tag(sync=True) _ipython_display_ = None # We cannot display a scale outside of a figure
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
34,750
bqplot.marks
Scatter
Scatter mark. In the case of the Scatter mark, scales for 'x' and 'y' MUST be provided. The scales of other data attributes are optional. In the case where another data attribute than 'x' or 'y' is provided but the corresponding scale is missing, the data attribute is ignored. Attributes ---------- icon: string (class-level attribute) Font-awesome icon for that mark name: string (class-level attribute) User-friendly name of the mark marker: {'circle', 'cross', 'diamond', 'square', 'triangle-down', 'triangle-up', 'arrow', 'rectangle', 'ellipse', 'plus', 'crosshair', 'point'} Marker shape colors: list of colors (default: ['steelblue']) List of colors of the markers. If the list is shorter than the number of points, the colors are reused. default_colors: Deprecated Same as `colors`, deprecated as of version 0.8.4 fill: Bool (default: True) Whether to fill the markers or not stroke: Color or None (default: None) Stroke color of the marker stroke_width: Float (default: 1.5) Stroke width of the marker opacities: list of floats (default: [1.0]) Default opacities of the markers. If the list is shorter than the number of points, the opacities are reused. default_skew: float (default: 0.5) Default skew of the marker. This number is validated to be between 0 and 1. default_size: nonnegative int (default: 64) Default marker size in pixel. If size data is provided with a scale, default_size stands for the maximal marker size (i.e. the maximum value for the 'size' scale range) drag_size: nonnegative float (default: 5.) Ratio of the size of the dragged scatter size to the default scatter size. names: numpy.ndarray (default: None) Labels for the points of the chart display_names: bool (default: True) Controls whether names are displayed for points in the scatter label_display_horizontal_offset: float (default: None) Adds an offset, in pixels, to the horizontal positioning of the 'names' label above each data point label_display_vertical_offset: float (default: None) Adds an offset, in pixels, to the vertical positioning of the 'names' label above each data point enable_move: bool (default: False) Controls whether points can be moved by dragging. Refer to restrict_x, restrict_y for more options. restrict_x: bool (default: False) Restricts movement of the point to only along the x axis. This is valid only when enable_move is set to True. If both restrict_x and restrict_y are set to True, the point cannot be moved. restrict_y: bool (default: False) Restricts movement of the point to only along the y axis. This is valid only when enable_move is set to True. If both restrict_x and restrict_y are set to True, the point cannot be moved. Data Attributes x: numpy.ndarray (default: []) abscissas of the data points (1d array) y: numpy.ndarray (default: []) ordinates of the data points (1d array) color: numpy.ndarray or None (default: None) color of the data points (1d array). Defaults to default_color when not provided or when a value is NaN opacity: numpy.ndarray or None (default: None) opacity of the data points (1d array). Defaults to default_opacity when not provided or when a value is NaN size: numpy.ndarray or None (default: None) size of the data points. Defaults to default_size when not provided or when a value is NaN skew: numpy.ndarray or None (default: None) skewness of the markers representing the data points. Defaults to default_skew when not provided or when a value is NaN rotation: numpy.ndarray or None (default: None) orientation of the markers representing the data points. The rotation scale's range is [0, 180] Defaults to 0 when not provided or when a value is NaN. Notes ----- The fields which can be passed to the default tooltip are: All the data attributes index: index of the marker being hovered on The following are the events which can trigger interactions: click: left click of the mouse hover: mouse-over an element The following are the interactions which can be linked to the above events: tooltip: display tooltip add: add new points to the scatter (can only linked to click)
class Scatter(_ScatterBase): """Scatter mark. In the case of the Scatter mark, scales for 'x' and 'y' MUST be provided. The scales of other data attributes are optional. In the case where another data attribute than 'x' or 'y' is provided but the corresponding scale is missing, the data attribute is ignored. Attributes ---------- icon: string (class-level attribute) Font-awesome icon for that mark name: string (class-level attribute) User-friendly name of the mark marker: {'circle', 'cross', 'diamond', 'square', 'triangle-down', 'triangle-up', 'arrow', 'rectangle', 'ellipse', 'plus', 'crosshair', 'point'} Marker shape colors: list of colors (default: ['steelblue']) List of colors of the markers. If the list is shorter than the number of points, the colors are reused. default_colors: Deprecated Same as `colors`, deprecated as of version 0.8.4 fill: Bool (default: True) Whether to fill the markers or not stroke: Color or None (default: None) Stroke color of the marker stroke_width: Float (default: 1.5) Stroke width of the marker opacities: list of floats (default: [1.0]) Default opacities of the markers. If the list is shorter than the number of points, the opacities are reused. default_skew: float (default: 0.5) Default skew of the marker. This number is validated to be between 0 and 1. default_size: nonnegative int (default: 64) Default marker size in pixel. If size data is provided with a scale, default_size stands for the maximal marker size (i.e. the maximum value for the 'size' scale range) drag_size: nonnegative float (default: 5.) Ratio of the size of the dragged scatter size to the default scatter size. names: numpy.ndarray (default: None) Labels for the points of the chart display_names: bool (default: True) Controls whether names are displayed for points in the scatter label_display_horizontal_offset: float (default: None) Adds an offset, in pixels, to the horizontal positioning of the 'names' label above each data point label_display_vertical_offset: float (default: None) Adds an offset, in pixels, to the vertical positioning of the 'names' label above each data point enable_move: bool (default: False) Controls whether points can be moved by dragging. Refer to restrict_x, restrict_y for more options. restrict_x: bool (default: False) Restricts movement of the point to only along the x axis. This is valid only when enable_move is set to True. If both restrict_x and restrict_y are set to True, the point cannot be moved. restrict_y: bool (default: False) Restricts movement of the point to only along the y axis. This is valid only when enable_move is set to True. If both restrict_x and restrict_y are set to True, the point cannot be moved. Data Attributes x: numpy.ndarray (default: []) abscissas of the data points (1d array) y: numpy.ndarray (default: []) ordinates of the data points (1d array) color: numpy.ndarray or None (default: None) color of the data points (1d array). Defaults to default_color when not provided or when a value is NaN opacity: numpy.ndarray or None (default: None) opacity of the data points (1d array). Defaults to default_opacity when not provided or when a value is NaN size: numpy.ndarray or None (default: None) size of the data points. Defaults to default_size when not provided or when a value is NaN skew: numpy.ndarray or None (default: None) skewness of the markers representing the data points. Defaults to default_skew when not provided or when a value is NaN rotation: numpy.ndarray or None (default: None) orientation of the markers representing the data points. The rotation scale's range is [0, 180] Defaults to 0 when not provided or when a value is NaN. Notes ----- The fields which can be passed to the default tooltip are: All the data attributes index: index of the marker being hovered on The following are the events which can trigger interactions: click: left click of the mouse hover: mouse-over an element The following are the interactions which can be linked to the above events: tooltip: display tooltip add: add new points to the scatter (can only linked to click) """ # Mark decoration icon = 'fa-cloud' name = 'Scatter' # Scaled attributes skew = Array(None, allow_none=True).tag(sync=True, scaled=True, rtype='Number', **array_serialization)\ .valid(array_squeeze, array_dimension_bounds(1, 1)) # Other attributes marker = Enum(['circle', 'cross', 'diamond', 'square', 'triangle-down', 'triangle-up', 'arrow', 'rectangle', 'ellipse', 'plus', 'crosshair', 'point'], default_value='circle').tag(sync=True, display_name='Marker') colors = List(trait=Color(default_value=None, allow_none=True), default_value=['steelblue'])\ .tag(sync=True, display_name='Colors') scales_metadata = Dict({ 'x': {'orientation': 'horizontal', 'dimension': 'x'}, 'y': {'orientation': 'vertical', 'dimension': 'y'}, 'color': {'dimension': 'color'}, 'size': {'dimension': 'size'}, 'opacity': {'dimension': 'opacity'}, 'rotation': {'dimension': 'rotation'}, 'skew': {'dimension': 'skew'} }).tag(sync=True) @property def default_colors(self): return self.colors @default_colors.setter def default_colors(self, value): warn("default_colors is deprecated, use colors instead.", DeprecationWarning) self.colors = value @property def default_opacities(self): return self.opacities @default_opacities.setter def default_opacities(self, value): warn("default_opacities is deprecated, use opacities instead.", DeprecationWarning) self.opacities = value stroke = Color(None, allow_none=True).tag(sync=True, display_name='Stroke color') stroke_width = Float(1.5).tag(sync=True, display_name='Stroke width') default_skew = Float(0.5, min=0, max=1).tag(sync=True) default_size = Int(64).tag(sync=True, display_name='Default size') names = Array(None, allow_none=True)\ .tag(sync=True, **array_serialization).valid(array_squeeze) display_names = Bool(True).tag(sync=True, display_name='Display names') label_display_horizontal_offset = Float(allow_none=True).tag(sync=True) label_display_vertical_offset = Float(allow_none=True).tag(sync=True) fill = Bool(True).tag(sync=True) drag_color = Color(None, allow_none=True).tag(sync=True) drag_size = Float(5.).tag(sync=True) names_unique = Bool(True).tag(sync=True) _view_name = Unicode('Scatter').tag(sync=True) _model_name = Unicode('ScatterModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
34,818
bqplot.marks
ScatterGL
null
class ScatterGL(Scatter): _view_name = Unicode('ScatterGL').tag(sync=True) _model_name = Unicode('ScatterGLModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
34,886
bqplot.scales
Stereographic
A perspective projection that uses a bijective and smooth map at every point except the projection point. The projection is not an equal-area projection but it is conformal. Attributes ---------- scale_factor: float (default: 250) Specifies the scale value for the projection rotate: tuple (default: (96, 0)) Degree of rotation in each axis. center: tuple (default: (0, 60)) Specifies the longitude and latitude where the map is centered. precision: float (default: 0.1) Specifies the threshold for the projections adaptive resampling to the specified value in pixels. clip_angle: float (default: 90.) Specifies the clipping circle radius to the specified angle in degrees.
class Stereographic(GeoScale): """A perspective projection that uses a bijective and smooth map at every point except the projection point. The projection is not an equal-area projection but it is conformal. Attributes ---------- scale_factor: float (default: 250) Specifies the scale value for the projection rotate: tuple (default: (96, 0)) Degree of rotation in each axis. center: tuple (default: (0, 60)) Specifies the longitude and latitude where the map is centered. precision: float (default: 0.1) Specifies the threshold for the projections adaptive resampling to the specified value in pixels. clip_angle: float (default: 90.) Specifies the clipping circle radius to the specified angle in degrees. """ scale_factor = Float(145.0).tag(sync=True) center = Tuple((0, 60)).tag(sync=True) precision = Float(0.1).tag(sync=True) rotate = Tuple((96, 0)).tag(sync=True) clip_angle = Float(179.9999, min=0.0, max=360.0).tag(sync=True) rtype = '(Number, Number)' dtype = np.number _view_name = Unicode('Stereographic').tag(sync=True) _model_name = Unicode('StereographicModel').tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
34,943
bqplot.toolbar
Toolbar
Default toolbar for bqplot figures. The default toolbar provides three buttons: - A *Panzoom* toggle button which enables panning and zooming the figure. - A *Save* button to save the figure as a png image. - A *Reset* button, which resets the figure position to its original state. When the *Panzoom* button is toggled to True for the first time, a new instance of ``PanZoom`` widget is created. The created ``PanZoom`` widget uses the scales of all the marks that are on the figure at this point. When the *PanZoom* widget is toggled to False, the figure retrieves its previous interaction. When the *Reset* button is pressed, the ``PanZoom`` widget is deleted and the figure scales reset to their initial state. We are back to the case where the PanZoom widget has never been set. If new marks are added to the figure after the panzoom button is toggled, and these use new scales, those scales will not be panned or zoomed, unless the reset button is clicked. Attributes ---------- figure: instance of Figure The figure to which the toolbar will apply.
class Toolbar(DOMWidget): """Default toolbar for bqplot figures. The default toolbar provides three buttons: - A *Panzoom* toggle button which enables panning and zooming the figure. - A *Save* button to save the figure as a png image. - A *Reset* button, which resets the figure position to its original state. When the *Panzoom* button is toggled to True for the first time, a new instance of ``PanZoom`` widget is created. The created ``PanZoom`` widget uses the scales of all the marks that are on the figure at this point. When the *PanZoom* widget is toggled to False, the figure retrieves its previous interaction. When the *Reset* button is pressed, the ``PanZoom`` widget is deleted and the figure scales reset to their initial state. We are back to the case where the PanZoom widget has never been set. If new marks are added to the figure after the panzoom button is toggled, and these use new scales, those scales will not be panned or zoomed, unless the reset button is clicked. Attributes ---------- figure: instance of Figure The figure to which the toolbar will apply. """ figure = Instance(Figure).tag(sync=True, **widget_serialization) _panning = Bool(read_only=True).tag(sync=True) _panzoom = Instance(PanZoom, default_value=None, allow_none=True, read_only=True).tag(sync=True, **widget_serialization) _view_name = Unicode('Toolbar').tag(sync=True) _model_name = Unicode('ToolbarModel').tag(sync=True) _view_module = Unicode('bqplot').tag(sync=True) _model_module = Unicode('bqplot').tag(sync=True) _view_module_version = Unicode(__frontend_version__).tag(sync=True) _model_module_version = Unicode(__frontend_version__).tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
35,004
bqplot.default_tooltip
Tooltip
Default tooltip widget for marks. Attributes ---------- fields: list (default: []) list of names of fields to be displayed in the tooltip All the attributes of the mark are accessible in the tooltip formats: list (default: []) list of formats to be applied to each of the fields. if no format is specified for a field, the value is displayed as it is labels: list (default: []) list of labels to be displayed in the table instead of the fields. If the length of labels is less than the length of fields, then the field names are displayed for those fields for which label is missing. show_labels: bool (default: True) Boolean attribute to enable and disable display of the label /field name as the first column along with the value
class Tooltip(DOMWidget): """Default tooltip widget for marks. Attributes ---------- fields: list (default: []) list of names of fields to be displayed in the tooltip All the attributes of the mark are accessible in the tooltip formats: list (default: []) list of formats to be applied to each of the fields. if no format is specified for a field, the value is displayed as it is labels: list (default: []) list of labels to be displayed in the table instead of the fields. If the length of labels is less than the length of fields, then the field names are displayed for those fields for which label is missing. show_labels: bool (default: True) Boolean attribute to enable and disable display of the label /field name as the first column along with the value """ fields = List().tag(sync=True) formats = List().tag(sync=True) show_labels = Bool(True).tag(sync=True) labels = List().tag(sync=True) _view_name = Unicode('Tooltip').tag(sync=True) _model_name = Unicode('TooltipModel').tag(sync=True) _view_module = Unicode('bqplot').tag(sync=True) _model_module = Unicode('bqplot').tag(sync=True) _view_module_version = Unicode(__frontend_version__).tag(sync=True) _model_module_version = Unicode(__frontend_version__).tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
35,095
traitlets.traitlets
Type
A trait whose value must be a subclass of a specified class.
class Type(ClassBasedTraitType[G, S]): """A trait whose value must be a subclass of a specified class.""" if t.TYPE_CHECKING: @t.overload def __init__( self: Type[type, type], default_value: Sentinel | None | str = ..., klass: None | str = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any | None = ..., **kwargs: t.Any, ) -> None: ... @t.overload def __init__( self: Type[type | None, type | None], default_value: Sentinel | None | str = ..., klass: None | str = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any | None = ..., **kwargs: t.Any, ) -> None: ... @t.overload def __init__( self: Type[S, S], default_value: S = ..., klass: S = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any | None = ..., **kwargs: t.Any, ) -> None: ... @t.overload def __init__( self: Type[S | None, S | None], default_value: S | None = ..., klass: S = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any | None = ..., **kwargs: t.Any, ) -> None: ... def __init__( self, default_value: t.Any = Undefined, klass: t.Any = None, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, config: t.Any | None = None, **kwargs: t.Any, ) -> None: """Construct a Type trait A Type trait specifies that its values must be subclasses of a particular class. If only ``default_value`` is given, it is used for the ``klass`` as well. If neither are given, both default to ``object``. Parameters ---------- default_value : class, str or None The default value must be a subclass of klass. If an str, the str must be a fully specified class name, like 'foo.bar.Bah'. The string is resolved into real class, when the parent :class:`HasTraits` class is instantiated. klass : class, str [ default object ] Values of this trait must be a subclass of klass. The klass may be specified in a string like: 'foo.bar.MyClass'. The string is resolved into real class, when the parent :class:`HasTraits` class is instantiated. allow_none : bool [ default False ] Indicates whether None is allowed as an assignable value. **kwargs extra kwargs passed to `ClassBasedTraitType` """ if default_value is Undefined: new_default_value = object if (klass is None) else klass else: new_default_value = default_value if klass is None: if (default_value is None) or (default_value is Undefined): klass = object else: klass = default_value if not (inspect.isclass(klass) or isinstance(klass, str)): raise TraitError("A Type trait must specify a class.") self.klass = klass super().__init__( new_default_value, allow_none=allow_none, read_only=read_only, help=help, config=config, **kwargs, ) def validate(self, obj: t.Any, value: t.Any) -> G: """Validates that the value is a valid object instance.""" if isinstance(value, str): try: value = self._resolve_string(value) except ImportError as e: raise TraitError( f"The '{self.name}' trait of {obj} instance must be a type, but " f"{value!r} could not be imported" ) from e try: if issubclass(value, self.klass): # type:ignore[arg-type] return t.cast(G, value) except Exception: pass self.error(obj, value) def info(self) -> str: """Returns a description of the trait.""" if isinstance(self.klass, str): klass = self.klass else: klass = self.klass.__module__ + "." + self.klass.__name__ result = "a subclass of '%s'" % klass if self.allow_none: return result + " or None" return result def instance_init(self, obj: t.Any) -> None: # we can't do this in subclass_init because that # might be called before all imports are done. self._resolve_classes() def _resolve_classes(self) -> None: if isinstance(self.klass, str): self.klass = self._resolve_string(self.klass) if isinstance(self.default_value, str): self.default_value = self._resolve_string(self.default_value) def default_value_repr(self) -> str: value = self.default_value assert value is not None if isinstance(value, str): return repr(value) else: return repr(f"{value.__module__}.{value.__name__}")
(default_value: Any = traitlets.Undefined, klass: 't.Any' = None, allow_none: bool = False, read_only: bool = None, help: 'str | None' = None, config: 't.Any | None' = None, **kwargs: 't.Any') -> 'None'
35,097
traitlets.traitlets
__init__
Construct a Type trait A Type trait specifies that its values must be subclasses of a particular class. If only ``default_value`` is given, it is used for the ``klass`` as well. If neither are given, both default to ``object``. Parameters ---------- default_value : class, str or None The default value must be a subclass of klass. If an str, the str must be a fully specified class name, like 'foo.bar.Bah'. The string is resolved into real class, when the parent :class:`HasTraits` class is instantiated. klass : class, str [ default object ] Values of this trait must be a subclass of klass. The klass may be specified in a string like: 'foo.bar.MyClass'. The string is resolved into real class, when the parent :class:`HasTraits` class is instantiated. allow_none : bool [ default False ] Indicates whether None is allowed as an assignable value. **kwargs extra kwargs passed to `ClassBasedTraitType`
def __init__( self, default_value: t.Any = Undefined, klass: t.Any = None, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, config: t.Any | None = None, **kwargs: t.Any, ) -> None: """Construct a Type trait A Type trait specifies that its values must be subclasses of a particular class. If only ``default_value`` is given, it is used for the ``klass`` as well. If neither are given, both default to ``object``. Parameters ---------- default_value : class, str or None The default value must be a subclass of klass. If an str, the str must be a fully specified class name, like 'foo.bar.Bah'. The string is resolved into real class, when the parent :class:`HasTraits` class is instantiated. klass : class, str [ default object ] Values of this trait must be a subclass of klass. The klass may be specified in a string like: 'foo.bar.MyClass'. The string is resolved into real class, when the parent :class:`HasTraits` class is instantiated. allow_none : bool [ default False ] Indicates whether None is allowed as an assignable value. **kwargs extra kwargs passed to `ClassBasedTraitType` """ if default_value is Undefined: new_default_value = object if (klass is None) else klass else: new_default_value = default_value if klass is None: if (default_value is None) or (default_value is Undefined): klass = object else: klass = default_value if not (inspect.isclass(klass) or isinstance(klass, str)): raise TraitError("A Type trait must specify a class.") self.klass = klass super().__init__( new_default_value, allow_none=allow_none, read_only=read_only, help=help, config=config, **kwargs, )
(self, default_value: Any = traitlets.Undefined, klass: Optional[Any] = None, allow_none: bool = False, read_only: Optional[bool] = None, help: Optional[str] = None, config: Optional[Any] = None, **kwargs: Any) -> NoneType
35,101
traitlets.traitlets
_resolve_classes
null
def _resolve_classes(self) -> None: if isinstance(self.klass, str): self.klass = self._resolve_string(self.klass) if isinstance(self.default_value, str): self.default_value = self._resolve_string(self.default_value)
(self) -> NoneType
35,106
traitlets.traitlets
default_value_repr
null
def default_value_repr(self) -> str: value = self.default_value assert value is not None if isinstance(value, str): return repr(value) else: return repr(f"{value.__module__}.{value.__name__}")
(self) -> str
35,112
traitlets.traitlets
info
Returns a description of the trait.
def info(self) -> str: """Returns a description of the trait.""" if isinstance(self.klass, str): klass = self.klass else: klass = self.klass.__module__ + "." + self.klass.__name__ result = "a subclass of '%s'" % klass if self.allow_none: return result + " or None" return result
(self) -> str
35,119
traitlets.traitlets
validate
Validates that the value is a valid object instance.
def validate(self, obj: t.Any, value: t.Any) -> G: """Validates that the value is a valid object instance.""" if isinstance(value, str): try: value = self._resolve_string(value) except ImportError as e: raise TraitError( f"The '{self.name}' trait of {obj} instance must be a type, but " f"{value!r} could not be imported" ) from e try: if issubclass(value, self.klass): # type:ignore[arg-type] return t.cast(G, value) except Exception: pass self.error(obj, value)
(self, obj: Any, value: Any) -> ~G
35,200
bqplot
_jupyter_labextension_paths
null
def _jupyter_labextension_paths(): return [{ 'src': f'{_prefix()}/share/jupyter/labextensions/bqplot/', 'dest': 'bqplot', }]
()
35,201
bqplot
_jupyter_nbextension_paths
null
def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': f'{_prefix()}/share/jupyter/nbextensions/bqplot/', 'dest': 'bqplot', 'require': 'bqplot/extension' }]
()
35,202
bqplot
_prefix
null
def _prefix(): import sys from pathlib import Path prefix = sys.prefix here = Path(__file__).parent # for when in dev mode if (here.parent / 'share/jupyter/nbextensions/bqplot').parent.exists(): prefix = here.parent return prefix
()
35,204
bqplot.traits
array_dimension_bounds
null
def array_dimension_bounds(mindim=0, maxdim=np.inf): def validator(trait, value): dim = len(value.shape) if dim < mindim or dim > maxdim: raise TraitError('Dimension mismatch for trait %s of class %s: expected an \ array of dimension comprised in interval [%s, %s] and got an array of shape %s' % ( trait.name, trait.this_class, mindim, maxdim, value.shape)) return value return validator
(mindim=0, maxdim=inf)