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

KrishnaswamyLab / scprep / 5314986012

pending completion
5314986012

push

github

scottgigante-immunai
use py3.11

3060 of 3195 relevant lines covered (95.77%)

3.83 hits per line

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

88.37
/scprep/plot/utils.py
1
from .. import utils
4✔
2
from .._lazyload import matplotlib as mpl
4✔
3
from .._lazyload import mpl_toolkits
4✔
4

5
import numpy as np
4✔
6
import platform
4✔
7

8
plt = mpl.pyplot
4✔
9

10

11
def _with_default(param, default):
4✔
12
    return param if param is not None else default
4✔
13

14

15
def _mpl_is_gui_backend():
4✔
16
    try:
4✔
17
        backend = mpl.get_backend()
4✔
18
    except Exception:
×
19
        return False
×
20
    if backend in ["module://ipykernel.pylab.backend_inline", "agg"]:
4✔
21
        return False
4✔
22
    else:
23
        return True
×
24

25

26
def _get_figure(ax=None, figsize=None, subplot_kw=None):
4✔
27
    if subplot_kw is None:
4✔
28
        subplot_kw = {}
4✔
29
    if ax is None:
4✔
30
        if "projection" in subplot_kw and subplot_kw["projection"] == "3d":
4✔
31
            # ensure mplot3d is loaded
32
            mpl_toolkits.mplot3d.Axes3D
4✔
33
        fig, ax = plt.subplots(figsize=figsize, subplot_kw=subplot_kw)
4✔
34
        show_fig = True
4✔
35
    else:
36
        try:
4✔
37
            fig = ax.get_figure()
4✔
38
        except AttributeError as e:
4✔
39
            if not isinstance(ax, mpl.axes.Axes):
4✔
40
                raise TypeError(
4✔
41
                    "Expected ax as a matplotlib.axes.Axes. " "Got {}".format(type(ax))
42
                )
43
            else:
44
                raise e
×
45
        if "projection" in subplot_kw:
4✔
46
            if subplot_kw["projection"] == "3d" and not isinstance(
4✔
47
                ax, mpl_toolkits.mplot3d.Axes3D
48
            ):
49
                raise TypeError(
4✔
50
                    "Expected ax with projection='3d'. " "Got 2D axis instead."
51
                )
52
        show_fig = False
4✔
53
    return fig, ax, show_fig
4✔
54

55

56
def _is_color_array(c):
4✔
57
    if c is None:
4✔
58
        return False
4✔
59
    else:
60
        try:
4✔
61
            c_rgb = mpl.colors.to_rgba_array(c)
4✔
62
            if np.any(c_rgb > 1):
4✔
63
                # possibly https://github.com/matplotlib/matplotlib/issues/13912
64
                for i in np.argwhere(c_rgb > 1).flatten():
×
65
                    if isinstance(c[i], str):
×
66
                        return False
×
67
            return True
4✔
68
        except ValueError:
4✔
69
            return False
4✔
70

71

72
def _in_ipynb():
4✔
73
    """Check if we are running in a Jupyter Notebook.
74

75
    Credit to https://stackoverflow.com/a/24937408/3996580
76
    """
77
    __VALID_NOTEBOOKS = [
4✔
78
        "<class 'google.colab._shell.Shell'>",
79
        "<class 'ipykernel.zmqshell.ZMQInteractiveShell'>",
80
    ]
81
    try:
4✔
82
        return str(type(get_ipython())) in __VALID_NOTEBOOKS
4✔
83
    except NameError:
4✔
84
        return False
4✔
85

86

87
@utils._with_pkg(pkg="matplotlib", min_version=3)
4✔
88
def show(fig):
3✔
89
    """Show a matplotlib Figure correctly, regardless of platform.
90

91
    If running a Jupyter notebook, we avoid running `fig.show`. If running
92
    in Windows, it is necessary to run `plt.show` rather than `fig.show`.
93

94
    Parameters
95
    ----------
96
    fig : matplotlib.Figure
97
        Figure to show
98
    """
99
    fig.tight_layout()
4✔
100
    if _mpl_is_gui_backend():
4✔
101
        if platform.system() == "Windows":
×
102
            plt.show(block=True)
×
103
        else:
104
            fig.show()
×
105

106

107
def _is_default_matplotlibrc():
4✔
108
    __defaults = {
4✔
109
        "axes.labelsize": "medium",
110
        "axes.titlesize": "large",
111
        "figure.titlesize": "large",
112
        "legend.fontsize": "medium",
113
        "legend.title_fontsize": None,
114
        "xtick.labelsize": "medium",
115
        "ytick.labelsize": "medium",
116
    }
117
    for k, v in __defaults.items():
4✔
118
        if plt.rcParams[k] != v:
4✔
119
            return False
4✔
120
    return True
4✔
121

122

123
def parse_fontsize(size=None, default=None):
4✔
124
    """Parse the user's input font size.
125

126
    Returns `size` if explicitly set by user,
127
    `default` if not set by user and the user's matplotlibrc is also default,
128
    or `None` otherwise (falling back to mpl defaults)
129

130
    Parameters
131
    ----------
132
    size
133
        Fontsize explicitly set by user
134
    default
135
        Desired default font size in
136
        xx-small, x-small, small, medium, large, x-large, xx-large,
137
        larger, smaller
138
    """
139
    if size is not None:
4✔
140
        return size
4✔
141
    elif _is_default_matplotlibrc():
4✔
142
        return default
4✔
143
    else:
144
        return None
4✔
145

146

147
class temp_fontsize(object):
4✔
148
    """Context manager to temporarily change matplotlib font size."""
149

150
    def __init__(self, size=None):
4✔
151
        """Initialize the context manager."""
152
        if size is None:
4✔
153
            size = plt.rcParams["font.size"]
4✔
154
        self.size = size
4✔
155

156
    def __enter__(self):
4✔
157
        """Temporarily set the font size."""
158
        self.old_size = plt.rcParams["font.size"]
4✔
159
        plt.rcParams["font.size"] = self.size
4✔
160

161
    def __exit__(self, type, value, traceback):
4✔
162
        """Change the font size back to default."""
163
        plt.rcParams["font.size"] = self.old_size
4✔
164

165

166
@utils._with_pkg(pkg="matplotlib", min_version=3)
4✔
167
def shift_ticklabels(axis, dx=0, dy=0):
4✔
168
    """Shifts ticklabels on an axis.
169

170
    Parameters
171
    ----------
172
    axis : matplotlib.axis.{X,Y}Axis, mpl_toolkits.mplot3d.axis3d.{X,Y,Z}Axis
173
        Axis on which to draw labels and ticks
174
    dx : float, optional (default: 0)
175
        Horizontal shift
176
    dy : float, optional (default: 0)
177
    """
178
    # Create offset transform by 5 points in x direction
179
    offset = mpl.transforms.ScaledTranslation(dx, dy, axis.get_figure().dpi_scale_trans)
4✔
180
    # apply offset transform to all ticklabels.
181
    for label in axis.get_majorticklabels():
4✔
182
        label.set_transform(label.get_transform() + offset)
4✔
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