• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JoranAngevaare / optim_esm_tools / 12056421220

27 Nov 2024 06:40PM UTC coverage: 76.759% (-6.9%) from 83.696%
12056421220

push

github

web-flow
Region calculation (#201)

* add region calculation

* add docstring

* fix np.float

* add few more tweaks

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix pbar

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix tool

* fix utils locations

* sync minor details

110 of 393 new or added lines in 8 files covered. (27.99%)

1 existing line in 1 file now uncovered.

2368 of 3085 relevant lines covered (76.76%)

3.86 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.64
/optim_esm_tools/plotting/plot_utils.py
1
import os
6✔
2
import typing as ty
6✔
3

4
import numpy as np
6✔
5
import optim_esm_tools as oet
6✔
6

7

8
def legend_kw(**kw) -> dict:
6✔
9
    options = dict(
6✔
10
        bbox_to_anchor=(0.0, 1.02, 1, 0.32),
11
        loc=3,
12
        ncol=3,
13
        mode='expand',
14
        borderaxespad=0.0,
15
        frameon=True,
16
    )
17
    options.update(kw)
6✔
18
    return options
6✔
19

20

21
def save_fig(
6✔
22
    name: str,
23
    file_types: ty.Tuple[str] = ('png', 'pdf'),
24
    save_in: ty.Optional[str] = None,
25
    sub_dir: str = 'figures',
26
    skip: bool = False,
27
    remove_space: bool = True,
28
    **kwargs,
29
):
30
    """Save a figure in the figures dir."""
31
    import matplotlib.pyplot as plt
6✔
32

33
    save_in = save_in or oet.utils.root_folder
6✔
34

35
    kwargs.setdefault('dpi', 150)
6✔
36
    kwargs.setdefault('bbox_inches', 'tight')
6✔
37
    if remove_space:
6✔
38
        name = name.replace(' ', '_')
6✔
39
        save_in = save_in.replace(' ', '')
6✔
40
        sub_dir = sub_dir.replace(' ', '')
6✔
41
    if sub_dir is None:
6✔
NEW
42
        sub_dir = ''
×
43
    for file_type in file_types:
6✔
44
        path = os.path.join(save_in, sub_dir, f'{name}.{file_type}')
6✔
45
        if not os.path.exists(p := os.path.join(save_in, sub_dir)):
6✔
46
            os.makedirs(p, exist_ok=True)
6✔
47
        if skip:
6✔
NEW
48
            print(f'Skip save {path}')
×
NEW
49
            return
×
50
        plt.savefig(path, **kwargs)
6✔
51

52

53
def get_plt_colors():
6✔
54
    """Get matplotlib colors."""
55
    import matplotlib.pyplot as plt
6✔
56
    import matplotlib
6✔
57

58
    my_colors = [matplotlib.colors.to_hex(c) for c in plt.cm.Set1.colors]
6✔
59
    # I don't like the yellowish color
60
    del my_colors[5]
6✔
61
    return my_colors
6✔
62

63

64
def default_plt_params():
6✔
65
    return {
6✔
66
        'axes.grid': True,
67
        'font.size': 18,
68
        'axes.titlesize': 20,
69
        'axes.labelsize': 18,
70
        'axes.linewidth': 2,
71
        'xtick.labelsize': 18,
72
        'ytick.labelsize': 18,
73
        'ytick.major.size': 8,
74
        'ytick.minor.size': 4,
75
        'xtick.major.size': 8,
76
        'xtick.minor.size': 4,
77
        'xtick.major.width': 2,
78
        'xtick.minor.width': 2,
79
        'ytick.major.width': 2,
80
        'ytick.minor.width': 2,
81
        'xtick.direction': 'in',
82
        'ytick.direction': 'in',
83
        'legend.fontsize': 14,
84
        'figure.facecolor': 'w',
85
        'figure.figsize': (8, 6),
86
        'image.cmap': 'viridis',
87
        'lines.linewidth': 2,
88
    }
89

90

91
def setup_plt(use_tex: bool = True, custom_cmap_name: str = 'custom_map'):
6✔
92
    """Change the plots to have uniform style defaults."""
93

94
    import matplotlib.pyplot as plt
6✔
95
    import matplotlib
6✔
96
    from cycler import cycler
6✔
97

98
    params = default_plt_params()
6✔
99
    if use_tex:
6✔
100
        params.update(
6✔
101
            {
102
                'font.family': 'Times New Roman',
103
            },
104
        )
105
    plt.rcParams.update(params)
6✔
106

107
    custom_cycler = cycler(color=get_plt_colors())
6✔
108
    # Could add cycler(marker=['o', 's', 'v', '^', 'D', 'P', '>', 'x'])
109

110
    plt.rcParams.update({'axes.prop_cycle': custom_cycler})
6✔
111
    if use_tex and not os.environ.get('DISABLE_LATEX', False):
6✔
112
        # Allow latex to be disabled from the environment coverage see
113
        matplotlib.rc('text', usetex=True)
6✔
114

115
    from matplotlib.colors import ListedColormap
6✔
116
    import matplotlib as mpl
6✔
117

118
    # Create capped custom map for printing (yellow does not print well)
119
    custom = ListedColormap(mpl.colormaps['viridis'](np.linspace(0, 0.85, 1000)))
6✔
120
    mpl.colormaps.register(custom, name=custom_cmap_name, force=True)
6✔
121
    setattr(mpl.pyplot.cm, custom_cmap_name, custom)
6✔
122

123
    custom_cmap_name += '_r'
6✔
124
    custom = ListedColormap(mpl.colormaps['viridis_r'](np.linspace(0.15, 1, 1000)))
6✔
125
    mpl.colormaps.register(custom, name=custom_cmap_name, force=True)
6✔
126
    setattr(mpl.pyplot.cm, custom_cmap_name, custom)
6✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc