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

KrishnaswamyLab / scprep / 5313380018

pending completion
5313380018

push

github

web-flow
Merge pull request #137 from KrishnaswamyLab/pandas_2

Upgrade to pandas 2.0

15 of 15 new or added lines in 4 files covered. (100.0%)

3052 of 3191 relevant lines covered (95.64%)

0.96 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
1✔
2
from .._lazyload import matplotlib as mpl
1✔
3
from .._lazyload import mpl_toolkits
1✔
4

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

8
plt = mpl.pyplot
1✔
9

10

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

14

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

25

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

55

56
def _is_color_array(c):
1✔
57
    if c is None:
1✔
58
        return False
1✔
59
    else:
60
        try:
1✔
61
            c_rgb = mpl.colors.to_rgba_array(c)
1✔
62
            if np.any(c_rgb > 1):
1✔
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
1✔
68
        except ValueError:
1✔
69
            return False
1✔
70

71

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

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

86

87
@utils._with_pkg(pkg="matplotlib", min_version=3)
1✔
88
def show(fig):
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()
1✔
100
    if _mpl_is_gui_backend():
1✔
101
        if platform.system() == "Windows":
×
102
            plt.show(block=True)
×
103
        else:
104
            fig.show()
×
105

106

107
def _is_default_matplotlibrc():
1✔
108
    __defaults = {
1✔
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():
1✔
118
        if plt.rcParams[k] != v:
1✔
119
            return False
1✔
120
    return True
1✔
121

122

123
def parse_fontsize(size=None, default=None):
1✔
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:
1✔
140
        return size
1✔
141
    elif _is_default_matplotlibrc():
1✔
142
        return default
1✔
143
    else:
144
        return None
1✔
145

146

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

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

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

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

165

166
@utils._with_pkg(pkg="matplotlib", min_version=3)
1✔
167
def shift_ticklabels(axis, dx=0, dy=0):
1✔
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)
1✔
180
    # apply offset transform to all ticklabels.
181
    for label in axis.get_majorticklabels():
1✔
182
        label.set_transform(label.get_transform() + offset)
1✔
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