mbapy 0.7.2__tar.gz → 0.7.3__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.
Files changed (92) hide show
  1. {mbapy-0.7.2/mbapy.egg-info → mbapy-0.7.3}/PKG-INFO +1 -1
  2. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/__version__.py +3 -3
  3. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/base.py +40 -23
  4. mbapy-0.7.3/mbapy/plot.py +263 -0
  5. mbapy-0.7.2/mbapy/plot.py → mbapy-0.7.3/mbapy/plot_utils/bar_utils.py +44 -212
  6. mbapy-0.7.3/mbapy/plot_utils/scatter_utils.py +231 -0
  7. mbapy-0.7.3/mbapy/sci_utils/__init__.py +0 -0
  8. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/duitang.py +3 -3
  9. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/hplc.py +1 -1
  10. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/mass.py +2 -2
  11. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/stats/reg.py +14 -10
  12. mbapy-0.7.3/mbapy/web_utils/__init__.py +0 -0
  13. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/web_utils/request.py +2 -1
  14. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/web_utils/spider.py +82 -41
  15. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/web_utils/task.py +126 -36
  16. {mbapy-0.7.2 → mbapy-0.7.3/mbapy.egg-info}/PKG-INFO +1 -1
  17. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy.egg-info/SOURCES.txt +4 -0
  18. {mbapy-0.7.2 → mbapy-0.7.3}/setup.py +2 -2
  19. {mbapy-0.7.2 → mbapy-0.7.3}/LICENSE +0 -0
  20. {mbapy-0.7.2 → mbapy-0.7.3}/MANIFEST.in +0 -0
  21. {mbapy-0.7.2 → mbapy-0.7.3}/README.md +0 -0
  22. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/__init__.py +0 -0
  23. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/bio/__init__.py +0 -0
  24. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/bio/peptide.py +0 -0
  25. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/__init__.py +0 -0
  26. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/arch/CL/__init__.py +0 -0
  27. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/arch/CL/builder.py +0 -0
  28. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/arch/CL/trainer.py +0 -0
  29. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/arch/CLIP/__init__.py +0 -0
  30. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/arch/CLIP/builder.py +0 -0
  31. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/arch/CLIP/trainer.py +0 -0
  32. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/arch/__init__.py +0 -0
  33. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/bb.py +0 -0
  34. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/data.py +0 -0
  35. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/hyper_search.py +0 -0
  36. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/loss.py +0 -0
  37. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/m.py +0 -0
  38. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/optim.py +0 -0
  39. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/paper/__init__.py +0 -0
  40. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/paper/bb.py +0 -0
  41. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/dl_torch/utils.py +0 -0
  42. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/file.py +0 -0
  43. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/file_utils/__init__.py +0 -0
  44. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/file_utils/image.py +0 -0
  45. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/file_utils/video.py +0 -0
  46. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/game.py +0 -0
  47. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/paper.py +0 -0
  48. {mbapy-0.7.2/mbapy/sci_utils → mbapy-0.7.3/mbapy/plot_utils}/__init__.py +0 -0
  49. /mbapy-0.7.2/mbapy/web_utils/__init__.py → /mbapy-0.7.3/mbapy/plot_utils/line_utils.py +0 -0
  50. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/sci_utils/paper_download.py +0 -0
  51. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/sci_utils/paper_parse.py +0 -0
  52. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/sci_utils/paper_search.py +0 -0
  53. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/__init__.py +0 -0
  54. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/__main__.py +0 -0
  55. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/_main_.py +0 -0
  56. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/_script_utils_.py +0 -0
  57. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/avif.py +0 -0
  58. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/cluster.py +0 -0
  59. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/cnipa.py +0 -0
  60. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/cp.py +0 -0
  61. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/extract-dir.py +0 -0
  62. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/extract_paper.py +0 -0
  63. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/file-size.py +0 -0
  64. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/mv.py +0 -0
  65. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/peptide.py +0 -0
  66. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/reviz.py +0 -0
  67. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/rm.py +0 -0
  68. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/scihub.py +0 -0
  69. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/scihub_selenium.py +0 -0
  70. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/splash_img.py +0 -0
  71. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/scripts/video.py +0 -0
  72. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/stats/__init__.py +0 -0
  73. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/stats/cluster.py +0 -0
  74. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/stats/df.py +0 -0
  75. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/stats/geography.py +0 -0
  76. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/stats/test.py +0 -0
  77. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/storage/libsci.dll +0 -0
  78. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/storage/libsci.so +0 -0
  79. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/storage/libstats.dll +0 -0
  80. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/storage/libstats.so +0 -0
  81. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/storage/mbapy-cli-scripts-list.json +0 -0
  82. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/web.py +0 -0
  83. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy/web_utils/parse.py +0 -0
  84. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy.egg-info/dependency_links.txt +0 -0
  85. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy.egg-info/entry_points.txt +0 -0
  86. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy.egg-info/requires.txt +0 -0
  87. {mbapy-0.7.2 → mbapy-0.7.3}/mbapy.egg-info/top_level.txt +0 -0
  88. {mbapy-0.7.2 → mbapy-0.7.3}/requirements.json +0 -0
  89. {mbapy-0.7.2 → mbapy-0.7.3}/setup.cfg +0 -0
  90. {mbapy-0.7.2 → mbapy-0.7.3}/test/test_base.py +0 -0
  91. {mbapy-0.7.2 → mbapy-0.7.3}/test/test_game.py +0 -0
  92. {mbapy-0.7.2 → mbapy-0.7.3}/test/test_web.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: mbapy
3
- Version: 0.7.2
3
+ Version: 0.7.3
4
4
  Summary: MyBA in Python
5
5
  Home-page: https://github.com/BHM-Bob/BA_PY
6
6
  Author: BHM-Bob G
@@ -2,15 +2,15 @@
2
2
  Author: BHM-Bob 2262029386@qq.com
3
3
  Date: 2022-11-01 22:16:49
4
4
  LastEditors: BHM-Bob 2262029386@qq.com
5
- LastEditTime: 2024-04-21 21:06:53
5
+ LastEditTime: 2024-04-25 23:17:56
6
6
  Description:
7
7
  '''
8
8
 
9
9
  __title__ = "mbapy"
10
10
  __description__ = "MyBA in Python"
11
11
  __url__ = "https://github.com/BHM-Bob/BA_PY"
12
- __version__ = "0.7.2"
13
- __build__ = "20240421_0"
12
+ __version__ = "0.7.3"
13
+ __build__ = "20240425_0"
14
14
  __author__ = "BHM-Bob G"
15
15
  __author_email__ = "bhmfly@foxmail.com"
16
16
  __license__ = "MIT"
@@ -2,7 +2,7 @@
2
2
  Author: BHM-Bob 2262029386@qq.com
3
3
  Date: 2022-10-19 22:46:30
4
4
  LastEditors: BHM-Bob 2262029386@qq.com
5
- LastEditTime: 2024-03-01 10:09:58
5
+ LastEditTime: 2024-04-25 22:58:26
6
6
  Description:
7
7
  '''
8
8
  import ctypes
@@ -356,6 +356,10 @@ def parameter_checker(*arg_checkers, raise_err = True, **kwarg_checkers):
356
356
 
357
357
  Returns:
358
358
  A decorated function that performs argument validity checks before executing the original function.
359
+
360
+ Notes:
361
+ - If all checkers get passed, the original function is executed.
362
+ - If any checker fails, the function returns None or raises a ValueError, depending on the value of `raise_err`.
359
363
 
360
364
  Example usage:
361
365
  >>> @check_arguments(path = check_parameters_path, head = check_parameters_len)
@@ -366,32 +370,39 @@ def parameter_checker(*arg_checkers, raise_err = True, **kwarg_checkers):
366
370
  def decorator(func):
367
371
  @wraps(func)
368
372
  def wrapper(*args, **kwargs):
369
- # info string
370
373
  info_string = f"Parameter checker for {func.__code__.co_name} : Invalid value for argument "
374
+ def check_arg(checker, arg_name: str, arg_value):
375
+ if not checker(arg_value):
376
+ if raise_err:
377
+ raise ValueError(info_string+arg_name)
378
+ else:
379
+ return put_err(info_string+arg_name, False)
380
+ return True
381
+ # args_name will exclude *args and **kwargs with name of args and kwargs
382
+ args_name = list(func.__code__.co_varnames)[:func.__code__.co_argcount+
383
+ func.__code__.co_kwonlyargcount]
371
384
  # check positional arguments
372
- for i, arg_check in enumerate(arg_checkers):
385
+ for i, arg_checker in enumerate(arg_checkers):
373
386
  if i < len(args):
374
- arg = args[i]
375
- if not arg_check(arg):
376
- arg_name = func.__code__.co_varnames[i]
377
- if raise_err:
378
- raise ValueError(info_string+arg_name)
379
- else:
380
- # directly return a none value, skip the err pop
381
- return put_err(info_string+arg_name, None)
387
+ if not check_arg(arg_checker, args_name[i], args[i]):
388
+ return None
382
389
  # check keyword arguments
383
390
  for arg_name, kwarg_checker in kwarg_checkers.items():
384
- # pass the rigth arg name
385
- if arg_name in func.__code__.co_varnames:
391
+ # if passed the rigth arg name
392
+ if arg_name in args_name:
386
393
  # get the index of the argument
387
- idx = func.__code__.co_varnames.index(arg_name)
388
- # get the argument through the index if passed positionally
389
- arg = args[idx] if idx < len(args) else kwargs[arg_name]
390
- if not kwarg_checker(arg):
391
- if raise_err:
392
- raise ValueError(info_string+arg_name)
393
- else:
394
- return put_err(info_string+arg_name, None)
394
+ idx = args_name.index(arg_name)
395
+ # get arg value
396
+ if idx < len(args):
397
+ arg_value = args[idx]
398
+ elif arg_name in kwargs:
399
+ arg_value = kwargs[arg_name]
400
+ elif func.__defaults__ and idx-len(args) < len(func.__defaults__):
401
+ arg_value = func.__defaults__[idx-len(args)]
402
+ else:
403
+ raise TypeError(f'{func.__code__.co_name}() minssing required argument')
404
+ if not check_arg(kwarg_checker, arg_name, arg_value):
405
+ return None
395
406
  return func(*args, **kwargs)
396
407
  return wrapper
397
408
  return decorator
@@ -681,5 +692,11 @@ __all__ = [
681
692
 
682
693
  if __name__ == '__main__':
683
694
  # dev code
684
- # set_default_kwargs
685
- d = set_default_kwargs({'a':1}, discard_extra=True, eps = 0.5, min_samples = 3)
695
+ class Test:
696
+ @parameter_checker(b = lambda b: b in ['b', 'B'], raise_err=False)
697
+ def __init__(self, a, b: str = 'b', *args, **kwargs) -> None:
698
+ print(a, b)
699
+
700
+ Test('A')
701
+ Test('A', 'A', e = 'E')
702
+ Test('A', 'B', 10)
@@ -0,0 +1,263 @@
1
+ from itertools import chain, combinations
2
+ from typing import Callable, Dict, List, Tuple, Union, Optional
3
+
4
+ import matplotlib.patches as patches
5
+ import matplotlib.pyplot as plt
6
+ import matplotlib.ticker as ticker
7
+ import numpy as np
8
+ import pandas as pd
9
+ import seaborn as sns
10
+ import statsmodels.api as sm
11
+
12
+ if __name__ == '__main__':
13
+ # dev mode
14
+ import mbapy.stats.test as mst
15
+ from mbapy.stats.df import (get_df_data, pro_bar_data, pro_bar_data_R,
16
+ sort_df_factors)
17
+ from mbapy.stats.test import p_value_to_stars
18
+ # Assembly of functions
19
+ from mbapy.plot_utils.bar_utils import AxisLable, pro_bar_data, plot_bar, plot_positional_hue
20
+ from mbapy.plot_utils.line_utils import *
21
+ from mbapy.plot_utils.scatter_utils import plot_reg, plot_scatter, add_scatter_legend
22
+ else:
23
+ # release mode
24
+ from .stats import test as mst
25
+ from .stats.df import (get_df_data, pro_bar_data, pro_bar_data_R,
26
+ sort_df_factors)
27
+ from .stats.test import p_value_to_stars
28
+ # Assembly of functions
29
+ from .plot_utils.bar_utils import AxisLable, pro_bar_data, plot_bar, plot_positional_hue
30
+ from .plot_utils.line_utils import *
31
+ from .plot_utils.scatter_utils import plot_reg, plot_scatter, add_scatter_legend
32
+
33
+ # plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文
34
+ plt.rcParams["font.family"] = 'Times New Roman'
35
+ plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
36
+ colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
37
+
38
+ def rgb2hex(r, g, b):
39
+ return '#'+('{:02X}' * 3).format(r, g, b)
40
+ def hex2rgb(hex:str):
41
+ return [int(hex[i:i+2], 16) for i in (1, 3, 5)]
42
+ def rgbs2hexs(rgbs:List[Tuple[float]]):
43
+ """
44
+ Takes a list of RGB tuples and converts them to a list of hexadecimal color codes.
45
+ Each RGB tuple must contain three floats between 0 and 1 representing the red, green, and blue
46
+ components of the color. Returns a list of hexadecimal color codes as strings.
47
+ """
48
+ return list(map(lambda x : rgb2hex(*[int(x[i]*255) for i in range(3)]),
49
+ rgbs))
50
+
51
+ def get_palette(n:int = 10, mode:Union[None, str] = None, return_n = True) -> List[str]:
52
+ """get a seq of hex colors
53
+ Parameters
54
+ ----------
55
+ n: how many colors required
56
+ mode: kind of colors
57
+ - hls : [default] sns.color_palette('hls', n)
58
+ - green : sum 5 grenns
59
+ - pair : plt.get_cmap('tab20')
60
+ - None : plt.get_cmap('Set1') for n<=9 or plt.get_cmap('Set3') for n<= 12
61
+ """
62
+ assert n >= 1, 'n < 1'
63
+ ret = None
64
+ if mode == 'hls':
65
+ ret = rgbs2hexs(sns.color_palette('hls', n))
66
+ elif n <= 5 and mode == 'green':
67
+ ret = ['#80ab1c', '#405535', '#99b69b', '#92e4ce', '#72cb87'][0:n]
68
+ elif n <= 9:
69
+ ret = rgbs2hexs(plt.get_cmap('Set1').colors)
70
+ elif n <= 12:
71
+ ret = rgbs2hexs(plt.get_cmap('Set3').colors)
72
+ elif n <= 20 and mode == 'pair':
73
+ ret = rgbs2hexs(plt.get_cmap('tab20').colors)
74
+ if return_n and ret is not None:
75
+ ret = ret[:n]
76
+ return ret
77
+
78
+
79
+ def calcu_swarm_pos(x: float, y: np.ndarray, width: float, d: Optional[float] = None):
80
+ """
81
+ This function calculates the x-coordinates for the data points in a swarm plot.
82
+ The x-coordinates are calculated based on the given x-coordinate, y-coordinates,
83
+ and width of the swarm. If d is not None, it will be used as the distance between
84
+ the data points. Otherwise, it will be calculated based on the number of data points.
85
+
86
+ Parameters:
87
+ - x: the x-coordinate of the center of the swarm.
88
+ - y: the y-coordinates of the data points.
89
+ - width: the width of the swarm.
90
+ - d: the distance between the data points. If None, it will be calculated based on the number of data points.
91
+
92
+ Returns:
93
+ - A numpy array of x-coordinates for the data points.
94
+ """
95
+ def _calcu_arithmetic(x, n, w, d):
96
+ if isinstance(d, float) or isinstance(d, int):
97
+ a0 = x - (n-1)*d/2
98
+ return np.linspace(a0, a0+d*(n-1), n)
99
+ if n == 1:
100
+ return x
101
+ else:
102
+ a0, d = x-w/2, w/(n-1)
103
+ return np.linspace(a0, a0+d*(n-1), n)
104
+ ret = np.zeros(len(y))
105
+ for y_u in np.unique(y):
106
+ y_idx = np.where(y == y_u)[0]
107
+ ret[y_idx] = _calcu_arithmetic(x, len(y_idx), width, d)
108
+ return ret
109
+
110
+ def qqplot(tags:List[str], df:pd.DataFrame, figsize = (12, 6), nrows = 1, ncols = 1, **kwargs):
111
+ """
112
+ Generate a QQ-plot for each column in the given DataFrame.
113
+
114
+ Parameters:
115
+ tags (List[str]): A list of column names to generate QQ-plots for.
116
+ df (pd.DataFrame): The DataFrame containing the data.
117
+ figsize (tuple, optional): The size of the figure. Defaults to (12, 6).
118
+ nrows (int, optional): The number of rows in the figure grid. Defaults to 1.
119
+ ncols (int, optional): The number of columns in the figure grid. Defaults to 1.
120
+ **kwargs: Additional keyword arguments including xlim, ylim, title, tick_size, and label_size.
121
+
122
+ Returns:
123
+ None
124
+ """
125
+ axs = []
126
+ fig = plt.figure(figsize = (12, 6))
127
+ for fig_idx in range(1, ncols*nrows+1):
128
+ axs.append(fig.add_subplot(nrows, ncols, fig_idx))
129
+ if 'xlim' in kwargs:
130
+ axs[-1].set_xlim(kwargs['xlim'])
131
+ if 'ylim' in kwargs:
132
+ axs[-1].set_ylim(kwargs['ylim'])
133
+ sm.qqplot(np.array(df[tags[fig_idx-1]]), fit=True, line="45", ax=axs[-1])
134
+ axs[-1].set_title(tags[fig_idx-1]+' - QQPlot', fontdict={'fontsize':15})
135
+ if 'title' in kwargs:
136
+ axs[-1].set_ylim(kwargs['title'][fig_idx-1])
137
+ if 'tick_size' in kwargs:
138
+ axs[-1].tick_params(labelsize = kwargs['tick_size'])
139
+ if 'label_size' in kwargs:
140
+ axs[-1].set_xlabel('Theoretical Quantiles', fontsize = kwargs['label_size'])
141
+ axs[-1].set_ylabel('Sample Quantiles', fontsize = kwargs['label_size'])
142
+ return axs
143
+
144
+ def save_show(path:str, dpi = 300, bbox_inches = 'tight'):
145
+ """
146
+ Saves the current matplotlib figure to a file at the specified path and displays the figure.
147
+
148
+ Parameters:
149
+ path (str): The path where the figure will be saved.
150
+ dpi (int, optional): The resolution of the saved figure in dots per inch. Default is 300.
151
+ bbox_inches (str or Bbox, optional): The portion of the figure to save. Default is 'tight'.
152
+
153
+ Returns:
154
+ None
155
+ """
156
+ plt.tight_layout()
157
+ plt.gcf().savefig(path, dpi=dpi, bbox_inches = bbox_inches)
158
+ plt.show()
159
+
160
+ def plot_stats_star(x1: float, x2: float, h: float, endpoint: float, p_value: float,
161
+ ax = plt, p2star: Callable[[float], str] = p_value_to_stars):
162
+ """
163
+ Params
164
+ - x1: The x-coordinate of the left endpoint.
165
+ - x2: The x-coordinate of the right endpoint.
166
+ - h: The y-coordinate of the horizontal line.
167
+ - endpoint: The height of the endpoint.
168
+ - p_value: The p-value of the difference.
169
+ - ax: The `Axes` instance to plot on. Default is `plt`.
170
+ - p2star: A function that converts a p-value to a string of stars. Default is `p_value_to_stars`.
171
+
172
+ Returns:
173
+ None
174
+ """
175
+ ax.plot([x1, x2], [h, h], color='black')
176
+ ax.plot([x1, x1], [h, h-endpoint], color='black')
177
+ ax.plot([x2, x2], [h, h-endpoint], color='black')
178
+ ax.text((x1+x2)/2, h, p2star(p_value), ha='center')
179
+
180
+ def plot_turkey(means, std_errs, tukey_results, min_star = 1):
181
+ """
182
+ Plot a bar chart showing the means of different groups along with the standard errors.
183
+
184
+ Parameters:
185
+ - means: A list of mean values for each group.
186
+ - std_errs: A list of standard errors for each group.
187
+ - tukey_results: The Tukey's test results object.
188
+
189
+ Returns:
190
+ The current `Axes` instance.
191
+
192
+ This function plots a bar chart using the given mean values and standard errors. It also marks the groups with significant differences based on the Tukey's test results.
193
+ For each combination of groups, the function checks if the corresponding Tukey's test result indicates a significant difference. If so, it plots a horizontal line at the maximum height, vertical lines at the endpoints, and places a text label with stars indicating the p-value of the difference.
194
+ """
195
+ x = np.arange(len(means))
196
+ plt.bar(x, means, yerr=std_errs, capsize=5)
197
+
198
+ combins = np.array(list(combinations(range(len(means)), 2)))
199
+ height = max(means) + max(std_errs)
200
+ min_height = 0.05 * height
201
+ endpoint_height = [height - 0.05 * min_height, height + 0.05 * min_height]
202
+ for i, combination in enumerate(combins):
203
+ if tukey_results.reject[i] \
204
+ and len(p_value_to_stars(tukey_results.pvalues[i])) >= min_star:
205
+ plt.plot(combination, [height, height], color='black')
206
+ plt.plot([combination[0], combination[0]], endpoint_height, color='black')
207
+ plt.plot([combination[1], combination[1]], endpoint_height, color='black')
208
+ plt.text(np.mean(combination), height,
209
+ p_value_to_stars(tukey_results.pvalues[i]), ha='center')
210
+ height += min_height
211
+
212
+ plt.xticks(x, tukey_results.groupsunique)
213
+ return plt.gca()
214
+
215
+
216
+ __all__ = [
217
+ 'AxisLable',
218
+ 'pro_bar_data',
219
+ 'plot_bar',
220
+ 'plot_positional_hue',
221
+
222
+ 'plot_reg',
223
+ 'plot_scatter',
224
+ 'add_scatter_legend',
225
+
226
+ 'rgb2hex',
227
+ 'hex2rgb',
228
+ 'rgbs2hexs',
229
+ 'get_palette',
230
+ 'calcu_swarm_pos',
231
+ 'qqplot',
232
+ 'save_show',
233
+ 'plot_stats_star',
234
+ 'plot_turkey'
235
+ ]
236
+
237
+
238
+ if __name__ == '__main__':
239
+ # dev code
240
+ df = pd.read_excel('./data/plot.xlsx', sheet_name='MWM')
241
+ df['Animal Type'] = df['Animal Type'].astype('str')
242
+ model = mst.multicomp_turkeyHSD({'Animal Type':[]}, 'Duration', df)
243
+ result = mst.turkey_to_table(model)
244
+ print(result)
245
+ # sub_df = get_df_data({'Animal Type':[]}, ['Duration'], df)
246
+ sub_df = pro_bar_data(['Animal Type'], ['Duration'], df)
247
+ # test err
248
+ cols = get_palette(n = 4, mode = 'hls')
249
+ plot_bar(['Animal Type'], ['Duration'], df, err = sub_df['Duration_SE'], jitter = True,
250
+ edgecolor = [cols], linewidth = 5, colors = ['white'], jitter_kwargs = {'size': 10, 'alpha': 1, 'color': [cols]})
251
+ plt.show()
252
+ plot_turkey(sub_df['Duration'], sub_df['Duration_SE'], model)
253
+ plt.show()
254
+
255
+ df = pd.DataFrame({'Month': [5, 5, 6, 6, 7, 7, 8, 8, 9, 9],
256
+ 'Ozone': [23.61538, 22.22445, 29.44444, 18.20790, 59.11538, 31.63584, 59.96154, 39.68121, 31.44828, 24.14182]})
257
+ model = mst.multicomp_turkeyHSD({'Month':[]}, 'Ozone', df)
258
+ result = mst.turkey_to_table(model)
259
+ print(result)
260
+ sub_df = pro_bar_data(['Month'], ['Ozone'], df)
261
+ plot_turkey(sub_df['Ozone'], sub_df['Ozone_SE'], model)
262
+ plt.show()
263
+