pistachioplots 0.1.0__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Daniel José Aguilar Paniagua
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.4
2
+ Name: pistachioplots
3
+ Version: 0.1.0
4
+ Summary: Plotting utilities built on pistachiots, polars, and plotnine
5
+ Author-email: Daniel José Aguilar Paniagua <danieljoseaguilar@gmail.com>
6
+ License: MIT
7
+ Keywords: plotting,plotnine,polars,time series,exploratory data analysis
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Scientific/Engineering :: Visualization
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/plain
19
+ License-File: LICENSE.txt
20
+ Requires-Dist: polars
21
+ Requires-Dist: pandas
22
+ Requires-Dist: numpy
23
+ Requires-Dist: scipy
24
+ Requires-Dist: matplotlib
25
+ Requires-Dist: plotnine
26
+ Requires-Dist: mizani
27
+ Requires-Dist: statsmodels
28
+ Requires-Dist: pistachiots
29
+ Dynamic: license-file
30
+
31
+ pistachioplots
32
+
33
+ Plotting utilities for exploratory data analysis and time series, built on
34
+ polars, plotnine and pistachiots.
35
+
36
+ The package installs as 'pistachioplots' and imports as 'PistachioPlots'.
37
+
38
+
39
+ INSTALLATION
40
+
41
+ pip install pistachioplots
42
+
43
+
44
+ USAGE
45
+
46
+ import PistachioPlots as pst
47
+
48
+ Every function returns a plotnine plot, or a dictionary of plots when it is
49
+ asked for several at once. Variables can be given explicitly or left out, in
50
+ which case the function picks the columns whose type fits.
51
+
52
+
53
+ DISTRIBUTIONS
54
+
55
+ dist_density(df, var) histogram with a kernel density overlay, and
56
+ optional analytic densities on top
57
+ dist_density_cond(df, var, var_cat)
58
+ the same, conditioned on a categorical
59
+ variable, overlaid or in facets
60
+ dist_mass(df, var) bar chart of a categorical variable, with
61
+ percentage and count labels
62
+ dist_mass_cond(df, var1, var2)
63
+ the distribution of var1 conditioned on var2,
64
+ in facets or as side-by-side bars
65
+
66
+
67
+ TIME SERIES
68
+
69
+ ts(df, var, response) one plot per variable, or a single faceted one
70
+ ts_multiple(df, var) several series in one panel or in facets
71
+ ts_by_keys(df, var) panel data with one or two keys
72
+ time_breaks(plt, dates) x-axis breaks and date format
73
+
74
+ These take a TSPolars object from pistachiots. 'response' gives one variable
75
+ the first color and the first place in the legend. 'ts_breaks_params' controls
76
+ the breaks: 'jump' (the step between them), 'date_format' and 'plot_minor'.
77
+
78
+
79
+ CORRELATIONS
80
+
81
+ corrs(df, response) Pearson, Spearman and Kendall coefficients
82
+ against a response, with significance marks
83
+ corrs_matrix(df) correlation matrix as a heatmap
84
+
85
+ Lagged variables named L1x, L2x and so on are grouped and sorted by lag number.
86
+
87
+
88
+ SCATTER AND LINES
89
+
90
+ scatter(df, var) scatter matrix across the given variables
91
+ scatter(df, vary, varx) a response against one or several covariates
92
+ line(df, varx, vary) a simple line, optionally stepped or filled
93
+
94
+
95
+ THEME AND COLORS
96
+
97
+ theme_params_def the default theme settings; copy it, change
98
+ what you need and pass it as theme_params
99
+ colors_categ(series) the palette for a categorical variable
100
+ set_palette(colors) override the package palette
101
+
102
+ tms = pst.theme_params_def.copy()
103
+ tms['x_angle'] = 90
104
+ pst.dist_mass(df, 'region', theme_params = tms)
105
+
106
+
107
+ LICENSE
108
+
109
+ MIT. See the LICENSE.txt file.
@@ -0,0 +1,79 @@
1
+ pistachioplots
2
+
3
+ Plotting utilities for exploratory data analysis and time series, built on
4
+ polars, plotnine and pistachiots.
5
+
6
+ The package installs as 'pistachioplots' and imports as 'PistachioPlots'.
7
+
8
+
9
+ INSTALLATION
10
+
11
+ pip install pistachioplots
12
+
13
+
14
+ USAGE
15
+
16
+ import PistachioPlots as pst
17
+
18
+ Every function returns a plotnine plot, or a dictionary of plots when it is
19
+ asked for several at once. Variables can be given explicitly or left out, in
20
+ which case the function picks the columns whose type fits.
21
+
22
+
23
+ DISTRIBUTIONS
24
+
25
+ dist_density(df, var) histogram with a kernel density overlay, and
26
+ optional analytic densities on top
27
+ dist_density_cond(df, var, var_cat)
28
+ the same, conditioned on a categorical
29
+ variable, overlaid or in facets
30
+ dist_mass(df, var) bar chart of a categorical variable, with
31
+ percentage and count labels
32
+ dist_mass_cond(df, var1, var2)
33
+ the distribution of var1 conditioned on var2,
34
+ in facets or as side-by-side bars
35
+
36
+
37
+ TIME SERIES
38
+
39
+ ts(df, var, response) one plot per variable, or a single faceted one
40
+ ts_multiple(df, var) several series in one panel or in facets
41
+ ts_by_keys(df, var) panel data with one or two keys
42
+ time_breaks(plt, dates) x-axis breaks and date format
43
+
44
+ These take a TSPolars object from pistachiots. 'response' gives one variable
45
+ the first color and the first place in the legend. 'ts_breaks_params' controls
46
+ the breaks: 'jump' (the step between them), 'date_format' and 'plot_minor'.
47
+
48
+
49
+ CORRELATIONS
50
+
51
+ corrs(df, response) Pearson, Spearman and Kendall coefficients
52
+ against a response, with significance marks
53
+ corrs_matrix(df) correlation matrix as a heatmap
54
+
55
+ Lagged variables named L1x, L2x and so on are grouped and sorted by lag number.
56
+
57
+
58
+ SCATTER AND LINES
59
+
60
+ scatter(df, var) scatter matrix across the given variables
61
+ scatter(df, vary, varx) a response against one or several covariates
62
+ line(df, varx, vary) a simple line, optionally stepped or filled
63
+
64
+
65
+ THEME AND COLORS
66
+
67
+ theme_params_def the default theme settings; copy it, change
68
+ what you need and pass it as theme_params
69
+ colors_categ(series) the palette for a categorical variable
70
+ set_palette(colors) override the package palette
71
+
72
+ tms = pst.theme_params_def.copy()
73
+ tms['x_angle'] = 90
74
+ pst.dist_mass(df, 'region', theme_params = tms)
75
+
76
+
77
+ LICENSE
78
+
79
+ MIT. See the LICENSE.txt file.
@@ -0,0 +1,38 @@
1
+ [project]
2
+ name = "pistachioplots"
3
+ version = "0.1.0"
4
+ description = "Plotting utilities built on pistachiots, polars, and plotnine"
5
+ readme = {file = "README.txt", content-type = "text/plain"}
6
+ requires-python = ">=3.9"
7
+ license = {text = "MIT"}
8
+ authors = [{name = "Daniel José Aguilar Paniagua", email = "danieljoseaguilar@gmail.com"}]
9
+ keywords = ["plotting", "plotnine", "polars", "time series", "exploratory data analysis"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Intended Audience :: Science/Research",
13
+ "License :: OSI Approved :: MIT License",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.9",
16
+ "Programming Language :: Python :: 3.10",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Topic :: Scientific/Engineering :: Visualization",
20
+ ]
21
+ dependencies = [
22
+ "polars",
23
+ "pandas",
24
+ "numpy",
25
+ "scipy",
26
+ "matplotlib",
27
+ "plotnine",
28
+ "mizani",
29
+ "statsmodels",
30
+ "pistachiots",
31
+ ]
32
+
33
+ [tool.setuptools.packages.find]
34
+ where = ["src"]
35
+
36
+ [build-system]
37
+ requires = ["setuptools>=61"]
38
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,330 @@
1
+
2
+
3
+ import numpy as np
4
+ import polars as pl
5
+ from plotnine import (
6
+ ggplot, aes, geom_col, geom_text, scale_fill_manual,
7
+ scale_x_discrete, labs, position_dodge, geom_raster,
8
+ scale_fill_gradient2, scale_fill_gradientn, coord_equal
9
+ )
10
+ import re
11
+ from scipy import stats
12
+ from typing import Literal
13
+ import warnings
14
+
15
+
16
+
17
+ import pistachiots as cln
18
+ from pistachiots import TSPolars
19
+ from . import PstUtils as psu
20
+
21
+
22
+ def corrs(df, response, covs = None, rem_lags = False, group_lags = True, alpha = 0.05, theme_params = psu.theme_params_def):
23
+
24
+ # 1. Valdiacion y limpieza:
25
+
26
+ #1.1. Quitar lags
27
+ if rem_lags:
28
+ df = df.rem_lags(rem_response = True, response = response)
29
+
30
+ #1.2. Extaer covariables.
31
+ df = df.select([c for c in df.columns if psu.is_continuous(df[c]) or psu.is_integer(df[c])])
32
+
33
+ if not covs:
34
+ covs = [c for c in df.columns if c!= response]
35
+ covs = [c for c in covs if c!=df.ts_col] if isinstance(df, TSPolars) else covs
36
+ if not covs:
37
+ raise ValueError('There are no numeric/ordered covariates.')
38
+ else:
39
+ missings_covs = [c for c in covs if c not in df.columns]
40
+ if missings_covs:
41
+ missing_str = ', '.join(missings_covs)
42
+ raise ValueError(f"Covariate(s) {missing_str} is not numeric/ordered and/or is not in df.")
43
+
44
+ if response not in df.columns:
45
+ raise ValueError('Response is not numeric/ordered and/or is not in df.')
46
+
47
+ if isinstance(df, TSPolars):
48
+ if group_lags and not any(re.match(r"^L[0-9]+", c) for c in covs):
49
+ warnings.warn("There are no lags but group_lags is True.")
50
+ group_lags = False
51
+
52
+
53
+ # 2. Calculate correlations:
54
+ def calc_corr_df(cov_name):
55
+ x = df[cov_name].to_numpy()
56
+ y = df[response].to_numpy()
57
+
58
+ nan_mask = np.isnan(x) | np.isnan(y)
59
+ x = x[~nan_mask]
60
+ y = y[~nan_mask]
61
+
62
+ pearson = stats.pearsonr(x, y, alternative='two-sided', method=None)
63
+ kendall = stats.kendalltau(x, y, method='auto', alternative='two-sided', variant='b', nan_policy='omit')
64
+ spearman = stats.spearmanr(x, y, nan_policy='omit', alternative='two-sided')
65
+
66
+ df_corr_cov = pl.DataFrame({
67
+ 'variable':[cov_name] * 3,
68
+ 'method':['Pearson', 'Spearman', 'Kendall'],
69
+ 'corr':[pearson.statistic, spearman.statistic, kendall.statistic],
70
+ 'p_val':[pearson.pvalue, spearman.pvalue, kendall.pvalue],
71
+ })
72
+
73
+ return df_corr_cov
74
+
75
+ df_corrs = (
76
+ pl.concat([calc_corr_df(c) for c in covs])
77
+ .with_columns(
78
+ pl.when(pl.col('p_val') <= alpha).then(pl.lit('*')).otherwise(pl.lit('')).alias('signif'),
79
+ pl.col('method').cast(pl.Enum(['Pearson', 'Kendall','Spearman']))
80
+ )
81
+ .with_columns(
82
+ pl.when(pl.col('corr') > 0).then(pl.col('corr')+0.04).otherwise(pl.col('corr')-0.04).alias('text_y'),
83
+ #pl.when(pl.col('corr') > 0).then(pl.lit(0)).otherwise(pl.lit(1)).alias('text_vjust')
84
+ )
85
+ )
86
+
87
+
88
+ # 3. Group lags:
89
+ if group_lags:
90
+ lag_re = re.compile(r"^L([0-9]+)")
91
+
92
+ covs_base = list(dict.fromkeys(lag_re.sub("", c) for c in covs))
93
+ covs_cont = [c for c in covs if not lag_re.match(c)]
94
+
95
+ ord_vars = []
96
+ for base in covs_base:
97
+ pattern = re.compile(rf"^L[0-9]+{re.escape(base)}$")
98
+ lagged = sorted(
99
+ (c for c in covs if pattern.match(c)),
100
+ key=lambda c: int(lag_re.match(c).group(1))
101
+ )
102
+ if base in covs_cont:
103
+ ord_vars.extend([base] + lagged)
104
+ else:
105
+ ord_vars.extend(lagged)
106
+
107
+ df_corrs = df_corrs.with_columns(
108
+ pl.col('variable').cast(pl.Enum(ord_vars))
109
+ )
110
+
111
+ # 4. Base plot:
112
+ palette = psu.colors_categ(df_corrs['method'], is_ord=False)
113
+
114
+ base_plot = (
115
+ ggplot(df_corrs, aes('variable', 'corr', fill='method'))
116
+ + geom_col(position=position_dodge(0.9))
117
+ + geom_text(
118
+ aes(label='signif', y='text_y'),
119
+ position=position_dodge(0.9),
120
+ size=9,
121
+ family=theme_params.get('font'),
122
+ )
123
+ + scale_fill_manual(values={
124
+ 'Pearson': palette[0], 'Kendall': palette[1], 'Spearman': palette[2]
125
+ })
126
+ + labs(
127
+ fill=None,
128
+ caption=f"*: significancia al {alpha * 100:g}%",
129
+ )
130
+ #+ scale_x_discrete(guide=guide_axis(n_dodge=1))
131
+ )
132
+
133
+ # 5. Add theme:
134
+ theme_params = dict(theme_params)
135
+ theme_params['title'] = f"Coeficientes de dependencia sobre {response}"
136
+ final_plot = psu.add_theme(base_plot, **theme_params)
137
+
138
+ return final_plot
139
+
140
+
141
+ def corrs_matrix(
142
+ df,
143
+ statistic: Literal['pearson', 'spearman', 'kendall'] = 'pearson',
144
+ varsx = None,
145
+ varsy = None,
146
+ ratio = 0.75,
147
+ rem_lags = False,
148
+ group_lags = True,
149
+ write_signif = False,
150
+ write_coef = False,
151
+ write_pval = False,
152
+ label_size = 9,
153
+ ndecimals = 4,
154
+ alpha1 = 0.05,
155
+ alpha2 = 0.01,
156
+ alpha3 = 0.0001,
157
+ theme_params = psu.theme_params_def
158
+ ):
159
+ # 1. Validacion y limpieza:
160
+
161
+ if rem_lags:
162
+ df = df.rem_lags(rem_response=False)
163
+
164
+ df = df.select([c for c in df.columns if psu.is_continuous(df[c]) or psu.is_integer(df[c])])
165
+
166
+ if isinstance(varsx, str):
167
+ varsx = [varsx]
168
+
169
+ if isinstance(varsy, str):
170
+ varsy = [varsy]
171
+
172
+ if not varsx:
173
+ varsx = [c for c in df.columns if c != df.ts_col] if isinstance(df, TSPolars) else list(df.columns)
174
+ if not varsx:
175
+ raise ValueError('There are no numeric columns.')
176
+ else:
177
+ missings_varsx = [c for c in varsx if c not in df.columns]
178
+ if missings_varsx:
179
+ missing_str = ', '.join(missings_varsx)
180
+ raise ValueError(f"Variables {missing_str} are not numeric and/or are not in df.")
181
+
182
+ if not varsy:
183
+ varsy = [c for c in df.columns if c != df.ts_col] if isinstance(df, TSPolars) else list(df.columns)
184
+ if not varsy:
185
+ raise ValueError('There are no numeric columns.')
186
+ else:
187
+ missings_varsy = [c for c in varsy if c not in df.columns]
188
+ if missings_varsy:
189
+ missing_str = ', '.join(missings_varsy)
190
+ raise ValueError(f"Variables {missing_str} are not numeric and/or are not in df.")
191
+
192
+ if statistic not in ('pearson', 'spearman', 'kendall'):
193
+ raise ValueError("statistic must be one of 'pearson', 'spearman', 'kendall'")
194
+
195
+ if isinstance(df, TSPolars):
196
+ if group_lags and not any(re.match(r"^L[0-9]+", c) for c in varsx+varsy):
197
+ warnings.warn("There are no lags but group_lags is True.")
198
+ group_lags = False
199
+
200
+ if isinstance(df, TSPolars):
201
+ df = df.df
202
+
203
+ # 2. Calculate correlations:
204
+ def calc_corr_df(varx, vary):
205
+ x = df[varx].to_numpy()
206
+ y = df[vary].to_numpy()
207
+
208
+ nan_mask = np.isnan(x) | np.isnan(y)
209
+ x = x[~nan_mask]
210
+ y = y[~nan_mask]
211
+
212
+ if statistic == 'pearson':
213
+ st = stats.pearsonr(x, y, alternative='two-sided')
214
+ elif statistic == 'spearman':
215
+ st = stats.spearmanr(x, y, nan_policy='omit', alternative='two-sided')
216
+ else:
217
+ st = stats.kendalltau(x, y, method='auto', alternative='two-sided', variant='b', nan_policy='omit')
218
+
219
+ return pl.DataFrame({
220
+ 'x': [varx],
221
+ 'y': [vary],
222
+ 'coef': [st.statistic],
223
+ 'p_val': [st.pvalue],
224
+ })
225
+
226
+ df_corrs = (
227
+ pl.concat([calc_corr_df(varx, vary) for varx in varsx for vary in varsy])
228
+ .with_columns(
229
+ (
230
+ pl.when(pl.col('p_val') <= alpha3)
231
+ .then(pl.lit('***'))
232
+ .when(pl.col('p_val') <= alpha2)
233
+ .then(pl.lit('**'))
234
+ .when(pl.col('p_val') <= alpha1)
235
+ .then(pl.lit('*'))
236
+ .otherwise(pl.lit(''))
237
+ .alias('signif')
238
+ ),
239
+ pl.col('p_val').round(ndecimals).cast(pl.Utf8).alias('p_val_fmt'),
240
+ pl.col('coef').map_elements(lambda v: f"{v:.{ndecimals}f}", return_dtype=pl.Utf8).alias('coef_fmt'),
241
+ )
242
+ .with_columns(
243
+ pl.when(pl.lit(write_coef) & pl.lit(write_signif))
244
+ .then(pl.col('coef_fmt') + pl.col('signif'))
245
+ .when(pl.lit(write_coef))
246
+ .then(pl.col('coef_fmt'))
247
+ .when(pl.lit(write_signif))
248
+ .then(pl.col('signif'))
249
+ .otherwise(pl.lit(''))
250
+ .alias('label')
251
+ )
252
+ .with_columns(
253
+ pl.when(pl.lit(write_pval))
254
+ .then(pl.col('label') + pl.lit('\n(') + pl.col('p_val_fmt') + pl.lit(')'))
255
+ .otherwise(pl.col('label'))
256
+ .alias('label')
257
+ )
258
+ )
259
+
260
+ # 3. Group lags (both axes):
261
+ if group_lags:
262
+ lag_re = re.compile(r"^L([0-9]+)")
263
+
264
+ def ordered_levels(varlist):
265
+ covs_base = list(dict.fromkeys(lag_re.sub("", c) for c in varlist))
266
+ covs_cont = [c for c in varlist if not lag_re.match(c)]
267
+ ord_vars = []
268
+ for base in covs_base:
269
+ pattern = re.compile(rf"^L[0-9]+{re.escape(base)}$")
270
+ lagged = sorted(
271
+ (c for c in varlist if pattern.match(c)),
272
+ key=lambda c: int(lag_re.match(c).group(1))
273
+ )
274
+ if base in covs_cont:
275
+ ord_vars.extend([base] + lagged)
276
+ else:
277
+ ord_vars.extend(lagged)
278
+ return ord_vars
279
+
280
+ df_corrs = (
281
+ df_corrs
282
+ .with_columns(
283
+ pl.col('x').cast(pl.Enum(ordered_levels(varsx))),
284
+ pl.col('y').cast(pl.Enum(ordered_levels(varsy)))
285
+ )
286
+ )
287
+
288
+ # 4. Create plot:
289
+ plt = ggplot(df_corrs, aes(x='x', y='y', fill='coef')) + geom_raster()
290
+
291
+ if write_signif or write_coef or write_pval:
292
+ plt = plt + geom_text(aes(label='label'), color='black', size=label_size)
293
+
294
+ plt = plt + labs(
295
+ x=None,
296
+ y=None,
297
+ fill=statistic.capitalize(),
298
+ caption=(
299
+ f"*: significancia al {alpha1*100:g}% | "
300
+ f"**: {alpha2*100:g}% | "
301
+ f"***: {alpha3*100:g}%"
302
+ if write_signif else None
303
+ ),
304
+ )
305
+
306
+ # 5. Add theme:
307
+ theme_params = dict(theme_params)
308
+ theme_params['title'] = f"Matriz de correlaciones ({statistic.capitalize()})"
309
+ plt = psu.add_theme(plt, **theme_params)
310
+
311
+ plt = plt + scale_fill_gradientn(
312
+ colors=['#67001F', '#B2182B', '#D6604D', '#F4A582', '#FDDBC7', '#FFFFFF',
313
+ '#D1E5F0', '#92C5DE', '#4393C3', '#2166AC', '#053061'],
314
+ limits=(-1, 1),
315
+ )
316
+
317
+ plt = plt + coord_equal(ratio=ratio)
318
+
319
+ return plt
320
+
321
+
322
+
323
+
324
+
325
+
326
+
327
+
328
+
329
+
330
+