29
29
from numpy import VisibleDeprecationWarning
30
30
31
31
import matplotlib
32
- from matplotlib import _api , _c_internal_utils
32
+ from matplotlib import _api , _c_internal_utils , mlab
33
33
34
34
35
35
class _ExceptionInfo :
@@ -1430,7 +1430,7 @@ def _reshape_2D(X, name):
1430
1430
return result
1431
1431
1432
1432
1433
- def violin_stats (X , method , points = 100 , quantiles = None ):
1433
+ def violin_stats (X , method = ( "GaussianKDE" , "scott" ) , points = 100 , quantiles = None ):
1434
1434
"""
1435
1435
Return a list of dictionaries of data which can be used to draw a series
1436
1436
of violin plots.
@@ -1449,11 +1449,23 @@ def violin_stats(X, method, points=100, quantiles=None):
1449
1449
Sample data that will be used to produce the gaussian kernel density
1450
1450
estimates. Must have 2 or fewer dimensions.
1451
1451
1452
- method : callable
1452
+ method : (name, bw_method) or callable,
1453
1453
The method used to calculate the kernel density estimate for each
1454
- column of data. When called via ``method(v, coords)``, it should
1455
- return a vector of the values of the KDE evaluated at the values
1456
- specified in coords.
1454
+ column of data. Valid values:
1455
+
1456
+ - a tuple of the form ``(name, bw_method)`` where *name* currently must
1457
+ always be ``"GaussianKDE"`` and *bw_method* is the method used to
1458
+ calculate the estimator bandwidth. Supported values are 'scott',
1459
+ 'silverman' or a float or a callable. If a float, this will be used
1460
+ directly as `!kde.factor`. If a callable, it should take a
1461
+ `matplotlib.mlab.GaussianKDE` instance as its only parameter and
1462
+ return a float.
1463
+
1464
+ - a callable with the signature ::
1465
+
1466
+ def method(data: ndarray, coords: ndarray) -> ndarray
1467
+
1468
+ It should return the KDE of *data* evaluated at *coords*.
1457
1469
1458
1470
points : int, default: 100
1459
1471
Defines the number of points to evaluate each of the gaussian kernel
@@ -1481,6 +1493,19 @@ def violin_stats(X, method, points=100, quantiles=None):
1481
1493
- max: The maximum value for this column of data.
1482
1494
- quantiles: The quantile values for this column of data.
1483
1495
"""
1496
+ if isinstance (method , tuple ):
1497
+ name , bw_method = method
1498
+ if name != "GaussianKDE" :
1499
+ raise ValueError (f"Unknown method { name !r} for violin_stats" )
1500
+
1501
+ def _kde_method (x , coords ):
1502
+ # fallback gracefully if the vector contains only one value
1503
+ if np .all (x [0 ] == x ):
1504
+ return (x [0 ] == coords ).astype (float )
1505
+ kde = mlab .GaussianKDE (x , bw_method )
1506
+ return kde .evaluate (coords )
1507
+
1508
+ method = _kde_method
1484
1509
1485
1510
# List of dictionaries describing each of the violins.
1486
1511
vpstats = []
0 commit comments