pltstat 0.11.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pltstat/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ # Author: Dmitrii Beregovoi
2
+ # License: BSD 3-Clause License, see LICENSE file
3
+
4
+ # Copyright: (c) 2025 Dmitrii Beregovoi
5
+
6
+ from . import config
7
+ from .config import backend, get_backend, set_backend
8
+
9
+ __version__ = "0.11.0"
10
+ __author__ = "Dmitrii Beregovoi"
11
+ __email__ = "dimaforth@gmail.com"
12
+ __all__ = [
13
+ "__version__",
14
+ "config",
15
+ "backend",
16
+ "get_backend",
17
+ "set_backend",
18
+ "stat_methods",
19
+ "cm",
20
+ "circle",
21
+ "in_out",
22
+ "singlefeat",
23
+ "twofeats",
24
+ "multfeats",
25
+ ]
pltstat/circle.py ADDED
@@ -0,0 +1,551 @@
1
+ """
2
+ Contains functions and methods related to circular statistical visualizations,
3
+ such as radar charts or circular histograms.
4
+ """
5
+
6
+ import matplotlib.pyplot as plt
7
+ from matplotlib import ticker
8
+ import numpy as np
9
+ import seaborn as sns
10
+
11
+ from .config import _figsize_to_px, _import_plotly, _resolve_engine, _warn_ignored_mpl_params
12
+
13
+
14
+ _HIGH = 24
15
+ _N_BINS = 24
16
+ _N_TICKS = 24
17
+
18
+
19
+ def rad2val(a, high=_HIGH):
20
+ """
21
+ Convert values ``a`` from radians to measures with the highest value ``high``
22
+
23
+ Parameters
24
+ ----------
25
+ a : array_like
26
+ Input array in radians
27
+ high : float or int
28
+ High boundary for the sample range
29
+
30
+ Returns
31
+ -------
32
+ rad2val : ndarray
33
+ The corresponding values with `high` boundary. This is a scalar if ``a`` is a scalar.
34
+
35
+ Example
36
+ --------
37
+ >>> import numpy as np
38
+ >>> from pltstat.circle import rad2val
39
+
40
+ >>> a = [0, np.pi, 4, 8]
41
+ >>> rad2val(a, high=24)
42
+ array([ 0., 12., 15.27887454, 30.55774907])
43
+ """
44
+ a = np.array(a)
45
+ a = a / np.pi / 2 * high
46
+ return a
47
+
48
+
49
+ def val2rad(a, high=_HIGH):
50
+ """
51
+ Convert values `a` from measures with the highest value `high` to radians
52
+
53
+ Parameters
54
+ ----------
55
+ a : array_like
56
+ Input array in measures with the ``high`` boundary fot the sample range
57
+ high : float or int
58
+ High boundary for the sample range
59
+
60
+ Returns
61
+ -------
62
+ rad2val : ndarray
63
+ The corresponding radian values. This is a scalar if ``a`` is a scalar.
64
+
65
+ Example
66
+ --------
67
+ >>> import numpy as np
68
+ >>> from pltstat.circle import val2rad
69
+
70
+ >>> a = [0, 3, 19, 25]
71
+ >>> val2rad(a, high=24)
72
+ array([0., 0.78539816, 4.97418837, 6.54498469])
73
+
74
+ >>> val2rad(a, high=24) / np.pi
75
+ array([0., 0.25, 1.58333333, 2.08333333])
76
+ """
77
+ a = np.array(a)
78
+ a = a / high * 2 * np.pi
79
+ return a
80
+
81
+
82
+ def _hist_yticks(a, bins):
83
+ """
84
+ Get the radial ticks matplotlib chooses for a circular histogram.
85
+
86
+ Parameters
87
+ ----------
88
+ a : array_like
89
+ Input array in radians.
90
+ bins : array_like
91
+ Edges of the bins, in radians.
92
+
93
+ Returns
94
+ -------
95
+ yticks : np.ndarray
96
+ Positions of the radial ticks, before any offset is added.
97
+
98
+ Notes
99
+ -----
100
+ The ticks are read from a throwaway polar figure, which is closed right
101
+ away. Matplotlib pads the radial axis past the tallest bin in a way that
102
+ a locator alone does not reproduce, so drawing is the reliable way to get
103
+ the very same ticks with either engine.
104
+ """
105
+ fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
106
+ ax.hist(a, bins=bins, edgecolor="black")
107
+ yticks = ax.axes.yaxis.get_ticklocs()
108
+ plt.close(fig)
109
+
110
+ return yticks
111
+
112
+
113
+ def _hist_plotly(counts, bins, theta, yticks, bottom, high, title, figsize=None):
114
+ """
115
+ Draw a circular histogram with plotly.
116
+
117
+ Parameters
118
+ ----------
119
+ counts : np.ndarray
120
+ Number of observations in every bin.
121
+ bins : np.ndarray
122
+ Edges of the bins, in radians.
123
+ theta : np.ndarray
124
+ Positions of the ticks of the angular axis, in radians.
125
+ yticks : np.ndarray
126
+ Positions of the radial ticks, before the offset is added.
127
+ bottom : float
128
+ Radial offset of the bins, which hollows the centre of the circle.
129
+ high : float or int
130
+ High boundary of the sample range, used to label the angular axis.
131
+ title : str or None
132
+ Title of the chart.
133
+ figsize : tuple or None, default: None
134
+ Size of the figure in inches, converted to pixels.
135
+
136
+ Returns
137
+ -------
138
+ fig : plotly.graph_objects.Figure
139
+ The circular histogram.
140
+
141
+ Notes
142
+ -----
143
+ Plotly measures the angles in degrees while matplotlib uses radians, so
144
+ the angles are converted here. Setting the angular axis to start at the
145
+ top and to run clockwise matches ``theta_offset`` and ``theta_direction``
146
+ of matplotlib.
147
+ """
148
+ go, _ = _import_plotly()
149
+ width, height = _figsize_to_px(figsize)
150
+
151
+ centers = (bins[:-1] + bins[1:]) / 2
152
+
153
+ fig = go.Figure(
154
+ go.Barpolar(
155
+ r=counts,
156
+ theta=np.degrees(centers),
157
+ width=np.degrees(np.diff(bins)),
158
+ base=bottom,
159
+ marker={"line": {"color": "black", "width": 1}},
160
+ hovertemplate="count = %{r}<extra></extra>",
161
+ )
162
+ )
163
+ fig.update_layout(
164
+ title=title,
165
+ width=width,
166
+ height=height,
167
+ polar={
168
+ "angularaxis": {
169
+ "rotation": 90,
170
+ "direction": "clockwise",
171
+ "tickmode": "array",
172
+ "tickvals": np.degrees(theta),
173
+ "ticktext": [f"{value / np.pi / 2 * high:.3g}" for value in theta],
174
+ },
175
+ "radialaxis": {
176
+ "tickmode": "array",
177
+ "tickvals": yticks + bottom,
178
+ "ticktext": [f"{value:g}" for value in yticks],
179
+ },
180
+ },
181
+ )
182
+
183
+ return fig
184
+
185
+
186
+ def _scatter_plotly(rads, y, theta, high, title, y_range, figsize=None):
187
+ """
188
+ Draw a scatter plot of a circular dataset with plotly.
189
+
190
+ Parameters
191
+ ----------
192
+ rads : np.ndarray
193
+ Angle of every point, in radians.
194
+ y : array_like
195
+ Radius of every point.
196
+ theta : np.ndarray
197
+ Positions of the ticks of the angular axis, in radians.
198
+ high : float or int
199
+ High boundary of the sample range, used to label the angular axis.
200
+ title : str or None
201
+ Title of the chart.
202
+ y_range : tuple[float, float]
203
+ Lowest and highest radius drawn, which pads the points.
204
+ figsize : tuple or None, default: None
205
+ Size of the figure in inches, converted to pixels.
206
+
207
+ Returns
208
+ -------
209
+ fig : plotly.graph_objects.Figure
210
+ The scatter plot.
211
+
212
+ Notes
213
+ -----
214
+ Plotly measures the angles in degrees while matplotlib uses radians, so
215
+ the angles are converted here.
216
+ """
217
+ go, _ = _import_plotly()
218
+ width, height = _figsize_to_px(figsize)
219
+
220
+ fig = go.Figure(
221
+ go.Scatterpolar(
222
+ r=y,
223
+ theta=np.degrees(rads),
224
+ mode="markers",
225
+ hovertemplate="%{r}<extra></extra>",
226
+ )
227
+ )
228
+ fig.update_layout(
229
+ title=title,
230
+ width=width,
231
+ height=height,
232
+ showlegend=False,
233
+ polar={
234
+ "angularaxis": {
235
+ "rotation": 90,
236
+ "direction": "clockwise",
237
+ "tickmode": "array",
238
+ "tickvals": np.degrees(theta),
239
+ "ticktext": [f"{value / np.pi / 2 * high:.3g}" for value in theta],
240
+ },
241
+ "radialaxis": {"range": list(y_range)},
242
+ },
243
+ )
244
+
245
+ return fig
246
+
247
+
248
+ def hist(
249
+ a, n_bins=_N_BINS, high=_HIGH, bottom=0.1, title=None, figsize=None, ax=None, return_ax=False,
250
+ engine=None, **kwargs,
251
+ ):
252
+ if n_bins < 2:
253
+ raise ValueError("Received an invalid number of bins. Number of bins must be at least 2, and must be an int.")
254
+
255
+ a = a / high * 2 * np.pi # h to rad
256
+
257
+ def radian_function(x, y):
258
+ """Helper function for labeling the x-axis"""
259
+ rad_x = x / np.pi / 2
260
+ return f"{(rad_x * high):.3g}"
261
+
262
+ engine = _resolve_engine(engine)
263
+
264
+ theta = np.linspace(0, 2 * np.pi, n_bins, endpoint=False)
265
+ bins = np.linspace(0, 2 * np.pi, n_bins + 1, endpoint=True)
266
+
267
+ counts = np.histogram(a, bins=bins, **kwargs)[0]
268
+ max_bin = counts.max()
269
+ bottom = max_bin * bottom
270
+
271
+ # get yticks:
272
+ yticks = _hist_yticks(a, bins)
273
+
274
+ if engine == "plotly":
275
+ _warn_ignored_mpl_params(engine, ax=ax, return_ax=return_ax)
276
+ return _hist_plotly(
277
+ counts, bins, theta, yticks, bottom, high, title, figsize=figsize
278
+ )
279
+
280
+ if ax is None:
281
+ fig, ax = plt.subplots(subplot_kw={"projection": "polar"}, figsize=figsize)
282
+ # ax = plt.subplot(111, polar=True)
283
+
284
+ ax.hist(a, bins=bins, edgecolor="black", bottom=bottom, **kwargs)
285
+
286
+ # arrange graph
287
+ ax.set(
288
+ theta_offset=np.pi / 2,
289
+ theta_direction=-1,
290
+ xticks=theta,
291
+ yticks=yticks + bottom,
292
+ yticklabels=yticks,
293
+ )
294
+ ax.xaxis.set_major_formatter(ticker.FuncFormatter(radian_function))
295
+ ax.set_title(title)
296
+ if return_ax:
297
+ return ax
298
+
299
+ return None
300
+
301
+
302
+ hist.__doc__ = """\
303
+ Plot histogram to show distributions of circular datasets.
304
+
305
+ Parameters
306
+ ----------
307
+ a : array_like
308
+ Input array in measures with the ``high`` boundary for the sample range.
309
+ n_bins : int, default: {n_bins}
310
+ The number of bins to produce. Raises ValueError if ``n_bins < 2``.
311
+ high : float or int, default: {high}
312
+ High boundary for the sample range.
313
+ bottom : float, default: 0.1
314
+ Proportion of location of the bottom of each bin, where 0 is center of the circle, and 1 is the edge.
315
+ Bins are drawn from ``bottom * max(bins)`` to ``bottom * max(bins) + hist(x, bins)``.
316
+ Valid range is [0, 1].
317
+ title : str or None, default: None
318
+ Text to use for the title.
319
+ figsize : (float, float) or None, default: None
320
+ Width, height in inches.
321
+ ax : :class:`matplotlib.axes.Axes` or array of Axes or None, default: None
322
+ Axes object to draw the plot onto, otherwise uses the current Axes. If ``ax`` is None, create nex ``ax``.
323
+ return_ax : bool, default: False
324
+ Show, it is necessary to return ``ax``.
325
+ Ignored when ``engine="plotly"``, which always returns the figure.
326
+ engine : {{"matplotlib", "plotly"}} or None, default: None
327
+ The rendering engine. If None, the engine set by
328
+ :func:`pltstat.set_backend` is used.
329
+ kwargs : key, value mappings
330
+ Other keywords arguments are passed down to :meth:`maptplotlib.axes.Axes.hist`.
331
+
332
+ Returns
333
+ -------
334
+ ax : :class:`matplotlib.axes.Axes` or array of Axes or :class:`plotly.graph_objects.Figure`
335
+ Returns the Axes object with the plot drawn onto it if ``return_ax argument`` is ``True``.
336
+ Returns the plotly Figure when ``engine="plotly"``.
337
+
338
+ Example
339
+ --------
340
+ >>> import numpy as np
341
+ >>> from pltstat.circle import hist
342
+ >>> np.random.seed(0)
343
+ >>> a = np.random.randint(0, 24, 30)
344
+ >>> a
345
+ array([ 6, 23, 11, 14, 18, 0, 14, 3, 21, 12, 10, 20, 11, 4, 6, 4, 15,
346
+ 20, 3, 12, 4, 20, 8, 14, 15, 20, 3, 23, 15, 13])
347
+ >>> hist(a, 12)""".format(n_bins=_N_BINS, high=_HIGH)
348
+
349
+
350
+ def mean(a, high=_HIGH, atol=1e-10):
351
+ # to rad
352
+ a = np.array(a) / high * 2 * np.pi
353
+
354
+ # cos, sin, radius and mean
355
+ c = np.mean(np.cos(a))
356
+ s = np.mean(np.sin(a))
357
+ r = np.sqrt(c ** 2 + s ** 2)
358
+
359
+ # if radius is 0 than it is not possible to calculate mean value
360
+ # 1e-10 for 7 signs after dot accuracy
361
+ if np.isclose(r, 0, atol=atol):
362
+ return np.nan
363
+
364
+ tau = np.arctan2(s, c)
365
+
366
+ # return from rad
367
+ tau = tau / np.pi / 2 * high
368
+ if tau < 0:
369
+ tau += high
370
+ # instead of elif, because-1.614809932057922e-15 + 360 => 360, for example a=[10, 350], high=360:
371
+ if tau >= high:
372
+ tau -= high
373
+ return tau
374
+
375
+
376
+ mean.__doc__ = """\
377
+ Compute the circular mean for samples in a range.
378
+ The function shows more accurate result than :meth:`scipy.stats.circmean`
379
+
380
+ Parameters
381
+ ----------
382
+ a : array_like
383
+ Input array in measures with the ``high`` boundary for the sample range.
384
+ high : float or int, default: {high}
385
+ High boundary for the sample range.
386
+ atol : float, default: 1e-10
387
+ The threshold for radius calculation. If the radius is less than ``atol``, it will be set to 0 and the mean value
388
+ will be NaN. When the radius is 0, it is not possible to calculate the mean value. If the radius is close to 0,
389
+ the mean value can be extremly inaccurate.
390
+ An ``atol`` equal to ``1e-10`` ensures a mean value accurate to approximately 7 decimal places.
391
+
392
+ Returns
393
+ -------
394
+ mean : float
395
+ Circular mean
396
+
397
+ Examples
398
+ --------
399
+ >>> import numpy as np
400
+ >>> from pltstat.circle import mean
401
+ >>> from scipy.stats import circmean
402
+ >>> a = [10, 350]
403
+ >>> mean(a, 360)
404
+ 0.0
405
+ >>> circmean(a, 360)
406
+ 359.99999999999994""".format(high=_HIGH)
407
+
408
+
409
+ def std(a, high=_HIGH):
410
+ # to rad
411
+ a = np.array(a) / high * 2 * np.pi
412
+
413
+ # cos, sin, radius and mean
414
+ c = np.mean(np.cos(a))
415
+ s = np.mean(np.sin(a))
416
+ r = np.sqrt(c ** 2 + s ** 2)
417
+
418
+ # if radius is 0 than it is not possible to calculate mean value
419
+ # 1e-10 for 7 signs after dot accuracy
420
+ # if np.isclose(r, 0, atol=1e-10):
421
+ # return np.nan
422
+
423
+ v = np.sqrt(-2 * np.log(r))
424
+
425
+ # return from rad
426
+ v = v / np.pi / 2 * high
427
+ return v
428
+
429
+
430
+ std.__doc__ = """\
431
+ Compute the circular standard deviation for samples in a range.
432
+
433
+ Parameters
434
+ ----------
435
+ a : array_like
436
+ Input array in measures with the ``high`` boundary for the sample range.
437
+ high : float or int, default: {high}
438
+ High boundary for the sample range.
439
+
440
+ Returns
441
+ -------
442
+ std : float
443
+ Circular standard deviation
444
+
445
+ Examples
446
+ --------
447
+ >>> import numpy as np
448
+ >>> from pltstat.circle import std
449
+ >>> from scipy.stats import circstd
450
+ >>> a = [10, 350]
451
+ >>> std(a, 360)
452
+ 10.0255602484647
453
+ >>> circstd(a, 360)
454
+ 10.025560248464737""".format(high=_HIGH)
455
+
456
+
457
+ def scatter(
458
+ deg, y, high=_HIGH, n_ticks=_N_TICKS, title=None, figsize=None, ax=None, return_ax=False,
459
+ engine=None, **kwargs
460
+ ):
461
+ BOTTOM_EDGE = 0.2
462
+ UPPER_EDGE = 0.1
463
+
464
+ rads = deg / high * 2 * np.pi # h to rad
465
+ theta = np.linspace(0, 2 * np.pi, n_ticks, endpoint=False)
466
+
467
+ def radian_function(x, y):
468
+ """Helper function for labeling the x-axis"""
469
+ rad_x = x / np.pi / 2
470
+ return f"{(rad_x * high):.3g}"
471
+
472
+ engine = _resolve_engine(engine)
473
+
474
+ y_max = max(y)
475
+ y_min = min(y)
476
+ y_diff = y_max - y_min
477
+ y_range = (y_min - y_diff * BOTTOM_EDGE, y_max + y_diff * UPPER_EDGE)
478
+
479
+ if engine == "plotly":
480
+ _warn_ignored_mpl_params(engine, ax=ax, return_ax=return_ax)
481
+ return _scatter_plotly(rads, y, theta, high, title, y_range, figsize=figsize)
482
+
483
+ if ax is None:
484
+ fig, ax = plt.subplots(subplot_kw={"projection": "polar"}, figsize=figsize)
485
+
486
+ sns.scatterplot(x=rads, y=y, ax=ax, **kwargs)
487
+ ax.set_ylim(y_range)
488
+
489
+ # arrange graph
490
+ ax.set(
491
+ theta_offset=np.pi / 2,
492
+ theta_direction=-1,
493
+ xticks=theta,
494
+ # yticks=yticks,
495
+ # yticklabels=yticks,
496
+ )
497
+ ax.xaxis.set_major_formatter(ticker.FuncFormatter(radian_function))
498
+ ax.set_title(title)
499
+ if return_ax:
500
+ return ax
501
+
502
+ return None
503
+
504
+
505
+ scatter.__doc__ = """\
506
+ Draw a scatter plot of circular datasets.
507
+
508
+ Parameters
509
+ ----------
510
+ deg : array_like
511
+ Variables that specify positions on the angle axis.
512
+ y : array_like
513
+ Variables that specify positions on the y axis.
514
+ high : float or int, default: {high}
515
+ High boundary for the sample range.
516
+ n_ticks : int, default: {n_ticks}
517
+ The number of angle ticks to produce.
518
+ ax : :class:`matplotlib.axes.Axes` or array of Axes or None, default: None
519
+ Axes object to draw the plot onto, otherwise uses the current Axes. If ``ax`` is None, create nex ``ax``.
520
+ return_ax : bool, default: False
521
+ Show, it is necessary to return ``ax``.
522
+ Ignored when ``engine="plotly"``, which always returns the figure.
523
+ engine : {{"matplotlib", "plotly"}} or None, default: None
524
+ The rendering engine. If None, the engine set by
525
+ :func:`pltstat.set_backend` is used.
526
+ kwargs : key, value mappings
527
+ Other keywords arguments are passed down to :meth:`seaborn.scatterplot`.
528
+
529
+ Returns
530
+ -------
531
+ ax : :class:`matplotlib.axes.Axes` or array of Axes
532
+ Returns the Axes object with the plot drawn onto it if ``return_ax argument`` is ``True``.
533
+
534
+
535
+ :return: ax if return_ax is True, else - return None
536
+
537
+ Example
538
+ --------
539
+ >>> import numpy as np
540
+ >>> from pltstat.circle import scatter
541
+ >>> np.random.seed(0)
542
+ >>> deg = np.linspace(0, 24, 20, endpoint=False)
543
+ >>> deg
544
+ array([ 0. , 1.2, 2.4, 3.6, 4.8, 6. , 7.2, 8.4, 9.6, 10.8, 12. ,
545
+ 13.2, 14.4, 15.6, 16.8, 18. , 19.2, 20.4, 21.6, 22.8])
546
+ >>> temp = np.concatenate((np.repeat([36.6], 10), np.linspace(36.6, 40, 10, endpoint=False)))
547
+ >>> temp
548
+ array([36.6 , 36.6 , 36.6 , 36.6 , 36.6 , 36.6 , 36.6 , 36.6 , 36.6 ,
549
+ 36.6 , 36.6 , 36.94, 37.28, 37.62, 37.96, 38.3 , 38.64, 38.98,
550
+ 39.32, 39.66])
551
+ >>> scatter(deg, temp, s=20, marker='o')""".format(n_ticks=_N_TICKS, high=_HIGH)