8000 Apply suggestions from code review · matplotlib/matplotlib@e688f03 · GitHub
[go: up one dir, main page]

Skip to content

Commit e688f03

Browse files
trygvradQuLogic
andcommitted
Apply suggestions from code review
Co-authored-by: Elliott Sales de Andrade <quantum.analyst@gmail.com>
1 parent 77da937 commit e688f03

File tree

5 files changed

+53
-55
lines changed

5 files changed

+53
-55
lines changed

lib/matplotlib/_cm_bivar.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# auto-genreated by https://github.com/trygvrad/multivariate_colormaps
1+
# auto-generated by https://github.com/trygvrad/multivariate_colormaps
22
# date: 2024-05-24
33

44
import numpy as np

lib/matplotlib/_cm_multivar.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# auto-genreated by https://github.com/trygvrad/multivariate_colormaps
1+
# auto-generated by https://github.com/trygvrad/multivariate_colormaps
22
# date: 2024-05-28
33

44
from .colors import LinearSegmentedColormap, MultivarColormap
@@ -157,10 +157,10 @@
157157
]}
158158

159159
cmap_families = {
160-
'2VarAddA': MultivarColormap([cmaps['2VarAddA' + str(i)] for i in range(2)],
160+
'2VarAddA': MultivarColormap([cmaps[f'2VarAddA{i}'] for i in range(2)],
161161
'sRGB_add', name='2VarAddA'),
162-
'2VarSubA': MultivarColormap([cmaps['2VarSubA' + str(i)] for i in range(2)],
162+
'2VarSubA': MultivarColormap([cmaps[f'2VarSubA{i}'] for i in range(2)],
163163
'sRGB_sub', name='2VarSubA'),
164-
'3VarAddA': MultivarColormap([cmaps['3VarAddA' + str(i)] for i in range(3)],
164+
'3VarAddA': MultivarColormap([cmaps[f'3VarAddA{i}'] for i in range(3)],
165165
'sRGB_add', name='3VarAddA'),
166166
}

lib/matplotlib/colors.py

Lines changed: 44 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1351,10 +1351,10 @@ def __call__(self, X, alpha=None, bytes=False, clip=True):
13511351
if alpha is not None:
13521352
if clip:
13531353
alpha = np.clip(alpha, 0, 1)
1354-
if alpha.shape not in [(), np.array(X[0]).shape]:
1354+
if np.shape(alpha) not in [(), np.shape(X[0])]:
13551355
raise ValueError(
1356-
f"alpha is array-like but its shape {alpha.shape} does "
1357-
f"not match that of X[0] {np.array(X[0]).shape}")
1356+
f"alpha is array-like but its shape {np.shape(alpha)} does "
1357+
f"not match that of X[0] {np.shape(X[0])}")
13581358
rgba[..., -1] *= alpha
13591359

13601360
if bytes:
@@ -1385,14 +1385,14 @@ def __copy__(self):
13851385
def __eq__(self, other):
13861386
if not isinstance(other, MultivarColormap):
13871387
return False
1388-
if not len(self) == len(other):
1388+
if len(self) != len(other):
13891389
return False
13901390
for c0, c1 in zip(self, other):
1391-
if not c0 == c1:
1391+
if c0 != c1:
13921392
return False
13931393
if not all(self._rgba_bad == other._rgba_bad):
13941394
return False
1395-
if not self.combination_mode == other.combination_mode:
1395+
if self.combination_mode != other.combination_mode:
13961396
return False
13971397
return True
13981398

@@ -1430,7 +1430,7 @@ def resampled(self, lutshape):
14301430
MultivarColormap
14311431
"""
14321432

1433-
if not np.iterable(lutshape) or not len(lutshape) == len(self):
1433+
if not np.iterable(lutshape) or len(lutshape) != len(self):
14341434
raise ValueError(f"lutshape must be of length {len(self)}")
14351435
new_cmap = self.copy()
14361436
for i, s in enumerate(lutshape):
@@ -1447,7 +1447,7 @@ def with_extremes(self, *, bad=None, under=None, over=None):
14471447
14481448
Parameters
14491449
----------
1450-
bad : None or Matplotlib color
1450+
bad : None or :mpltype:`color`
14511451
If Matplotlib color, the bad value is set accordingly in the copy
14521452
14531453
under : None or tuple of length matching the length of the MultivarColormap
@@ -1468,17 +1468,19 @@ def with_extremes(self, *, bad=None, under=None, over=None):
14681468
if bad is not None:
14691469
new_cm._rgba_bad = to_rgba(bad)
14701470
if under is not None:
1471-
if not np.iterable(under) or not len(under) == len(new_cm):
1471+
if not np.iterable(under) or len(under) != len(new_cm):
14721472
raise ValueError("*under* must contain a color for each scalar colormap"
14731473
f" i.e. be of length {len(new_cm)}.")
14741474
else:
1475-
[c.set_under(b) for c, b in zip(new_cm, under)]
1475+
for c, b in zip(new_cm, under):
1476+
c.set_under(b)
14761477
if over is not None:
1477-
if not np.iterable(over) or not len(over) == len(new_cm):
1478+
if not np.iterable(over) or len(over) != len(new_cm):
14781479
raise ValueError("*over* must contain a color for each scalar colormap"
14791480
f" i.e. be of length {len(new_cm)}.")
14801481
else:
1481-
[c.set_over(b) for c, b in zip(new_cm, over)]
1482+
for c, b in zip(new_cm, over):
1483+
c.set_over(b)
14821484
return new_cm
14831485

14841486
@property
@@ -1511,9 +1513,9 @@ def _repr_html_(self):
15111513

15121514
class BivarColormap:
15131515
"""
1514-
Baseclass for all bivarate to RGBA mappings.
1516+
Base class for all bivariate to RGBA mappings.
15151517
1516-
Designed as a drop-in replcement for Colormap when using a 2D
1518+
Designed as a drop-in replacement for Colormap when using a 2D
15171519
lookup table. To be used with `~matplotlib.cm.VectorMappable`.
15181520
"""
15191521

@@ -1527,7 +1529,7 @@ def __init__(self, N=256, M=256, shape='square', origin=(0, 0),
15271529
M : int
15281530
The number of RGB quantization levels along the second axis.
15291531
If None, M = N
1530-
shape: str 'square' or 'circle' or 'ignore' or 'circleignore'
1532+
shape: {'square', 'circle', 'ignore', 'circleignore'}
15311533
15321534
- 'square' each variate is clipped to [0,1] independently
15331535
- 'circle' the variates are clipped radially to the center
@@ -1594,7 +1596,7 @@ def __call__(self, X, alpha=None, bytes=False):
15941596
if len(X) != 2:
15951597
raise ValueError(
15961598
f'For a `BivarColormap` the data must have a first dimension '
1597-
f'{2}, not {len(X)}')
1599+
f'2, not {len(X)}')
15981600

15991601
if not self._isinit:
16001602
self._init()
@@ -1621,8 +1623,7 @@ def __call__(self, X, alpha=None, bytes=False):
16211623
X1[X1 == self.M] = self.M - 1
16221624

16231625
# Pre-compute the masks before casting to int (which can truncate)
1624-
mask_outside = (X0 < 0) | (X1 < 0) \
1625-
| (X0 >= self.N) | (X1 >= self.M)
1626+
mask_outside = (X0 < 0) | (X1 < 0) | (X0 >= self.N) | (X1 >= self.M)
16261627
# If input was masked, get the bad mask from it; else mask out nans.
16271628
mask_bad_0 = X0.mask if np.ma.is_masked(X0) else np.isnan(X0)
16281629
mask_bad_1 = X1.mask if np.ma.is_masked(X1) else np.isnan(X1)
@@ -1650,10 +1651,10 @@ def __call__(self, X, alpha=None, bytes=False):
16501651
alpha = np.clip(alpha, 0, 1)
16511652
if bytes:
16521653
alpha *= 255 # Will be cast to uint8 upon assignment.
1653-
if alpha.shape not in [(), np.array(X0).shape]:
1654+
if np.shape(alpha) not in [(), np.shape(X0)]:
16541655
raise ValueError(
1655-
f"alpha is array-like but its shape {alpha.shape} does "
1656-
f"not match that of X[0] {np.array(X0).shape}")
1656+
f"alpha is array-like but its shape {np.shape(alpha)} does "
1657+
f"not match that of X[0] {np.shape(X0)}")
16571658
rgba[..., -1] = alpha
16581659
# If the "bad" color is all zeros, then ignore alpha input.
16591660
if (np.array(self._rgba_bad) == 0).all():
@@ -1713,7 +1714,7 @@ def __eq__(self, other):
17131714
return False
17141715
if not np.array_equal(self._rgba_outside, other._rgba_outside):
17151716
return False
1716-
if not self.shape == other.shape:
1717+
if self.shape != other.shape:
17171718
return False
17181719
return True
17191720

@@ -1728,6 +1729,7 @@ def get_outside(self):
17281729
def resampled(self, lutshape, transposed=False):
17291730
"""
17301731
Return a new colormap with *lutshape* entries.
1732+
17311733
Note that this function does not move the origin.
17321734
17331735
Parameters
@@ -1748,7 +1750,7 @@ def resampled(self, lutshape, transposed=False):
17481750
BivarColormap
17491751
"""
17501752

1751-
if not np.iterable(lutshape) or not len(lutshape) == 2:
1753+
if not np.iterable(lutshape) or len(lutshape) != 2:
17521754
raise ValueError("lutshape must be of length 2")
17531755
lutshape = [lutshape[0], lutshape[1]]
17541756
if lutshape[0] is None or lutshape[0] == 1:
@@ -1776,7 +1778,7 @@ def resampled(self, lutshape, transposed=False):
17761778
else:
17771779
x_1 = np.linspace(1, 0, lutshape[1])[np.newaxis, :] * np.ones(lutshape)
17781780

1779-
# we need to use shape = 'sqare' while resampling the colormap.
1781+
# we need to use shape = 'square' while resampling the colormap.
17801782
# if the colormap has shape = 'circle' we would otherwise get *outside* in the
17811783
# resampled colormap
17821784
shape_memory = self._shape
@@ -1785,7 +1787,7 @@ def resampled(self, lutshape, transposed=False):
17851787
new_lut = self((x_1, x_0))
17861788
new_cmap = BivarColormapFromImage(new_lut, name=self.name,
17871789
shape=shape_memory,
1788-
origin=(self.origin[1], self.origin[0]))
1790+
origin=self.origin[::-1])
17891791
else:
17901792
new_lut = self((x_0, x_1))
17911793
new_cmap = BivarColormapFromImage(new_lut, name=self.name,
@@ -1801,12 +1803,8 @@ def reversed(self, axis_0=True, axis_1=True):
18011803
"""
18021804
Reverses both or one of the axis.
18031805
"""
1804-
r_0 = 1
1805-
if axis_0:
1806-
r_0 = -1
1807-
r_1 = 1
1808-
if axis_1:
1809-
r_1 = -1
1806+
r_0 = -1 if axis_0 else 1
1807+
r_1 = -1 if axis_1 else 1
18101808
return self.resampled((r_0, r_1))
18111809

18121810
def transposed(self):
@@ -1823,22 +1821,22 @@ def with_extremes(self, *, bad=None, outside=None, shape=None, origin=None):
18231821
18241822
Parameters
18251823
----------
1826-
bad : None or Matplotlib color
1824+
bad : None or :mpltype:`color`
18271825
If Matplotlib color, the *bad* value is set accordingly in the copy
18281826
1829-
outside : None or Matplotlib color
1827+
outside : None or :mpltype:`color`
18301828
If Matplotlib color and shape is 'ignore' or 'circleignore', values
18311829
*outside* the colormap are colored accordingly in the copy
18321830
1833-
shape: str 'square' or 'circle' or 'ignore' or 'circleignore'
1831+
shape : {'square', 'circle', 'ignore', 'circleignore'}
18341832
18351833
- If 'square' each variate is clipped to [0,1] independently
18361834
- If 'circle' the variates are clipped radially to the center
18371835
of the colormap, and a circular mask is applied when the colormap
18381836
is displayed
18391837
- If 'ignore' the variates are not clipped, but instead assigned the
18401838
*outside* color
1841-
- If 'circleignore' a circular mask is applied, but the data is not
1839+
- If 'circleignore' a circular mask is applied, but the data is not
18421840
clipped and instead assigned the *outside* color
18431841
18441842
origin: (float, float)
@@ -1890,7 +1888,7 @@ def _clip(self, X):
18901888
----------
18911889
X: np.array
18921890
array of floats or ints to be clipped
1893-
shape: str 'square' or 'circle' or 'ignore' or 'circleignore'
1891+
shape : {'square', 'circle', 'ignore', 'circleignore'}
18941892
18951893
- If 'square' each variate is clipped to [0,1] independently
18961894
- If 'circle' the variates are clipped radially to the center
@@ -1921,7 +1919,7 @@ def _clip(self, X):
19211919

19221920
elif self.shape == 'circle' or self.shape == 'circleignore':
19231921
for X_part in X:
1924-
if not X_part.dtype.kind == "f":
1922+
if X_part.dtype.kind != "f":
19251923
raise NotImplementedError(
19261924
"Circular bivariate colormaps are only"
19271925
" implemented for use with with floats")
@@ -1944,14 +1942,14 @@ def __getitem__(self, item):
19441942
if origin_1_as_int > self.M-1:
19451943
origin_1_as_int = self.M-1
19461944
one_d_lut = self._lut[:, origin_1_as_int]
1947-
new_cmap = ListedColormap(one_d_lut, name=self.name+'_0', N=self.N)
1945+
new_cmap = ListedColormap(one_d_lut, name=f'{self.name}_0', N=self.N)
19481946

19491947
elif item == 1:
19501948
origin_0_as_int = int(self._origin[0]*self.N)
19511949
if origin_0_as_int > self.N-1:
19521950
origin_0_as_int = self.N-1
19531951
one_d_lut = self._lut[origin_0_as_int, :]
1954-
new_cmap = ListedColormap(one_d_lut, name=self.name+'_1', N=self.M)
1952+
new_cmap = ListedColormap(one_d_lut, name=f'{self.name}_1', N=self.M)
19551953
else:
19561954
raise KeyError(f"only 0 or 1 are"
19571955
f" valid keys for BivarColormap, not {item!r}")
@@ -2025,15 +2023,15 @@ def copy(self):
20252023

20262024
class SegmentedBivarColormap(BivarColormap):
20272025
"""
2028-
BivarColormap object generated by supersampling a regular grid
2026+
BivarColormap object generated by supersampling a regular grid.
20292027
20302028
Parameters
20312029
----------
2032-
patch : nparray of shape (k, k, 3)
2033-
This patch gets supersamples to a lut of shape (N, M, 4)
2030+
patch : np.array of shape (k, k, 3)
2031+
This patch gets supersampled to a lut of shape (N, M, 4).
20342032
N : int
20352033
The number of RGB quantization levels along each axis.
2036-
shape: str 'square' or 'circle' or 'ignore' or 'circleignore'
2034+
shape: {'square', 'circle', 'ignore', 'circleignore'}
20372035
20382036
- If 'square' each variate is clipped to [0,1] independently
20392037
- If 'circle' the variates are clipped radially to the center
@@ -2073,13 +2071,13 @@ def _init(self):
20732071

20742072
class BivarColormapFromImage(BivarColormap):
20752073
"""
2076-
BivarColormap object generated by supersampling a regular grid
2074+
BivarColormap object generated by supersampling a regular grid.
20772075
20782076
Parameters
20792077
----------
20802078
lut : nparray of shape (N, M, 3) or (N, M, 4)
20812079
The look-up-table
2082-
shape: str 'square' or 'circle' or 'ignore' or 'circleignore'
2080+
shape: {'square', 'circle', 'ignore', 'circleignore'}
20832081
20842082
- If 'square' each variate is clipped to [0,1] independently
20852083
- If 'circle' the variates are clipped radially to the center
@@ -2099,7 +2097,7 @@ class BivarColormapFromImage(BivarColormap):
20992097
"""
21002098

21012099
def __init__(self, lut, shape='square', origin=(0, 0), name='from image'):
2102-
# We can allow for a PIL.Image as unput in the following way, but importing
2100+
# We can allow for a PIL.Image as input in the following way, but importing
21032101
# matplotlib.image.pil_to_array() results in a circular import
21042102
# For now, this function only accepts numpy arrays.
21052103
# i.e.:

lib/matplotlib/colors.pyi

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ class MultivarColormap:
158158
def copy(self) -> MultivarColormap: ...
159159
def __copy__(self) -> MultivarColormap: ...
160160
def __getitem__(self, item: int) -> Colormap: ...
161-
def __iter__(self) -> Colormap: ...
161+
def __iter__(self) -> Iterator[Colormap]: ...
162162
def __len__(self) -> int: ...
163163
def get_bad(self) -> np.ndarray: ...
164164
def resampled(self, lutshape: Sequence[int | None]) -> MultivarColormap: ...
@@ -201,13 +201,13 @@ class BivarColormap:
201201
def origin(self) -> tuple[float, float]: ...
202202
def __copy__(self) -> BivarColormap: ...
203203
def __getitem__(self, item: int) -> Colormap: ...
204-
def __eq__(self, other) -> bool: ...
204+
def __eq__(self, other: Any) -> bool: ...
205205
def get_bad(self) -> np.ndarray: ...
206206
def get_outside(self) -> np.ndarray: ...
207207
def copy(self) -> BivarColormap: ...
208208
def resampled(self, lutshape: Sequence[int | None], transposed: bool = ...) -> BivarColormap: ...
209209
def transposed(self) -> BivarColormap: ...
210-
def reversed(self, axis_0: bool = True, axis_1: bool = True) -> BivarColormap: ...
210+
def reversed(self, axis_0: bool = ..., axis_1: bool = ...) -> BivarColormap: ...
211211
def with_extremes(
212212
self,
213213
*,

lib/matplotlib/tests/test_multivariate_colormaps.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
@image_comparison(["bivariate_cmap_shapes.png"])
1515
def test_bivariate_cmap_shapes():
16-
x_0 = (np.arange(100, dtype='float32').reshape(10, 10) % 10)/9 * 1.2 - 0.1
16+
x_0 = np.repeat(np.linspace(-0.1, 1.1, 10, dtype='float32'), (10, 1))
1717
x_1 = x_0.T
1818

1919
fig, axes = plt.subplots(1, 4, figsize=(10, 2))

0 commit comments

Comments
 (0)
0