Skip to content

Overview of the API

logo logo

This part of the project documentation focuses on an information-oriented approach. Use it as a reference for the technical implementation of the calculator project code.

configuration

configuration

BackendConfiguration

Source code in plotex/configuration/configuration.py
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
class BackendConfiguration():

    CONFIG_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config_files/config.txt")
    CONFIG_URL = "https://gist.githubusercontent.com/rg089/26d06984604c92cf452e77ee345434ea/raw/98730d2afa1be6381b4c9c0f6f18da440200fc9a/latex_plots.txt"


    def __init__(self, url=None, override=False, **kwargs):
        """initializing the configuration class

        Args:
            url: the url of the config to create a new config, defaults
                to None
            override: if the config from the specified link already
                exists, whether to create it again (used if in-place
                changes have been made to the url)
            kwargs: other keyword arguments can include arguments for theme, style, palette etc.
        """
        if url is None:
            self.url = BackendConfiguration.CONFIG_URL
        self.override = override

        self.style = None
        self.palette = None
        self.__init_theme(**kwargs)


    def __fetch_content(self, url):
        """fetches the config params from the url if not locally present

        Raises:
            Exception: if issue in fetching and decoding

        Returns:
            returns the content from the url
        """
        print(f"[INFO] Fetching configuration parameters from {url}!")
        try:
            r = requests.get(url)
            content = r.content.decode()
        except:
            raise Exception('An error occured while fetching and decoding the url content')

        return content


    def __generate_content_path(self):
        """creates the config by using a cached file, or fetching from the internet if cached file not present

        Returns:
            the file path of the config file
        """
        url_hash = hash_url(self.url)
        fpath = combine_hash(BackendConfiguration.CONFIG_FILE_PATH, url_hash)

        exists = check_if_exists(fpath)
        if exists and not self.override: # If file exists and we don't need to override
            return fpath

        content = self.__fetch_content(url=self.url)
        save_file(content=content, fpath=fpath)

        return fpath


    def __init_theme(self, **kwargs):
        # Set style
        self.style = find_value_from_keys(kwargs, ['style', 'theme', 'background'])

        # Set palette
        self.palette = find_value_from_keys(kwargs, ['palette', 'cmap'])
        if self.palette is None: # If palette wasn't specified but colorblind argument is given
            use_colorblind = find_value_from_keys(kwargs, ['colorblind', 'colourblind', 'blind'])
            if use_colorblind:
                self.palette = 'colorblind'


    def reset(self):
        """reset the parameters to the original matplotlib ones"""
        plt.rcdefaults()


    def initialize(self):
        """initializes the configuration file by setting the style from the config file"""

        if self.style is not None:
            sns.set_style(self.style)

        # Nothe that the settings in the config file will override the conflicting ones in the specified seaborn style
        final_path = self.__generate_content_path()
        plt.style.use(final_path)

        if self.palette is not None:
            sns.set_palette(self.palette)
__fetch_content(url)

fetches the config params from the url if not locally present

Raises:

Type Description
Exception

if issue in fetching and decoding

Returns:

Type Description

returns the content from the url

Source code in plotex/configuration/configuration.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def __fetch_content(self, url):
    """fetches the config params from the url if not locally present

    Raises:
        Exception: if issue in fetching and decoding

    Returns:
        returns the content from the url
    """
    print(f"[INFO] Fetching configuration parameters from {url}!")
    try:
        r = requests.get(url)
        content = r.content.decode()
    except:
        raise Exception('An error occured while fetching and decoding the url content')

    return content
__generate_content_path()

creates the config by using a cached file, or fetching from the internet if cached file not present

Returns:

Type Description

the file path of the config file

Source code in plotex/configuration/configuration.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def __generate_content_path(self):
    """creates the config by using a cached file, or fetching from the internet if cached file not present

    Returns:
        the file path of the config file
    """
    url_hash = hash_url(self.url)
    fpath = combine_hash(BackendConfiguration.CONFIG_FILE_PATH, url_hash)

    exists = check_if_exists(fpath)
    if exists and not self.override: # If file exists and we don't need to override
        return fpath

    content = self.__fetch_content(url=self.url)
    save_file(content=content, fpath=fpath)

    return fpath
__init__(url=None, override=False, **kwargs)

initializing the configuration class

Parameters:

Name Type Description Default
url

the url of the config to create a new config, defaults to None

None
override

if the config from the specified link already exists, whether to create it again (used if in-place changes have been made to the url)

False
kwargs

other keyword arguments can include arguments for theme, style, palette etc.

{}
Source code in plotex/configuration/configuration.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def __init__(self, url=None, override=False, **kwargs):
    """initializing the configuration class

    Args:
        url: the url of the config to create a new config, defaults
            to None
        override: if the config from the specified link already
            exists, whether to create it again (used if in-place
            changes have been made to the url)
        kwargs: other keyword arguments can include arguments for theme, style, palette etc.
    """
    if url is None:
        self.url = BackendConfiguration.CONFIG_URL
    self.override = override

    self.style = None
    self.palette = None
    self.__init_theme(**kwargs)
initialize()

initializes the configuration file by setting the style from the config file

Source code in plotex/configuration/configuration.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def initialize(self):
    """initializes the configuration file by setting the style from the config file"""

    if self.style is not None:
        sns.set_style(self.style)

    # Nothe that the settings in the config file will override the conflicting ones in the specified seaborn style
    final_path = self.__generate_content_path()
    plt.style.use(final_path)

    if self.palette is not None:
        sns.set_palette(self.palette)
reset()

reset the parameters to the original matplotlib ones

Source code in plotex/configuration/configuration.py
85
86
87
def reset(self):
    """reset the parameters to the original matplotlib ones"""
    plt.rcdefaults()

main

Plotex

a facade over various different functions in the module for a direct one-point access

Source code in plotex/main.py
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
class Plotex:
    """a facade over various different functions in the module for a direct one-point access"""
    def __init__(self, **kwargs):
        """initialize the controller

        Args:
            **kwargs: parameters for the config file, the params include
                `url` \
        (the url for the config file), `cmap/palette` for the cmap, `style/theme` \
        for the seaborn style
        """
        init = kwargs.get('initialize', True)
        if init:
            self.init(**kwargs)


    def init(self, **kwargs):
        """initialize the controller

        Args:
            **kwargs: parameters for the config file, the params include
                `url` \
        (the url for the config file), `cmap/palette` for the cmap, `style/theme` \
        for the seaborn style
        """
        self.config = BackendConfiguration(**kwargs)
        self.sizer = Sizing(config=self.config)
        self.params = None
        self.config.initialize()


    def skeleton(self, width=None, publisher=None, width_in_pts=True, reinitialize=True, fraction=1, 
                   subplots=(1, 1), **kwargs):
        """finds the ideal size of the plot and adjusts the text sizes according to the required dimensions
        this is a dummy function wrapped over the `get_figure` function from Sizing to enable direct access

        Args:
            width: the width, defaults to None
            publisher: the name of the publisher, defaults to None
            width_in_pts: whether the width is in points, defaults to
                True
            reinitialize: whether to reinitialize the config to itys
                defaults, defaults to True
            fraction: the fraction of the width supplied to use,
                defaults to 1
            subplots: (nrows, ncols), defaults to (1, 1)

        Returns:
            fig, axes if return_size is False, else (width, height)
        """

        output = self.sizer.get_size(width=width, publisher=publisher, width_in_pts=width_in_pts, reinitialize=reinitialize,
                              fraction=fraction, subplots=subplots, **kwargs)
        self.params = plt.rcParams.copy()
        return output

    def update_textsize(self, reinitialize=True, **kwargs):
        """This function changes the font size of various text elements in the plot such as xlabel, \
        ylabel, title, ticks, etc., by a specified offset. Uses deterministic and probabilistic \
        matching to determine and map the keyword argument to the required property

        Args:
            reinitialize: initialize size params to those created by
                `get_size` after adjusting for\ columns, fraction etc.
            **kwargs: flexible keyword arguments specified by the user,
                where the name of \
        the argument is the key and the offset is the value.
        """
        self.sizer.update_textsize(reinitialize=reinitialize, **kwargs)


    def update_textweight(self, reinitialize=False, **kwargs):
        """This function changes the font weight of various text elements in the plot such as xlabel, \
        ylabel, title. The values are 'light', 'normal', 'bold'.
        Uses deterministic and probabilistic matching to determine and map the keyword
        \ argument to the required property

        Args:
            reinitialize: initialize size params to those created by
                `get_size` after adjusting for\ columns, fraction etc.
            **kwargs: flexible keyword arguments specified by the user,
                where the name of \
        the argument is the key and the weight is the value.
        """
        self.sizer.update_textweight(reinitialize=reinitialize, **kwargs)


    def remove_ticks(self, xtick=True, ytick=True):
        """remove the tick marks

        Args:
            xtick: remove ticks on x-axis, defaults to True
            ytick: remove ticks on y-axis, defaults to True
        """
        self.sizer.remove_ticks(xtick=xtick, ytick=ytick)


    def set_lim(self, ax, xlims=(None, None), ylims=(None, None)):
        """set the starting and ending points of the x and y axes

        Args:
            ax: the matplotlib axis object
            xlims: tuple containing the (min, max) values of the \ x
                axis, defaults to (None, None)
            ylims: tuple containing the (min, max) values of the \ y
                axis, defaults to (None, None)
        """
        if xlims[0] is not None and xlims[1] is not None:
            ax.set_xlim(xlims[0], xlims[1])
        if ylims[0] is not None and ylims[1] is not None:
            ax.set_ylim(ylims[0], ylims[1])


    @copy_docstring(set_text)
    def set_text(self, plt=None, ax=None, xlabel=None, ylabel=None, title=None, xticklocs=None, xticklabels=None,
               xtickrot=None, yticklocs=None, yticklabels=None, ytickrot=None):
        set_text(plt=plt, ax=ax, xlabel=xlabel, ylabel=ylabel, title=title, xticklocs=xticklocs, xticklabels=xticklabels,
               xtickrot=xtickrot, yticklocs=yticklocs, yticklabels=yticklabels, ytickrot=ytickrot)


    @copy_docstring(save)
    def save(self, save_path, fig=None, plt=None, format='pdf'):
        save(save_path, fig=fig, plt=plt, format=format)

__init__(**kwargs)

initialize the controller

Parameters:

Name Type Description Default
**kwargs

parameters for the config file, the params include url (the url for the config file), cmap/palette for the cmap, style/theme for the seaborn style

{}
Source code in plotex/main.py
10
11
12
13
14
15
16
17
18
19
20
21
def __init__(self, **kwargs):
    """initialize the controller

    Args:
        **kwargs: parameters for the config file, the params include
            `url` \
    (the url for the config file), `cmap/palette` for the cmap, `style/theme` \
    for the seaborn style
    """
    init = kwargs.get('initialize', True)
    if init:
        self.init(**kwargs)

init(**kwargs)

initialize the controller

Parameters:

Name Type Description Default
**kwargs

parameters for the config file, the params include url (the url for the config file), cmap/palette for the cmap, style/theme for the seaborn style

{}
Source code in plotex/main.py
24
25
26
27
28
29
30
31
32
33
34
35
36
def init(self, **kwargs):
    """initialize the controller

    Args:
        **kwargs: parameters for the config file, the params include
            `url` \
    (the url for the config file), `cmap/palette` for the cmap, `style/theme` \
    for the seaborn style
    """
    self.config = BackendConfiguration(**kwargs)
    self.sizer = Sizing(config=self.config)
    self.params = None
    self.config.initialize()

remove_ticks(xtick=True, ytick=True)

remove the tick marks

Parameters:

Name Type Description Default
xtick

remove ticks on x-axis, defaults to True

True
ytick

remove ticks on y-axis, defaults to True

True
Source code in plotex/main.py
 95
 96
 97
 98
 99
100
101
102
def remove_ticks(self, xtick=True, ytick=True):
    """remove the tick marks

    Args:
        xtick: remove ticks on x-axis, defaults to True
        ytick: remove ticks on y-axis, defaults to True
    """
    self.sizer.remove_ticks(xtick=xtick, ytick=ytick)

set_lim(ax, xlims=(None, None), ylims=(None, None))

set the starting and ending points of the x and y axes

Parameters:

Name Type Description Default
ax

the matplotlib axis object

required
xlims

tuple containing the (min, max) values of the \ x axis, defaults to (None, None)

(None, None)
ylims

tuple containing the (min, max) values of the \ y axis, defaults to (None, None)

(None, None)
Source code in plotex/main.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def set_lim(self, ax, xlims=(None, None), ylims=(None, None)):
    """set the starting and ending points of the x and y axes

    Args:
        ax: the matplotlib axis object
        xlims: tuple containing the (min, max) values of the \ x
            axis, defaults to (None, None)
        ylims: tuple containing the (min, max) values of the \ y
            axis, defaults to (None, None)
    """
    if xlims[0] is not None and xlims[1] is not None:
        ax.set_xlim(xlims[0], xlims[1])
    if ylims[0] is not None and ylims[1] is not None:
        ax.set_ylim(ylims[0], ylims[1])

skeleton(width=None, publisher=None, width_in_pts=True, reinitialize=True, fraction=1, subplots=(1, 1), **kwargs)

finds the ideal size of the plot and adjusts the text sizes according to the required dimensions this is a dummy function wrapped over the get_figure function from Sizing to enable direct access

Parameters:

Name Type Description Default
width

the width, defaults to None

None
publisher

the name of the publisher, defaults to None

None
width_in_pts

whether the width is in points, defaults to True

True
reinitialize

whether to reinitialize the config to itys defaults, defaults to True

True
fraction

the fraction of the width supplied to use, defaults to 1

1
subplots

(nrows, ncols), defaults to (1, 1)

(1, 1)

Returns:

Type Description

fig, axes if return_size is False, else (width, height)

Source code in plotex/main.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def skeleton(self, width=None, publisher=None, width_in_pts=True, reinitialize=True, fraction=1, 
               subplots=(1, 1), **kwargs):
    """finds the ideal size of the plot and adjusts the text sizes according to the required dimensions
    this is a dummy function wrapped over the `get_figure` function from Sizing to enable direct access

    Args:
        width: the width, defaults to None
        publisher: the name of the publisher, defaults to None
        width_in_pts: whether the width is in points, defaults to
            True
        reinitialize: whether to reinitialize the config to itys
            defaults, defaults to True
        fraction: the fraction of the width supplied to use,
            defaults to 1
        subplots: (nrows, ncols), defaults to (1, 1)

    Returns:
        fig, axes if return_size is False, else (width, height)
    """

    output = self.sizer.get_size(width=width, publisher=publisher, width_in_pts=width_in_pts, reinitialize=reinitialize,
                          fraction=fraction, subplots=subplots, **kwargs)
    self.params = plt.rcParams.copy()
    return output

update_textsize(reinitialize=True, **kwargs)

This function changes the font size of various text elements in the plot such as xlabel, ylabel, title, ticks, etc., by a specified offset. Uses deterministic and probabilistic matching to determine and map the keyword argument to the required property

Parameters:

Name Type Description Default
reinitialize

initialize size params to those created by get_size after adjusting for\ columns, fraction etc.

True
**kwargs

flexible keyword arguments specified by the user, where the name of the argument is the key and the offset is the value.

{}
Source code in plotex/main.py
64
65
66
67
68
69
70
71
72
73
74
75
76
def update_textsize(self, reinitialize=True, **kwargs):
    """This function changes the font size of various text elements in the plot such as xlabel, \
    ylabel, title, ticks, etc., by a specified offset. Uses deterministic and probabilistic \
    matching to determine and map the keyword argument to the required property

    Args:
        reinitialize: initialize size params to those created by
            `get_size` after adjusting for\ columns, fraction etc.
        **kwargs: flexible keyword arguments specified by the user,
            where the name of \
    the argument is the key and the offset is the value.
    """
    self.sizer.update_textsize(reinitialize=reinitialize, **kwargs)

update_textweight(reinitialize=False, **kwargs)

This function changes the font weight of various text elements in the plot such as xlabel, ylabel, title. The values are 'light', 'normal', 'bold'. Uses deterministic and probabilistic matching to determine and map the keyword \ argument to the required property

Parameters:

Name Type Description Default
reinitialize

initialize size params to those created by get_size after adjusting for\ columns, fraction etc.

False
**kwargs

flexible keyword arguments specified by the user, where the name of the argument is the key and the weight is the value.

{}
Source code in plotex/main.py
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def update_textweight(self, reinitialize=False, **kwargs):
    """This function changes the font weight of various text elements in the plot such as xlabel, \
    ylabel, title. The values are 'light', 'normal', 'bold'.
    Uses deterministic and probabilistic matching to determine and map the keyword
    \ argument to the required property

    Args:
        reinitialize: initialize size params to those created by
            `get_size` after adjusting for\ columns, fraction etc.
        **kwargs: flexible keyword arguments specified by the user,
            where the name of \
    the argument is the key and the weight is the value.
    """
    self.sizer.update_textweight(reinitialize=reinitialize, **kwargs)

plotsize

figsize

Sizing

Source code in plotex/plotsize/figsize.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
class Sizing():

    CONFIG_URL = 'https://gist.githubusercontent.com/rg089/92540eef5ee88de5d2770a453c85c489/raw/b127ba7b0e7eff3c5eddf1202f01595e5c60c949/size_config.json'
    CONFIG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config_files/size_config.json")


    def __init__(self, config=None, **config_kwargs):
        """initialize the sizing class

        Args:
            config: the config file, defaults to None
        """
        self.config = config
        if self.config is None:
            self.config = BackendConfiguration(**config_kwargs)
            self.config.initialize()
        self.params = None
        self.size_config = self.__load_config()


    def __load_config(self):
        if os.path.exists(Sizing.CONFIG_PATH):
            with open(Sizing.CONFIG_PATH, 'r') as f:
                config = json.load(f)
        else:
            r = requests.get(Sizing.CONFIG_URL)
            config = r.json()
            save_file(content=config, fpath=Sizing.CONFIG_PATH)

        return config


    def __save_params(self):
        """save a copy of the current rcParams"""
        self.params = plt.rcParams.copy()


    def __load_params(self):
        """load the current saved copy of the rcParams"""
        if self.params is not None:
            plt.rcParams.update(self.params)


    def __get_width_publisher(self, publisher, width=None):
        """get the width in pts given the name of the publisher

        Args:
            publisher (str): the name of the publisher
            width (float): if width is specified, then it is cached

        Returns:
            float: the width in pts
        """
        publisher = publisher.lower()

        if width is not None:
            self.__cache_width(publisher, width)
            return width

        width = self.__read_width(publisher)

        return width


    def __read_width(self, publisher:str):
        """
        reads the width from the config file for the supplied publisher. \
        If not found, then use the ACL format width

        Args:
            publisher (str): the publisher name

        Returns:
            float: the width in pts
        """
        if publisher in self.size_config['width']:
            width = self.size_config['width'][publisher]
        else:
            print(f'[INFO] Publisher "{publisher}" not found, setting to ACL format!')
            print('To save this publisher, give the values for both publisher and width')
            width = 455.244

        return width


    def __cache_width(self, publisher:str, width:float):
        """
        caches the `publisher:width` mapping 

        Args:
            publisher (str): the publisher
            width (float): the width in pts
        """
        print(f'[INFO] Caching {publisher}:{width} mapping!')
        self.size_config['width'][publisher] = width
        save_file(self.size_config, Sizing.CONFIG_PATH)


    def adjust_font_size(self, subplots, fraction, **kwargs):
        """adjust the font_size based on the fraction and number of columns and
        saves the adjusted params

        Args:
            subplots: at uple of (nrow, ncols)
            fraction: fraction of the total width to use
        """
        _, num_cols = subplots

        font_params = ['font.size', 'axes.titlesize', 'legend.title_fontsize', 'xtick.labelsize', 'ytick.labelsize', 'axes.labelsize', 'legend.fontsize']
        for param in font_params:
            curr_value = float(plt.rcParams[param])
            plt.rcParams[param] = math.ceil(curr_value/num_cols*fraction)
        self.__save_params()


    def __find_matching_param(self, key, main_params, special_params={}):
        """find the matching paramater to the key in the matplotlib.rcParams file specified by
        the main_params and special_params

        Args:
            key: the key with which we search
            main_params: the main dictionary, with keys as rcParams keys
                and values as their shortened versions
            special_params: direct mapping to handle exceptions where
                probabilstic matching might fail, defaults to {}

        Returns:
            the found parameter, or None if not found
        """
        all_matches = list(main_params.keys()) + list(main_params.values()) # Search over both keys and values

        if key in special_params:
            parameter = special_params[key]
        else:
            parameter = difflib.get_close_matches(key, all_matches, n=1)

            if not parameter:
                print(f"[INFO] No match found for argument: {key}!")
                return None

            parameter = parameter[0]

            if parameter not in main_params:
                parameter = [k for k, v in main_params.items() if v == parameter][0]

        return parameter


    def update_textsize(self, reinitialize=True, **kwargs):
        """This function changes the font size of various text elements in the plot such as xlabel,
        ylabel, title, sticks, etc., by a specified offset. Uses deterministic and probabilistic
        matching to determine and map the keyword argument to the required property

        Args:
            reinitialize: initialize size params to those created by
                `get_size` after adjusting for columns, fraction etc.
            **kwargs: flexible keyword arguments specified by the user,
                where the name of
        the argument is the key and the offset is the value.
        """
        if reinitialize:
            self.__load_params()

        font_params = {'font.size': 'fontsize',
                    'axes.titlesize': 'title',
                    'legend.title_fontsize': 'legendtitle',
                    'xtick.labelsize': 'xticks',
                    'ytick.labelsize': 'yticks',
                    'axes.labelsize': 'labels',
                    'legend.fontsize': 'legend'}

        special_params = {'xlabel': 'axes.labelsize', 'ylabel': 'axes.labelsize', 
                          'title': 'axes.titlesize', 'legend': 'legend.fontsize'}

        for key, value in kwargs.items():
            font_param = self.__find_matching_param(key=key, main_params=font_params, 
                                                    special_params=special_params)
            if font_param is None: continue
            current_size = plt.rcParams[font_param]
            plt.rcParams[font_param] = current_size + value


    def update_textweight(self, reinitialize=False, **kwargs):
        """This function changes the font weight of various text elements in the plot such as xlabel,
        ylabel, title. The values are 'light', 'normal', 'bold'.
        Uses deterministic and probabilistic matching to determine and map the keyword
        argument to the required property

        Args:
            reinitialize: initialize size params to those created by
                `get_size` after adjusting for columns, fraction etc.
            **kwargs: flexible keyword arguments specified by the user,
                where the name of
        the argument is the key and the weight is the value.
        """
        if reinitialize:
            self.__load_params()

        font_params = {
                    'axes.titleweight': 'title',
                    'axes.labelweight': 'label'}

        special_params = {'xlabel': 'axes.labelweight', 'ylabel': 'axes.labelweight', 
                          'title': 'axes.titlweight'}

        for key, value in kwargs.items():
            font_param = self.__find_matching_param(key, main_params=font_params, 
                                                    special_params=special_params)
            if font_param is None: continue            
            plt.rcParams[font_param] = value


    def remove_ticks(self, xtick=True, ytick=True):
        """remove the tick marks

        Args:
            xtick: remove ticks on x-axis, defaults to True
            ytick: remove ticks on y-axis, defaults to True
        """
        if xtick:
            plt.rcParams['xtick.major.size'] = 0
        if ytick:
            plt.rcParams['ytick.major.size'] = 0


    def set_lim(self, ax, xlims=(None, None), ylims=(None, None)):
        """set the starting and ending points of the x and y axes

        Args:
            ax: the matplotlib axis object
            xlims: tuple containing the (min, max) values of the x
                axis, defaults to (None, None)
            ylims: tuple containing the (min, max) values of the y
                axis, defaults to (None, None)
        """
        if xlims[0] is not None and xlims[1] is not None:
            ax.set_xlim(xlims[0], xlims[1])
        if ylims[0] is not None and ylims[1] is not None:
            ax.set_ylim(ylims[0], ylims[1])


    def convert_width_to_inches(self, width=None, publisher=None):
        """convert width from pts to inches

        Args:
            width: the given width in pts, defaults to None
            publisher: the name of the publisher, defaults to None

        Returns:
            the width in inches
        """
        if publisher is not None:
            width_pt = self.__get_width_publisher(publisher=publisher, width=width)
        else:
            width_pt = width 
        fig_width_pt = width_pt 
        inches_per_pt = 1 / 72.27

        fig_width_in = fig_width_pt * inches_per_pt
        return fig_width_in


    def get_size(self, width=None, publisher=None, width_in_pts=True, reinitialize=True, fraction=1, 
                   subplots=(1, 1), **kwargs):
        """finds the ideal size of the plot and adjusts the text sizes according to the required dimensions
            if both publisher and width are specified, then the publisher:width is cached

        Args:
            width: the width, defaults to None
            publisher: the name of the publisher, defaults to None
            width_in_pts: whether the width is in points, defaults to
                True
            reinitialize: whether to reinitialize the config to itys
                defaults, defaults to True
            fraction: the fraction of the width supplied to use,
                defaults to 1
            subplots: (nrows, ncols), defaults to (1, 1)

        Returns:
            figsize (width, height)
        """
        assert publisher is not None or width is not None, "Either set the width or the format."

        if reinitialize: self.config.initialize()

        golden_ratio = (5**.5 - 1) / 2

        if width_in_pts:
            fig_width_in = self.convert_width_to_inches(width=width, publisher=publisher)
        else:
            fig_width_in = width

        fig_width_in *= fraction
        fig_height_in = fig_width_in * golden_ratio * (subplots[0] / subplots[1])

        self.adjust_font_size(subplots=subplots, fraction=fraction, **kwargs)

        return (fig_width_in, fig_height_in)
__cache_width(publisher, width)

caches the publisher:width mapping

Parameters:

Name Type Description Default
publisher str

the publisher

required
width float

the width in pts

required
Source code in plotex/plotsize/figsize.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
def __cache_width(self, publisher:str, width:float):
    """
    caches the `publisher:width` mapping 

    Args:
        publisher (str): the publisher
        width (float): the width in pts
    """
    print(f'[INFO] Caching {publisher}:{width} mapping!')
    self.size_config['width'][publisher] = width
    save_file(self.size_config, Sizing.CONFIG_PATH)
__find_matching_param(key, main_params, special_params={})

find the matching paramater to the key in the matplotlib.rcParams file specified by the main_params and special_params

Parameters:

Name Type Description Default
key

the key with which we search

required
main_params

the main dictionary, with keys as rcParams keys and values as their shortened versions

required
special_params

direct mapping to handle exceptions where probabilstic matching might fail, defaults to {}

{}

Returns:

Type Description

the found parameter, or None if not found

Source code in plotex/plotsize/figsize.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def __find_matching_param(self, key, main_params, special_params={}):
    """find the matching paramater to the key in the matplotlib.rcParams file specified by
    the main_params and special_params

    Args:
        key: the key with which we search
        main_params: the main dictionary, with keys as rcParams keys
            and values as their shortened versions
        special_params: direct mapping to handle exceptions where
            probabilstic matching might fail, defaults to {}

    Returns:
        the found parameter, or None if not found
    """
    all_matches = list(main_params.keys()) + list(main_params.values()) # Search over both keys and values

    if key in special_params:
        parameter = special_params[key]
    else:
        parameter = difflib.get_close_matches(key, all_matches, n=1)

        if not parameter:
            print(f"[INFO] No match found for argument: {key}!")
            return None

        parameter = parameter[0]

        if parameter not in main_params:
            parameter = [k for k, v in main_params.items() if v == parameter][0]

    return parameter
__get_width_publisher(publisher, width=None)

get the width in pts given the name of the publisher

Parameters:

Name Type Description Default
publisher str

the name of the publisher

required
width float

if width is specified, then it is cached

None

Returns:

Name Type Description
float

the width in pts

Source code in plotex/plotsize/figsize.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def __get_width_publisher(self, publisher, width=None):
    """get the width in pts given the name of the publisher

    Args:
        publisher (str): the name of the publisher
        width (float): if width is specified, then it is cached

    Returns:
        float: the width in pts
    """
    publisher = publisher.lower()

    if width is not None:
        self.__cache_width(publisher, width)
        return width

    width = self.__read_width(publisher)

    return width
__init__(config=None, **config_kwargs)

initialize the sizing class

Parameters:

Name Type Description Default
config

the config file, defaults to None

None
Source code in plotex/plotsize/figsize.py
16
17
18
19
20
21
22
23
24
25
26
27
def __init__(self, config=None, **config_kwargs):
    """initialize the sizing class

    Args:
        config: the config file, defaults to None
    """
    self.config = config
    if self.config is None:
        self.config = BackendConfiguration(**config_kwargs)
        self.config.initialize()
    self.params = None
    self.size_config = self.__load_config()
__load_params()

load the current saved copy of the rcParams

Source code in plotex/plotsize/figsize.py
47
48
49
50
def __load_params(self):
    """load the current saved copy of the rcParams"""
    if self.params is not None:
        plt.rcParams.update(self.params)
__read_width(publisher)

reads the width from the config file for the supplied publisher. If not found, then use the ACL format width

Parameters:

Name Type Description Default
publisher str

the publisher name

required

Returns:

Name Type Description
float

the width in pts

Source code in plotex/plotsize/figsize.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def __read_width(self, publisher:str):
    """
    reads the width from the config file for the supplied publisher. \
    If not found, then use the ACL format width

    Args:
        publisher (str): the publisher name

    Returns:
        float: the width in pts
    """
    if publisher in self.size_config['width']:
        width = self.size_config['width'][publisher]
    else:
        print(f'[INFO] Publisher "{publisher}" not found, setting to ACL format!')
        print('To save this publisher, give the values for both publisher and width')
        width = 455.244

    return width
__save_params()

save a copy of the current rcParams

Source code in plotex/plotsize/figsize.py
42
43
44
def __save_params(self):
    """save a copy of the current rcParams"""
    self.params = plt.rcParams.copy()
adjust_font_size(subplots, fraction, **kwargs)

adjust the font_size based on the fraction and number of columns and saves the adjusted params

Parameters:

Name Type Description Default
subplots

at uple of (nrow, ncols)

required
fraction

fraction of the total width to use

required
Source code in plotex/plotsize/figsize.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def adjust_font_size(self, subplots, fraction, **kwargs):
    """adjust the font_size based on the fraction and number of columns and
    saves the adjusted params

    Args:
        subplots: at uple of (nrow, ncols)
        fraction: fraction of the total width to use
    """
    _, num_cols = subplots

    font_params = ['font.size', 'axes.titlesize', 'legend.title_fontsize', 'xtick.labelsize', 'ytick.labelsize', 'axes.labelsize', 'legend.fontsize']
    for param in font_params:
        curr_value = float(plt.rcParams[param])
        plt.rcParams[param] = math.ceil(curr_value/num_cols*fraction)
    self.__save_params()
convert_width_to_inches(width=None, publisher=None)

convert width from pts to inches

Parameters:

Name Type Description Default
width

the given width in pts, defaults to None

None
publisher

the name of the publisher, defaults to None

None

Returns:

Type Description

the width in inches

Source code in plotex/plotsize/figsize.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def convert_width_to_inches(self, width=None, publisher=None):
    """convert width from pts to inches

    Args:
        width: the given width in pts, defaults to None
        publisher: the name of the publisher, defaults to None

    Returns:
        the width in inches
    """
    if publisher is not None:
        width_pt = self.__get_width_publisher(publisher=publisher, width=width)
    else:
        width_pt = width 
    fig_width_pt = width_pt 
    inches_per_pt = 1 / 72.27

    fig_width_in = fig_width_pt * inches_per_pt
    return fig_width_in
get_size(width=None, publisher=None, width_in_pts=True, reinitialize=True, fraction=1, subplots=(1, 1), **kwargs)

finds the ideal size of the plot and adjusts the text sizes according to the required dimensions if both publisher and width are specified, then the publisher:width is cached

Parameters:

Name Type Description Default
width

the width, defaults to None

None
publisher

the name of the publisher, defaults to None

None
width_in_pts

whether the width is in points, defaults to True

True
reinitialize

whether to reinitialize the config to itys defaults, defaults to True

True
fraction

the fraction of the width supplied to use, defaults to 1

1
subplots

(nrows, ncols), defaults to (1, 1)

(1, 1)

Returns:

Type Description

figsize (width, height)

Source code in plotex/plotsize/figsize.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
def get_size(self, width=None, publisher=None, width_in_pts=True, reinitialize=True, fraction=1, 
               subplots=(1, 1), **kwargs):
    """finds the ideal size of the plot and adjusts the text sizes according to the required dimensions
        if both publisher and width are specified, then the publisher:width is cached

    Args:
        width: the width, defaults to None
        publisher: the name of the publisher, defaults to None
        width_in_pts: whether the width is in points, defaults to
            True
        reinitialize: whether to reinitialize the config to itys
            defaults, defaults to True
        fraction: the fraction of the width supplied to use,
            defaults to 1
        subplots: (nrows, ncols), defaults to (1, 1)

    Returns:
        figsize (width, height)
    """
    assert publisher is not None or width is not None, "Either set the width or the format."

    if reinitialize: self.config.initialize()

    golden_ratio = (5**.5 - 1) / 2

    if width_in_pts:
        fig_width_in = self.convert_width_to_inches(width=width, publisher=publisher)
    else:
        fig_width_in = width

    fig_width_in *= fraction
    fig_height_in = fig_width_in * golden_ratio * (subplots[0] / subplots[1])

    self.adjust_font_size(subplots=subplots, fraction=fraction, **kwargs)

    return (fig_width_in, fig_height_in)
remove_ticks(xtick=True, ytick=True)

remove the tick marks

Parameters:

Name Type Description Default
xtick

remove ticks on x-axis, defaults to True

True
ytick

remove ticks on y-axis, defaults to True

True
Source code in plotex/plotsize/figsize.py
222
223
224
225
226
227
228
229
230
231
232
def remove_ticks(self, xtick=True, ytick=True):
    """remove the tick marks

    Args:
        xtick: remove ticks on x-axis, defaults to True
        ytick: remove ticks on y-axis, defaults to True
    """
    if xtick:
        plt.rcParams['xtick.major.size'] = 0
    if ytick:
        plt.rcParams['ytick.major.size'] = 0
set_lim(ax, xlims=(None, None), ylims=(None, None))

set the starting and ending points of the x and y axes

Parameters:

Name Type Description Default
ax

the matplotlib axis object

required
xlims

tuple containing the (min, max) values of the x axis, defaults to (None, None)

(None, None)
ylims

tuple containing the (min, max) values of the y axis, defaults to (None, None)

(None, None)
Source code in plotex/plotsize/figsize.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def set_lim(self, ax, xlims=(None, None), ylims=(None, None)):
    """set the starting and ending points of the x and y axes

    Args:
        ax: the matplotlib axis object
        xlims: tuple containing the (min, max) values of the x
            axis, defaults to (None, None)
        ylims: tuple containing the (min, max) values of the y
            axis, defaults to (None, None)
    """
    if xlims[0] is not None and xlims[1] is not None:
        ax.set_xlim(xlims[0], xlims[1])
    if ylims[0] is not None and ylims[1] is not None:
        ax.set_ylim(ylims[0], ylims[1])
update_textsize(reinitialize=True, **kwargs)

This function changes the font size of various text elements in the plot such as xlabel, ylabel, title, sticks, etc., by a specified offset. Uses deterministic and probabilistic matching to determine and map the keyword argument to the required property

Parameters:

Name Type Description Default
reinitialize

initialize size params to those created by get_size after adjusting for columns, fraction etc.

True
**kwargs

flexible keyword arguments specified by the user, where the name of

{}

the argument is the key and the offset is the value.

Source code in plotex/plotsize/figsize.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def update_textsize(self, reinitialize=True, **kwargs):
    """This function changes the font size of various text elements in the plot such as xlabel,
    ylabel, title, sticks, etc., by a specified offset. Uses deterministic and probabilistic
    matching to determine and map the keyword argument to the required property

    Args:
        reinitialize: initialize size params to those created by
            `get_size` after adjusting for columns, fraction etc.
        **kwargs: flexible keyword arguments specified by the user,
            where the name of
    the argument is the key and the offset is the value.
    """
    if reinitialize:
        self.__load_params()

    font_params = {'font.size': 'fontsize',
                'axes.titlesize': 'title',
                'legend.title_fontsize': 'legendtitle',
                'xtick.labelsize': 'xticks',
                'ytick.labelsize': 'yticks',
                'axes.labelsize': 'labels',
                'legend.fontsize': 'legend'}

    special_params = {'xlabel': 'axes.labelsize', 'ylabel': 'axes.labelsize', 
                      'title': 'axes.titlesize', 'legend': 'legend.fontsize'}

    for key, value in kwargs.items():
        font_param = self.__find_matching_param(key=key, main_params=font_params, 
                                                special_params=special_params)
        if font_param is None: continue
        current_size = plt.rcParams[font_param]
        plt.rcParams[font_param] = current_size + value
update_textweight(reinitialize=False, **kwargs)

This function changes the font weight of various text elements in the plot such as xlabel, ylabel, title. The values are 'light', 'normal', 'bold'. Uses deterministic and probabilistic matching to determine and map the keyword argument to the required property

Parameters:

Name Type Description Default
reinitialize

initialize size params to those created by get_size after adjusting for columns, fraction etc.

False
**kwargs

flexible keyword arguments specified by the user, where the name of

{}

the argument is the key and the weight is the value.

Source code in plotex/plotsize/figsize.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def update_textweight(self, reinitialize=False, **kwargs):
    """This function changes the font weight of various text elements in the plot such as xlabel,
    ylabel, title. The values are 'light', 'normal', 'bold'.
    Uses deterministic and probabilistic matching to determine and map the keyword
    argument to the required property

    Args:
        reinitialize: initialize size params to those created by
            `get_size` after adjusting for columns, fraction etc.
        **kwargs: flexible keyword arguments specified by the user,
            where the name of
    the argument is the key and the weight is the value.
    """
    if reinitialize:
        self.__load_params()

    font_params = {
                'axes.titleweight': 'title',
                'axes.labelweight': 'label'}

    special_params = {'xlabel': 'axes.labelweight', 'ylabel': 'axes.labelweight', 
                      'title': 'axes.titlweight'}

    for key, value in kwargs.items():
        font_param = self.__find_matching_param(key, main_params=font_params, 
                                                special_params=special_params)
        if font_param is None: continue            
        plt.rcParams[font_param] = value

utils

general

check_if_exists(fpath)

checks if fpath exists

Parameters:

Name Type Description Default
fpath str

the file path to check

required

:return bool: whether the path exists

Source code in plotex/utils/general.py
32
33
34
35
36
37
38
39
def check_if_exists(fpath):
    """checks if fpath exists

    Args:
        fpath (str): the file path to check
    :return bool: whether the path exists
    """
    return os.path.exists(fpath)

combine_hash(fpath, hashed)

combines the file name with the hashcode and returns the absolute path

Parameters:

Name Type Description Default
fpath

fpath

required
hashed

ahash code

required

Returns:

Type Description

the absolute combine path

Source code in plotex/utils/general.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def combine_hash(fpath, hashed):
    """combines the file name with the hashcode and returns the absolute path

    Args:
        fpath: fpath
        hashed: ahash code

    Returns:
        the absolute combine path
    """
    assert fpath.endswith('.txt')

    stripped_path = fpath.rstrip('.txt')
    final_path = f"{stripped_path}_{hashed}.txt"
    final_path = os.path.abspath(final_path)

    return final_path

find_value_from_keys(main_dict, keys)

traverses the specified key list, and if any key is found in the dictionary, returns the corresponding value, else None

Parameters:

Name Type Description Default
main_dict

the dictionary to search in

required
keys

the list of keys

required

Returns:

Type Description

the value if found, else None

Source code in plotex/utils/general.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def find_value_from_keys(main_dict, keys):
    """traverses the specified key list, and if any key is found in the dictionary,
    returns the corresponding value, else None

    Args:
        main_dict: the dictionary to search in
        keys: the list of keys

    Returns:
        the value if found, else None
    """
    for key in keys:
        if key in main_dict:
            return main_dict[key]

    return None

save(save_path, fig=None, plt=None, format='pdf')

utility function to save the figure

Parameters:

Name Type Description Default
save_path

the save path for the figure (including the extension)

required
fig

the figure object, defaults to None

None
plt

the plt object, defaults to None

None
format

the format of the output plot, defaults to 'pdf'

'pdf'
Source code in plotex/utils/general.py
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def save(save_path, fig=None, plt=None, format='pdf'):
    """utility function to save the figure

    Args:
        save_path: the save path for the figure (including the
            extension)
        fig: the figure object, defaults to None
        plt: the plt object, defaults to None
        format: the format of the output plot, defaults to 'pdf'
    """
    assert fig is not None or plt is not None

    if fig is not None:
        fig.savefig(save_path, format=format)
    if plt is not None:
        plt.savefig(save_path, format=format)

save_file(content, fpath)

saves the supplied content in a text file

Parameters:

Name Type Description Default
content str/dict

the content

required
fpath str

the file path to save at

required
Source code in plotex/utils/general.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def save_file(content, fpath):
    """saves the supplied content in a text file

    Args:
        content (str/dict): the content
        fpath (str): the file path to save at
    """
    base_folder = os.path.dirname(fpath)
    os.makedirs(base_folder, exist_ok=True)

    if fpath.endswith('.json'):
        with open(fpath, "w") as f:
            json.dump(content, f)
    else:
        assert isinstance(content, str)
        with open(fpath, "w") as f:
            f.write(content)

hashing

hash_url(url)

generate a hash for the url

Parameters:

Name Type Description Default
url

the url string

required

Returns:

Type Description

the generated hash

Source code in plotex/utils/hashing.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def hash_url(url):
    """generate a hash for the url

    Args:
        url: the url string

    Returns:
        the generated hash
    """
    # Take the hash of the URL
    url_hash = hashlib.sha1(url.encode('utf-8')).hexdigest()
    # Encode the hash in base64
    file_name = base64.b64encode(url_hash.encode('utf-8')).decode('utf-8')
    # Remove any characters that are not safe for use in a file name
    file_name = file_name.replace('/', '_').replace('+', '-')
    # Truncate the file name to a maximum length
    file_name = file_name[:10]
    return file_name

plotting

custom_legend(ax, text, xy=(0.5, 0.5), box=True, box_bgcolor=(1.0, 1, 1, 1), box_edgecolor=(0.0, 0.0, 0.0, 0.1))

create a custom legend/text (without color strip)

Args:
    ax: mpl axes object
    text: the text to add (str or list); if list added with `

` xy: the (x,y) offset fraction, relative to the BOTTOM-LEFT point, defaults to (0.5, 0.5) box: whether to add a bounding box, defaults to True box_bgcolor: the background color of the box, defaults to (1.0, 1, 1, 1) box_edgecolor: the edge color of the box, defaults to (0.0, 0.0, 0.0, 0.1)

Returns:
    `ax`, the axis object
Source code in plotex/utils/plotting.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def custom_legend(ax, text, xy=(0.5, 0.5), box=True, box_bgcolor=(1.0, 1, 1, 1),
                  box_edgecolor=(0.0, 0.0, 0.0, 0.1)):
    """create a custom legend/text (without color strip)

    Args:
        ax: mpl axes object
        text: the text to add (str or list); if list added with `\n`
        xy: the (x,y) offset fraction, relative to the BOTTOM-LEFT
            point, defaults to (0.5, 0.5)
        box: whether to add a bounding box, defaults to True
        box_bgcolor: the background color of the box, defaults to (1.0,
            1, 1, 1)
        box_edgecolor: the edge color of the box, defaults to (0.0, 0.0,
            0.0, 0.1)

    Returns:
        `ax`, the axis object
    """

    if isinstance(text, list):
        text = '\n'.join(text)

    assert isinstance(text, str)

    if box:
        ax.annotate(text,
                xy=xy, xycoords='axes fraction',
                textcoords='offset points',
                bbox=dict(boxstyle="round", fc=box_bgcolor,
                          ec=box_edgecolor))
    else:
        ax.annotate(text,
                xy=xy, xycoords='axes fraction',
                textcoords='offset points')

    return ax

optimize_labels(labels, values)

optimizes the bar chart labels by interweaving the labels based on their length to minimize overlap

Parameters:

Name Type Description Default
labels

the original labels

required
values

the original values

required

Returns:

Type Description

optimized labels, values

Source code in plotex/utils/plotting.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def optimize_labels(labels, values):
    """optimizes the bar chart labels by interweaving the labels based on their length to minimize overlap

    Args:
        labels: the original labels
        values: the original values

    Returns:
        optimized labels, values
    """
    mapper = {l:v for l,v in zip(labels, values)}
    sorted_labels = sorted(labels, key=len)

    n = len(labels)
    start, end = 0, n-1

    final_labels = []

    while end >= start:
        if end == start:
            final_labels.append(sorted_labels[start])
        else:
            final_labels.append(sorted_labels[start])
            final_labels.append(sorted_labels[end])
        start += 1
        end -= 1

    final_values = [mapper[label] for label in final_labels]
    return final_labels, final_values

set_text(plt=None, ax=None, xlabel=None, ylabel=None, title=None, xticklocs=None, xticklabels=None, xtickrot=None, yticklocs=None, yticklabels=None, ytickrot=None)

set xlabel/ylabel/xticks/yticks/title (including rotation of ticks)

Parameters:

Name Type Description Default
plt plt

the matplotlib pyplot object

None
ax matplotlib.axes.Axes

axis on which to label

None
xlabel

the xlabel string, defaults to None

None
ylabel

the ylabel string, defaults to None

None
title

the title string, defaults to None

None
xticklocs

the location of xticks, defaults to None

None
xticklabels

the labels of xticks, defaults to None

None
xtickrot

the rotation angle in degrees of xtick labels, defaults to None

None
yticklocs

the location of yticks, defaults to None

None
yticklabels

the labels of yticks, defaults to None

None
ytickrot

the rotation angle in degrees of ytick labels, defaults to None

None
Source code in plotex/utils/plotting.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def set_text(plt:plt=None, ax:matplotlib.axes.Axes=None, xlabel=None, ylabel=None, title=None, xticklocs=None, xticklabels=None,
               xtickrot=None, yticklocs=None, yticklabels=None, ytickrot=None):
    """set xlabel/ylabel/xticks/yticks/title (including rotation of ticks)

    Args:
        plt: the matplotlib pyplot object
        ax: axis on which to label
        xlabel: the xlabel string, defaults to None
        ylabel: the ylabel string, defaults to None
        title: the title string, defaults to None
        xticklocs: the location of xticks, defaults to None
        xticklabels: the labels of xticks, defaults to None
        xtickrot: the rotation angle in degrees of xtick labels,
            defaults to None
        yticklocs: the location of yticks, defaults to None
        yticklabels: the labels of yticks, defaults to None
        ytickrot: the rotation angle in degrees of ytick labels,
            defaults to None
    """

    assert plt is not None or ax is not None

    if xlabel is not None:
        if ax is not None: ax.set_xlabel(xlabel)
        elif plt is not None: plt.xlabel(xlabel)

    if ylabel is not None:
        if ax is not None: ax.set_ylabel(ylabel)
        elif plt is not None: plt.ylabel(ylabel)

    if title is not None:
        if ax is not None: ax.set_title(title)
        elif plt is not None: plt.title(title)

    if xtickrot is not None:
        if ax is not None: ax.tick_params(axis='x', rotation=xtickrot)
        elif plt is not None: plt.xticks(rotation=xtickrot)

    assert xticklabels is None or (xticklabels is not None and xticklocs is not None)
    if xticklocs is not None:
        if ax is not None: ax.set_xticks(xticklocs, labels=xticklabels)
        elif plt is not None: plt.xticks(ticks=xticklocs, labels=xticklabels)

    if ytickrot is not None:
        if ax is not None: ax.tick_params(axis='y', rotation=ytickrot)
        elif plt is not None: plt.yticks(rotation=ytickrot)

    assert yticklabels is None or (yticklabels is not None and yticklocs is not None)
    if yticklocs is not None:
        if ax is not None: ax.set_yticks(yticklocs, labels=yticklabels)
        elif plt is not None: plt.yticks(ticks=yticklocs, labels=yticklabels)