pltstat 0.9.5__tar.gz

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.

Potentially problematic release.


This version of pltstat might be problematic. Click here for more details.

pltstat-0.9.5/PKG-INFO ADDED
@@ -0,0 +1,218 @@
1
+ Metadata-Version: 2.1
2
+ Name: pltstat
3
+ Version: 0.9.5
4
+ Summary: A Python Library for Statistical Data Visualization
5
+ Home-page: https://github.com/trojanskehesten/pltstat
6
+ Download-URL: https://github.com/trojanskehesten/pltstat/archive/refs/tags/v0.9.5.zip
7
+ Author: Dmitrii Beregovoi
8
+ Author-email: dimaforth@gmail.com
9
+ License: BSD 3-Clause License, see LICENSE file
10
+ Keywords: matplotlib,statistics,visualization,dataanalysis
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: BSD License
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Topic :: Scientific/Engineering :: Visualization
19
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Classifier: Natural Language :: English
22
+ Requires-Python: ==3.12
23
+ Description-Content-Type: text/markdown
24
+ Requires-Dist: numpy
25
+ Requires-Dist: pandas
26
+ Requires-Dist: matplotlib
27
+ Requires-Dist: seaborn
28
+ Requires-Dist: rpy2
29
+ Requires-Dist: umap-learn
30
+ Requires-Dist: scipy
31
+ Requires-Dist: scikit-learn
32
+ Requires-Dist: phik
33
+
34
+ # pltstat: A Python Library for Statistical Data Visualization
35
+
36
+ `pltstat` is a Python library designed to facilitate the visualization of statistical data analysis. This library includes a variety of tools and methods to streamline data exploration, statistical computation, and graphical representation.
37
+
38
+ ---
39
+
40
+ ## Installation
41
+
42
+ ### Requirements
43
+
44
+ Before installing, make sure that:
45
+
46
+ 1. You are using **Python 3.12**. You can check your Python version by running:
47
+
48
+ ```bash
49
+ python --version
50
+ ```
51
+
52
+ You can download it from the [official Python website](https://www.python.org/downloads/release/python-3120/).
53
+
54
+ 2. **R language** is installed on your system, as the `rpy2` library (used in this project) requires it. You can download R from the [official R website](https://cloud.r-project.org/).
55
+
56
+ Check the installed version of R:
57
+
58
+ ```bash
59
+ R --version
60
+ ```
61
+
62
+ 3. Verify that the `R_HOME` environment variable is correctly set and that R is accessible from the command line:
63
+
64
+ ```bash
65
+ python -c "import os; print(os.getenv('R_HOME'))"
66
+ ```
67
+
68
+ 4. Setting Up `R_HOME` (if needed)
69
+
70
+ - **Windows**:
71
+ 1. Locate the R installation directory (e.g., `C:\Program Files\R\R-4.x.x`).
72
+ 2. Add the path to `R_HOME`:
73
+ - Open "System Properties" > "Environment Variables."
74
+ - Under "System Variables," click "New" or "Edit" and set:
75
+ - **Variable name**: `R_HOME`
76
+ - **Variable value**: Path to your R directory (e.g., `C:\Program Files\R\R-4.x.x`).
77
+
78
+ - **macOS/Linux**:
79
+ Add the following line to your shell configuration file (`~/.bashrc`, `~/.zshrc`, or `~/.bash_profile`):
80
+ ```bash
81
+ export R_HOME=/usr/lib/R
82
+
83
+ ### Installation
84
+
85
+ To install the `pltstat` library, simply run the following command:
86
+
87
+ ```bash
88
+ pip install pltstat
89
+ ```
90
+
91
+ This will install the library along with all the required dependencies as specified in the `requirements.txt` file.
92
+
93
+ After installation the package, you can start using `pltstat` by importing the necessary modules in your Python scripts.
94
+
95
+ ### Example
96
+
97
+ ```python
98
+ import pandas as pd
99
+ from pltstat import twofeats as tf
100
+
101
+ # Data creation:
102
+ data = {
103
+ "gender": ["male", "female", "female", "male", "male", "female", "female", "male", "male",
104
+ "female", "male", "female", "male", "male", "female", "male", "female", "male",
105
+ "female", "male", "female", "male", "female", "male", "female", "male", "female",
106
+ "female", "male", "male", "male"],
107
+ "age": [22, 20, 17, 16, 19, 17, 11, 29, 24, 12, 22, 20, 19, 16, 11, 29, 24, 20, 16, 22,
108
+ 17, 29, 24, 16, 17, 29, 22, 19, 22, 22, 24, 29]
109
+ }
110
+
111
+ df = pd.DataFrame(data)
112
+
113
+ # Boxplot creation:
114
+ tf.boxplot(df, "gender", "age")
115
+ ```
116
+
117
+ ---
118
+
119
+ ## File Descriptions
120
+
121
+ ### Python Modules
122
+
123
+ - **[`__init__.py`](__init__.py)**
124
+ - Marks the directory as a Python package. This file allows you to import modules from the `pltstat` package.
125
+
126
+ - **[`singlefeat.py`](singlefeat.py)**
127
+ - Dedicated to the analysis and visualization of single-variable features, including plotting functions such as pie charts, count plots, and histograms.
128
+
129
+ - **[`twofeats.py`](twofeats.py)**
130
+ - Provides tools for analyzing interactions between two features. Includes functions for creating crosstabs, computing correlations, and visualizing results using violin plots, boxplots, and distribution box plots. These functions also display p-values and other statistical metrics to summarize relationships between the two features.
131
+
132
+ - **[`multfeats.py`]()**
133
+ - Provides tools for analyzing relationships between multiple features.
134
+ Includes visualization functions for analyzing missing data, comparing distributions, and visualizing dimensionality reductions. Additionally, it provides methods for creating heatmaps that display correlations and p-values, including Spearman's correlation, Mann-Whitney p-values, and Phik correlations.
135
+
136
+ - **[`circle.py`](circle.py)**
137
+ - Contains functions and methods related to circular statistical visualizations, such as radar charts or circular histograms.
138
+
139
+ - **[`cm.py`](cm.py)**
140
+ - Contains custom colormap utilities for visualizations, such as rendering correlation matrices or creating two-colored maps for p-values with a threshold (e.g., alpha).
141
+
142
+ - **[`corr_methods.py`](corr_methods.py)**
143
+ - Includes methods for calculating correlation matrices and related statistical relationships.
144
+
145
+ - **[`in_out.py`](in_out.py)**
146
+ - Provides utilities for reading, writing, and preprocessing input and output data files.
147
+
148
+ ### Other Files
149
+
150
+ - **[`.gitignore`](.gitignore)**
151
+ - Specifies intentionally untracked files to ignore in the repository, such as virtual environments and temporary files.
152
+
153
+ - **`README.md`**
154
+ - This file provides an overview of the project, including file descriptions and usage instructions.
155
+
156
+ - **[`requirements.txt`](requirements.txt)**
157
+ - Lists the Python dependencies required to run the library. Install them using:
158
+ ```bash
159
+ pip install -r requirements.txt
160
+ ```
161
+
162
+ ---
163
+
164
+ ## Getting Started
165
+
166
+ 1. Clone the repository:
167
+ ```bash
168
+ git clone https://github.com/trojanskehesten/pltstat.git
169
+ ```
170
+
171
+ 2. Navigate to the project directory:
172
+ ```bash
173
+ cd pltstat
174
+ ```
175
+
176
+ 3. **Python Version**: This library is compatible with [Python 3.12](https://www.python.org/downloads/release/python-3120/). Ensure you have this version installed before running the project.
177
+
178
+ 4. **R Installation**: Ensure that the [R language is installed](https://cloud.r-project.org/) on your system, as the `rpy2` library (used in this project) requires it.
179
+
180
+ 5. Install dependencies:
181
+ ```bash
182
+ pip install -r requirements.txt
183
+ ```
184
+
185
+ 6. Explore the modules and utilize the library in your projects.
186
+
187
+ ---
188
+
189
+ ## Usage
190
+ Each module in `pltstat` is designed to be modular and reusable. Import the required module and use its functions to visualize your statistical data. For example:
191
+
192
+ ```python
193
+ import pandas as pd
194
+ from pltstat import singlefeat as sf
195
+
196
+ data = {
197
+ "Age": [25, 30, 22, 27, 35],
198
+ "A/B Test Group": ["A", "B", "A", "B", "A"],
199
+ }
200
+ df = pd.DataFrame(data)
201
+
202
+ # Example: Plot a histogram
203
+ sf.pie(df["A/B Test Group"])
204
+ ```
205
+
206
+ ---
207
+
208
+ ## Contributing
209
+ Contributions are welcome! If you'd like to improve the library or fix issues, please:
210
+ 1. Fork the repository.
211
+ 2. Create a new branch.
212
+ 3. Make your changes and commit them.
213
+ 4. Submit a pull request.
214
+
215
+ ---
216
+
217
+ ## License
218
+ This project is licensed under the BSD 3-Clause License. See the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,18 @@
1
+ # Author: Dmitrii Beregovoi
2
+ # License: BSD 3-Clause License, see LICENSE file
3
+
4
+ # Copyright: (c) 2025 Dmitrii Beregovoi
5
+
6
+ __version__ = "0.9.0"
7
+ __author__ = "Dmitrii Beregovoi"
8
+ __email__ = "dimaforth@gmail.com"
9
+ __all__ = [
10
+ "__version__",
11
+ "corr_methods",
12
+ "cm",
13
+ "circle",
14
+ "in_out",
15
+ "singlefeat",
16
+ "twofeats",
17
+ "multfeats",
18
+ ]
@@ -0,0 +1,351 @@
1
+ # TODO: Description
2
+ import matplotlib.pyplot as plt
3
+ from matplotlib import ticker
4
+ import numpy as np
5
+ import seaborn as sns
6
+
7
+
8
+ _HIGH = 24
9
+ _N_BINS = 24
10
+ _N_TICKS = 24
11
+
12
+
13
+ def rad2val(a, high=_HIGH):
14
+ """
15
+ Convert values ``a`` from radians to measures with the highest value ``high``
16
+
17
+ Parameters
18
+ ----------
19
+ a : array_like
20
+ Input array in radians
21
+ high : float or int
22
+ High boundary for the sample range
23
+
24
+ Returns
25
+ -------
26
+ rad2val : ndarray
27
+ The corresponding values with `high` boundary. This is a scalar if ``a`` is a scalar.
28
+
29
+ Example
30
+ --------
31
+ >>> import numpy as np
32
+ >>> from pltstat.circle import rad2val
33
+
34
+ >>> a = [0, np.pi, 4, 8]
35
+ >>> rad2val(a, high=24)
36
+ array([ 0., 12., 15.27887454, 30.55774907])
37
+ """
38
+ a = np.array(a)
39
+ a = a / np.pi / 2 * high
40
+ return a
41
+
42
+
43
+ def val2rad(a, high=_HIGH):
44
+ """
45
+ Convert values `a` from measures with the highest value `high` to radians
46
+
47
+ Parameters
48
+ ----------
49
+ a : array_like
50
+ Input array in measures with the ``high`` boundary fot the sample range
51
+ high : float or int
52
+ High boundary for the sample range
53
+
54
+ Returns
55
+ -------
56
+ rad2val : ndarray
57
+ The corresponding radian values. This is a scalar if ``a`` is a scalar.
58
+
59
+ Example
60
+ --------
61
+ >>> import numpy as np
62
+ >>> from pltstat.circle import val2rad
63
+
64
+ >>> a = [0, 3, 19, 25]
65
+ >>> val2rad(a, high=24)
66
+ array([0., 0.78539816, 4.97418837, 6.54498469])
67
+
68
+ >>> val2rad(a, high=24) / np.pi
69
+ array([0., 0.25, 1.58333333, 2.08333333])
70
+ """
71
+ a = np.array(a)
72
+ a = a / high * 2 * np.pi
73
+ return a
74
+
75
+
76
+ def hist(
77
+ a, n_bins=_N_BINS, high=_HIGH, bottom=0.1, title=None, figsize=None, ax=None, return_ax=False, **kwargs,
78
+ ):
79
+ if n_bins < 2:
80
+ raise ValueError("Received an invalid number of bins. Number of bins must be at least 2, and must be an int.")
81
+
82
+ a = a / high * 2 * np.pi # h to rad
83
+
84
+ def radian_function(x, y):
85
+ """Helper function for labeling the x-axis"""
86
+ rad_x = x / np.pi / 2
87
+ return f"{(rad_x * high):.3g}"
88
+
89
+ theta = np.linspace(0, 2 * np.pi, n_bins, endpoint=False)
90
+ bins = np.linspace(0, 2 * np.pi, n_bins + 1, endpoint=True)
91
+
92
+ if ax is None:
93
+ fig, ax = plt.subplots(subplot_kw={"projection": "polar"}, figsize=figsize)
94
+ # ax = plt.subplot(111, polar=True)
95
+
96
+ max_bin = np.histogram(a, bins=bins, **kwargs)[0].max()
97
+ bottom = max_bin * bottom
98
+
99
+ # get yticks:
100
+ fig, ax2 = plt.subplots(subplot_kw={"projection": "polar"})
101
+ ax2.hist(a, bins=bins, edgecolor="black")
102
+ yticks = ax2.axes.yaxis.get_ticklocs()
103
+ plt.close(fig)
104
+
105
+ ax.hist(a, bins=bins, edgecolor="black", bottom=bottom, **kwargs)
106
+
107
+ # arrange graph
108
+ ax.set(
109
+ theta_offset=np.pi / 2,
110
+ theta_direction=-1,
111
+ xticks=theta,
112
+ yticks=yticks + bottom,
113
+ yticklabels=yticks,
114
+ )
115
+ ax.xaxis.set_major_formatter(ticker.FuncFormatter(radian_function))
116
+ ax.set_title(title)
117
+ if return_ax:
118
+ return ax
119
+
120
+
121
+ hist.__doc__ = """\
122
+ Plot histogram to show distributions of circular datasets.
123
+
124
+ Parameters
125
+ ----------
126
+ a : array_like
127
+ Input array in measures with the ``high`` boundary for the sample range.
128
+ n_bins : int, default: {n_bins}
129
+ The number of bins to produce. Raises ValueError if ``n_bins < 2``.
130
+ high : float or int, default: {high}
131
+ High boundary for the sample range.
132
+ bottom : float, default: 0.1
133
+ Proportion of location of the bottom of each bin, where 0 is center of the circle, and 1 is the edge.
134
+ Bins are drawn from ``bottom * max(bins)`` to ``bottom * max(bins) + hist(x, bins)``.
135
+ Valid range is [0, 1].
136
+ title : str or None, default: None
137
+ Text to use for the title.
138
+ figsize : (float, float) or None, default: None
139
+ Width, height in inches.
140
+ ax : :class:`matplotlib.axes.Axes` or array of Axes or None, default: None
141
+ Axes object to draw the plot onto, otherwise uses the current Axes. If ``ax`` is None, create nex ``ax``.
142
+ return_ax : bool, default: False
143
+ Show, it is necessary to return ``ax``.
144
+ kwargs : key, value mappings
145
+ Other keywords arguments are passed down to :meth:`maptplotlib.axes.Axes.hist`.
146
+
147
+ Returns
148
+ -------
149
+ ax : :class:`matplotlib.axes.Axes` or array of Axes
150
+ Returns the Axes object with the plot drawn onto it if ``return_ax argument`` is ``True``.
151
+
152
+ Example
153
+ --------
154
+ >>> import numpy as np
155
+ >>> from pltstat.circle import hist
156
+ >>> np.random.seed(0)
157
+ >>> a = np.random.randint(0, 24, 30)
158
+ >>> a
159
+ array([ 6, 23, 11, 14, 18, 0, 14, 3, 21, 12, 10, 20, 11, 4, 6, 4, 15,
160
+ 20, 3, 12, 4, 20, 8, 14, 15, 20, 3, 23, 15, 13])
161
+ >>> hist(a, 12)""".format(n_bins=_N_BINS, high=_HIGH)
162
+
163
+
164
+ def mean(a, high=_HIGH, atol=1e-10):
165
+ # to rad
166
+ a = np.array(a) / high * 2 * np.pi
167
+
168
+ # cos, sin, radius and mean
169
+ c = np.mean(np.cos(a))
170
+ s = np.mean(np.sin(a))
171
+ r = np.sqrt(c ** 2 + s ** 2)
172
+
173
+ # if radius is 0 than it is not possible to calculate mean value
174
+ # 1e-10 for 7 signs after dot accuracy
175
+ if np.isclose(r, 0, atol=atol):
176
+ return np.nan
177
+
178
+ tau = np.arctan2(s, c)
179
+
180
+ # return from rad
181
+ tau = tau / np.pi / 2 * high
182
+ if tau < 0:
183
+ tau += high
184
+ # instead of elif, because-1.614809932057922e-15 + 360 => 360, for example a=[10, 350], high=360:
185
+ if tau >= high:
186
+ tau -= high
187
+ return tau
188
+
189
+
190
+ mean.__doc__ = """\
191
+ Compute the circular mean for samples in a range.
192
+ The function shows more accurate result than :meth:`scipy.stats.circmean`
193
+
194
+ Parameters
195
+ ----------
196
+ a : array_like
197
+ Input array in measures with the ``high`` boundary for the sample range.
198
+ high : float or int, default: {high}
199
+ High boundary for the sample range.
200
+ atol : float, default: 1e-10
201
+ The threshold for radius calculation. If the radius is less than ``atol``, it will be set to 0 and the mean value
202
+ will be NaN. When the radius is 0, it is not possible to calculate the mean value. If the radius is close to 0,
203
+ the mean value can be extremly inaccurate.
204
+ An ``atol`` equal to ``1e-10`` ensures a mean value accurate to approximately 7 decimal places.
205
+
206
+ Returns
207
+ -------
208
+ mean : float
209
+ Circular mean
210
+
211
+ Examples
212
+ --------
213
+ >>> import numpy as np
214
+ >>> from pltstat.circle import mean
215
+ >>> from scipy.stats import circmean
216
+ >>> a = [10, 350]
217
+ >>> mean(a, 360)
218
+ 0.0
219
+ >>> circmean(a, 360)
220
+ 359.99999999999994""".format(high=_HIGH)
221
+
222
+
223
+ def std(a, high=_HIGH):
224
+ # to rad
225
+ a = np.array(a) / high * 2 * np.pi
226
+
227
+ # cos, sin, radius and mean
228
+ c = np.mean(np.cos(a))
229
+ s = np.mean(np.sin(a))
230
+ r = np.sqrt(c ** 2 + s ** 2)
231
+
232
+ # if radius is 0 than it is not possible to calculate mean value
233
+ # 1e-10 for 7 signs after dot accuracy
234
+ # if np.isclose(r, 0, atol=1e-10):
235
+ # return np.nan
236
+
237
+ v = np.sqrt(-2 * np.log(r))
238
+
239
+ # return from rad
240
+ v = v / np.pi / 2 * high
241
+ return v
242
+
243
+
244
+ std.__doc__ = """\
245
+ Compute the circular standard deviation for samples in a range.
246
+
247
+ Parameters
248
+ ----------
249
+ a : array_like
250
+ Input array in measures with the ``high`` boundary for the sample range.
251
+ high : float or int, default: {high}
252
+ High boundary for the sample range.
253
+
254
+ Returns
255
+ -------
256
+ std : float
257
+ Circular standard deviation
258
+
259
+ Examples
260
+ --------
261
+ >>> import numpy as np
262
+ >>> from pltstat.circle import std
263
+ >>> from scipy.stats import circstd
264
+ >>> a = [10, 350]
265
+ >>> std(a, 360)
266
+ 10.0255602484647
267
+ >>> circstd(a, 360)
268
+ 10.025560248464737""".format(high=_HIGH)
269
+
270
+
271
+ def scatter(
272
+ deg, y, high=_HIGH, n_ticks=_N_TICKS, title=None, figsize=None, ax=None, return_ax=False, **kwargs
273
+ ):
274
+ BOTTOM_EDGE = 0.2
275
+ UPPER_EDGE = 0.1
276
+
277
+ rads = deg / high * 2 * np.pi # h to rad
278
+ theta = np.linspace(0, 2 * np.pi, n_ticks, endpoint=False)
279
+
280
+ def radian_function(x, y):
281
+ """Helper function for labeling the x-axis"""
282
+ rad_x = x / np.pi / 2
283
+ return f"{(rad_x * high):.3g}"
284
+
285
+ if ax is None:
286
+ fig, ax = plt.subplots(subplot_kw={"projection": "polar"}, figsize=figsize)
287
+
288
+ y_max = max(y)
289
+ y_min = min(y)
290
+ y_diff = y_max - y_min
291
+
292
+ sns.scatterplot(x=rads, y=y, ax=ax, **kwargs)
293
+ ax.set_ylim((y_min - y_diff * BOTTOM_EDGE, y_max + y_diff * UPPER_EDGE))
294
+
295
+ # arrange graph
296
+ ax.set(
297
+ theta_offset=np.pi / 2,
298
+ theta_direction=-1,
299
+ xticks=theta,
300
+ # yticks=yticks,
301
+ # yticklabels=yticks,
302
+ )
303
+ ax.xaxis.set_major_formatter(ticker.FuncFormatter(radian_function))
304
+ ax.set_title(title)
305
+ if return_ax:
306
+ return ax
307
+
308
+
309
+ scatter.__doc__ = """\
310
+ Draw a scatter plot of circular datasets.
311
+
312
+ Parameters
313
+ ----------
314
+ deg : array_like
315
+ Variables that specify positions on the angle axis.
316
+ y : array_like
317
+ Variables that specify positions on the y axis.
318
+ high : float or int, default: {high}
319
+ High boundary for the sample range.
320
+ n_ticks : int, default: {n_ticks}
321
+ The number of angle ticks to produce.
322
+ ax : :class:`matplotlib.axes.Axes` or array of Axes or None, default: None
323
+ Axes object to draw the plot onto, otherwise uses the current Axes. If ``ax`` is None, create nex ``ax``.
324
+ return_ax : bool, default: False
325
+ Show, it is necessary to return ``ax``.
326
+ kwargs : key, value mappings
327
+ Other keywords arguments are passed down to :meth:`seaborn.scatterplot`.
328
+
329
+ Returns
330
+ -------
331
+ ax : :class:`matplotlib.axes.Axes` or array of Axes
332
+ Returns the Axes object with the plot drawn onto it if ``return_ax argument`` is ``True``.
333
+
334
+
335
+ :return: ax if return_ax is True, else - return None
336
+
337
+ Example
338
+ --------
339
+ >>> import numpy as np
340
+ >>> from pltstat.circle import scatter
341
+ >>> np.random.seed(0)
342
+ >>> deg = np.linspace(0, 24, 20, endpoint=False)
343
+ >>> deg
344
+ array([ 0. , 1.2, 2.4, 3.6, 4.8, 6. , 7.2, 8.4, 9.6, 10.8, 12. ,
345
+ 13.2, 14.4, 15.6, 16.8, 18. , 19.2, 20.4, 21.6, 22.8])
346
+ >>> temp = np.concatenate((np.repeat([36.6], 10), np.linspace(36.6, 40, 10, endpoint=False)))
347
+ >>> temp
348
+ array([36.6 , 36.6 , 36.6 , 36.6 , 36.6 , 36.6 , 36.6 , 36.6 , 36.6 ,
349
+ 36.6 , 36.6 , 36.94, 37.28, 37.62, 37.96, 38.3 , 38.64, 38.98,
350
+ 39.32, 39.66])
351
+ >>> scatter(deg, temp, s=20, marker='o')""".format(n_ticks=_N_TICKS, high=_HIGH)
@@ -0,0 +1,101 @@
1
+ from matplotlib.colors import LinearSegmentedColormap
2
+
3
+
4
+ def get_pval_legend_thr_cmap(alpha=0.05):
5
+ """
6
+ Get Red-Green LinearSegmentedColormap for plot of p-values with ``alpha`` threshold and ``cbar_kws`` for legend.
7
+ It is green when a value is less than threshold and red in another case
8
+
9
+ Parameters
10
+ ----------
11
+ alpha : float, default: 0.05
12
+ Significance level. Must be in (0, 1)
13
+
14
+ Returns
15
+ -------
16
+ cmap : :class:`matplotlib.colors.LinearSegmentedColormap`
17
+ Colormap instance for p-values
18
+ cbar_kws : dict([(str, list)])
19
+ Dictionary with list of legend ticks
20
+
21
+ Example
22
+ --------
23
+ >>> from pltstat.cm import get_pval_legend_thr_cmap
24
+ >>> from numpy.random import random
25
+ >>> import seaborn as sns
26
+ >>> from matplotlib import pyplot as plt
27
+ >>>
28
+ >>> pvals = random((30, 4))
29
+ >>> cmap, cbar_kws = get_pval_legend_thr_cmap()
30
+ >>> plt.figure(figsize=(14, 8))
31
+ >>> sns.heatmap(pvals, vmin=0, vmax=1, annot=True, fmt='.2f', linewidth=1, cmap=cmap, cbar_kws=cbar_kws);
32
+ """
33
+ green = "palegreen"
34
+ red = "lightcoral"
35
+ cmap = [
36
+ (0, green),
37
+ (alpha, green),
38
+ (alpha, red),
39
+ (1, red),
40
+ ]
41
+ cmap = LinearSegmentedColormap.from_list("custom", cmap)
42
+ cbar_kws = {"ticks": [0.0, alpha, 1.0]}
43
+ return cmap, cbar_kws
44
+
45
+
46
+ def get_corr_thr_cmap(threshold=0.8, vmin=-1):
47
+ """
48
+ Get Blue-Red cmap for plot correlations with ``|threshold|``
49
+ It works for correlations from 'vmin' to +1, where vmin is 0 or -1
50
+
51
+ Parameters
52
+ ----------
53
+ threshold : float, default: 0.08
54
+ Level for colouring the correlation. Must be in (0, 1)
55
+ vmin : int, default: -1
56
+ Minimum value of correlations. Must be in -1 or 0.
57
+
58
+ Returns
59
+ -------
60
+ cmap : :class:``matplotlib.colors.LinearSegmentedColormap``
61
+ Colormap instance for correlations with specific ``threshold``
62
+
63
+ Example
64
+ --------
65
+ >>> from pltstat.cm import get_corr_thr_cmap
66
+ >>> from numpy.random import random
67
+ >>> import seaborn as sns
68
+ >>> from matplotlib import pyplot as plt
69
+ >>>
70
+ >>> pvals = random((30, 4))
71
+ >>> cmap = get_corr_thr_cmap(vmin=0)
72
+ >>> plt.figure(figsize=(14, 8))
73
+ >>> sns.heatmap(pvals, vmin=0, vmax=1, annot=True, fmt='.2f', linewidth=1, cmap=cmap);
74
+ """
75
+ if (threshold > 1) or (threshold < 0):
76
+ raise ValueError("thresholds must be from 0 to 1")
77
+
78
+ white = "White"
79
+ blue = "Blue"
80
+ red = "Red"
81
+
82
+ if vmin == -1:
83
+ threshold = 1 - threshold
84
+ threshold = threshold / 2
85
+ cmap = [
86
+ (0, blue),
87
+ (threshold, white),
88
+ (1 - threshold, white),
89
+ (1, red),
90
+ ]
91
+ elif vmin == 0:
92
+ cmap = [
93
+ (0, white),
94
+ (threshold, white),
95
+ (1, red),
96
+ ]
97
+ else:
98
+ raise ValueError("'vmin' must be -1 or 0")
99
+
100
+ cmap = LinearSegmentedColormap.from_list("custom", cmap)
101
+ return cmap