Skip to content

Commit 5a1e12b

Browse files
phoflmeeseeksmachine
authored andcommitted
Backport PR pandas-dev#48601: CI: Fix matplolib release issues
1 parent aabf659 commit 5a1e12b

File tree

11 files changed

+94
-42
lines changed

11 files changed

+94
-42
lines changed

doc/source/user_guide/visualization.rst

+1
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,7 @@ To plot multiple column groups in a single axes, repeat ``plot`` method specifyi
625625
It is recommended to specify ``color`` and ``label`` keywords to distinguish each groups.
626626

627627
.. ipython:: python
628+
:okwarning:
628629
629630
ax = df.plot.scatter(x="a", y="b", color="DarkBlue", label="Group 1")
630631
@savefig scatter_plot_repeated.png

pandas/plotting/_core.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1016,7 +1016,7 @@ def __call__(self, *args, **kwargs):
10161016
10171017
>>> s = pd.Series([1, 3, 2])
10181018
>>> s.plot.line()
1019-
<AxesSubplot:ylabel='Density'>
1019+
<AxesSubplot: ylabel='Density'>
10201020
10211021
.. plot::
10221022
:context: close-figs

pandas/plotting/_matplotlib/compat.py

+1
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,4 @@ def inner():
1919

2020
mpl_ge_3_4_0 = _mpl_version("3.4.0", operator.ge)
2121
mpl_ge_3_5_0 = _mpl_version("3.5.0", operator.ge)
22+
mpl_ge_3_6_0 = _mpl_version("3.6.0", operator.ge)

pandas/plotting/_matplotlib/core.py

+17-4
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
)
1515
import warnings
1616

17+
import matplotlib as mpl
1718
from matplotlib.artist import Artist
1819
import numpy as np
1920

@@ -54,6 +55,7 @@
5455
from pandas.core.frame import DataFrame
5556

5657
from pandas.io.formats.printing import pprint_thing
58+
from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0
5759
from pandas.plotting._matplotlib.converter import register_pandas_matplotlib_converters
5860
from pandas.plotting._matplotlib.groupby import reconstruct_data_with_by
5961
from pandas.plotting._matplotlib.misc import unpack_single_str_list
@@ -1205,9 +1207,6 @@ def _make_plot(self):
12051207

12061208
color_by_categorical = c_is_column and is_categorical_dtype(self.data[c])
12071209

1208-
# pandas uses colormap, matplotlib uses cmap.
1209-
cmap = self.colormap or "Greys"
1210-
cmap = self.plt.cm.get_cmap(cmap)
12111210
color = self.kwds.pop("color", None)
12121211
if c is not None and color is not None:
12131212
raise TypeError("Specify exactly one of `c` and `color`")
@@ -1222,6 +1221,17 @@ def _make_plot(self):
12221221
else:
12231222
c_values = c
12241223

1224+
# cmap is only used if c_values are integers, otherwise UserWarning
1225+
if is_integer_dtype(c_values):
1226+
# pandas uses colormap, matplotlib uses cmap.
1227+
cmap = self.colormap or "Greys"
1228+
if mpl_ge_3_6_0():
1229+
cmap = mpl.colormaps[cmap]
1230+
else:
1231+
cmap = self.plt.cm.get_cmap(cmap)
1232+
else:
1233+
cmap = None
1234+
12251235
if color_by_categorical:
12261236
from matplotlib import colors
12271237

@@ -1286,7 +1296,10 @@ def _make_plot(self):
12861296
ax = self.axes[0]
12871297
# pandas uses colormap, matplotlib uses cmap.
12881298
cmap = self.colormap or "BuGn"
1289-
cmap = self.plt.cm.get_cmap(cmap)
1299+
if mpl_ge_3_6_0():
1300+
cmap = mpl.colormaps[cmap]
1301+
else:
1302+
cmap = self.plt.cm.get_cmap(cmap)
12901303
cb = self.kwds.pop("colorbar", True)
12911304

12921305
if C is None:

pandas/plotting/_matplotlib/style.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
)
1313
import warnings
1414

15+
import matplotlib as mpl
1516
import matplotlib.cm as cm
1617
import matplotlib.colors
1718
import numpy as np
@@ -22,6 +23,8 @@
2223

2324
import pandas.core.common as com
2425

26+
from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0
27+
2528
if TYPE_CHECKING:
2629
from matplotlib.colors import Colormap
2730

@@ -155,7 +158,10 @@ def _get_cmap_instance(colormap: str | Colormap) -> Colormap:
155158
"""Get instance of matplotlib colormap."""
156159
if isinstance(colormap, str):
157160
cmap = colormap
158-
colormap = cm.get_cmap(colormap)
161+
if mpl_ge_3_6_0():
162+
colormap = mpl.colormaps[colormap]
163+
else:
164+
colormap = cm.get_cmap(colormap)
159165
if colormap is None:
160166
raise ValueError(f"Colormap {cmap} is not recognized")
161167
return colormap

pandas/plotting/_misc.py

+22-22
Original file line numberDiff line numberDiff line change
@@ -139,22 +139,22 @@ def scatter_matrix(
139139
140140
>>> df = pd.DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D'])
141141
>>> pd.plotting.scatter_matrix(df, alpha=0.2)
142-
array([[<AxesSubplot:xlabel='A', ylabel='A'>,
143-
<AxesSubplot:xlabel='B', ylabel='A'>,
144-
<AxesSubplot:xlabel='C', ylabel='A'>,
145-
<AxesSubplot:xlabel='D', ylabel='A'>],
146-
[<AxesSubplot:xlabel='A', ylabel='B'>,
147-
<AxesSubplot:xlabel='B', ylabel='B'>,
148-
<AxesSubplot:xlabel='C', ylabel='B'>,
149-
<AxesSubplot:xlabel='D', ylabel='B'>],
150-
[<AxesSubplot:xlabel='A', ylabel='C'>,
151-
<AxesSubplot:xlabel='B', ylabel='C'>,
152-
<AxesSubplot:xlabel='C', ylabel='C'>,
153-
<AxesSubplot:xlabel='D', ylabel='C'>],
154-
[<AxesSubplot:xlabel='A', ylabel='D'>,
155-
<AxesSubplot:xlabel='B', ylabel='D'>,
156-
<AxesSubplot:xlabel='C', ylabel='D'>,
157-
<AxesSubplot:xlabel='D', ylabel='D'>]], dtype=object)
142+
array([[<AxesSubplot: xlabel='A', ylabel='A'>,
143+
<AxesSubplot: xlabel='B', ylabel='A'>,
144+
<AxesSubplot: xlabel='C', ylabel='A'>,
145+
<AxesSubplot: xlabel='D', ylabel='A'>],
146+
[<AxesSubplot: xlabel='A', ylabel='B'>,
147+
<AxesSubplot: xlabel='B', ylabel='B'>,
148+
<AxesSubplot: xlabel='C', ylabel='B'>,
149+
<AxesSubplot: xlabel='D', ylabel='B'>],
150+
[<AxesSubplot: xlabel='A', ylabel='C'>,
151+
<AxesSubplot: xlabel='B', ylabel='C'>,
152+
<AxesSubplot: xlabel='C', ylabel='C'>,
153+
<AxesSubplot: xlabel='D', ylabel='C'>],
154+
[<AxesSubplot: xlabel='A', ylabel='D'>,
155+
<AxesSubplot: xlabel='B', ylabel='D'>,
156+
<AxesSubplot: xlabel='C', ylabel='D'>,
157+
<AxesSubplot: xlabel='D', ylabel='D'>]], dtype=object)
158158
"""
159159
plot_backend = _get_plot_backend("matplotlib")
160160
return plot_backend.scatter_matrix(
@@ -247,7 +247,7 @@ def radviz(
247247
... }
248248
... )
249249
>>> pd.plotting.radviz(df, 'Category')
250-
<AxesSubplot:xlabel='y(t)', ylabel='y(t + 1)'>
250+
<AxesSubplot: xlabel='y(t)', ylabel='y(t + 1)'>
251251
"""
252252
plot_backend = _get_plot_backend("matplotlib")
253253
return plot_backend.radviz(
@@ -311,7 +311,7 @@ def andrews_curves(
311311
... 'pandas/main/pandas/tests/io/data/csv/iris.csv'
312312
... )
313313
>>> pd.plotting.andrews_curves(df, 'Name')
314-
<AxesSubplot:title={'center':'width'}>
314+
<AxesSubplot: title={'center': 'width'}>
315315
"""
316316
plot_backend = _get_plot_backend("matplotlib")
317317
return plot_backend.andrews_curves(
@@ -445,7 +445,7 @@ def parallel_coordinates(
445445
>>> pd.plotting.parallel_coordinates(
446446
... df, 'Name', color=('#556270', '#4ECDC4', '#C7F464')
447447
... )
448-
<AxesSubplot:xlabel='y(t)', ylabel='y(t + 1)'>
448+
<AxesSubplot: xlabel='y(t)', ylabel='y(t + 1)'>
449449
"""
450450
plot_backend = _get_plot_backend("matplotlib")
451451
return plot_backend.parallel_coordinates(
@@ -494,15 +494,15 @@ def lag_plot(series: Series, lag: int = 1, ax: Axes | None = None, **kwds) -> Ax
494494
>>> x = np.cumsum(np.random.normal(loc=1, scale=5, size=50))
495495
>>> s = pd.Series(x)
496496
>>> s.plot()
497-
<AxesSubplot:xlabel='Midrange'>
497+
<AxesSubplot: xlabel='Midrange'>
498498
499499
A lag plot with ``lag=1`` returns
500500
501501
.. plot::
502502
:context: close-figs
503503
504504
>>> pd.plotting.lag_plot(s, lag=1)
505-
<AxesSubplot:xlabel='y(t)', ylabel='y(t + 1)'>
505+
<AxesSubplot: xlabel='y(t)', ylabel='y(t + 1)'>
506506
"""
507507
plot_backend = _get_plot_backend("matplotlib")
508508
return plot_backend.lag_plot(series=series, lag=lag, ax=ax, **kwds)
@@ -536,7 +536,7 @@ def autocorrelation_plot(series: Series, ax: Axes | None = None, **kwargs) -> Ax
536536
>>> spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000)
537537
>>> s = pd.Series(0.7 * np.random.rand(1000) + 0.3 * np.sin(spacing))
538538
>>> pd.plotting.autocorrelation_plot(s)
539-
<AxesSubplot:title={'center':'width'}, xlabel='Lag', ylabel='Autocorrelation'>
539+
<AxesSubplot: title={'center': 'width'}, xlabel='Lag', ylabel='Autocorrelation'>
540540
"""
541541
plot_backend = _get_plot_backend("matplotlib")
542542
return plot_backend.autocorrelation_plot(series=series, ax=ax, **kwargs)

pandas/tests/plotting/frame/test_frame.py

+18-8
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,15 @@
3232
from pandas.io.formats.printing import pprint_thing
3333
import pandas.plotting as plotting
3434

35+
try:
36+
from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0
37+
except ImportError:
38+
mpl_ge_3_6_0 = lambda: True
39+
3540

3641
@td.skip_if_no_mpl
3742
class TestDataFramePlots(TestPlotBase):
43+
@pytest.mark.xfail(mpl_ge_3_6_0(), reason="Api changed")
3844
@pytest.mark.slow
3945
def test_plot(self):
4046
df = tm.makeTimeDataFrame()
@@ -733,7 +739,7 @@ def test_plot_scatter_with_c(self):
733739
from pandas.plotting._matplotlib.compat import mpl_ge_3_4_0
734740

735741
df = DataFrame(
736-
np.random.randn(6, 4),
742+
np.random.randint(low=0, high=100, size=(6, 4)),
737743
index=list(string.ascii_letters[:6]),
738744
columns=["x", "y", "z", "four"],
739745
)
@@ -1533,17 +1539,17 @@ def test_errorbar_plot_iterator(self):
15331539

15341540
def test_errorbar_with_integer_column_names(self):
15351541
# test with integer column names
1536-
df = DataFrame(np.random.randn(10, 2))
1537-
df_err = DataFrame(np.random.randn(10, 2))
1542+
df = DataFrame(np.abs(np.random.randn(10, 2)))
1543+
df_err = DataFrame(np.abs(np.random.randn(10, 2)))
15381544
ax = _check_plot_works(df.plot, yerr=df_err)
15391545
self._check_has_errorbars(ax, xerr=0, yerr=2)
15401546
ax = _check_plot_works(df.plot, y=0, yerr=1)
15411547
self._check_has_errorbars(ax, xerr=0, yerr=1)
15421548

15431549
@pytest.mark.slow
15441550
def test_errorbar_with_partial_columns(self):
1545-
df = DataFrame(np.random.randn(10, 3))
1546-
df_err = DataFrame(np.random.randn(10, 2), columns=[0, 2])
1551+
df = DataFrame(np.abs(np.random.randn(10, 3)))
1552+
df_err = DataFrame(np.abs(np.random.randn(10, 2)), columns=[0, 2])
15471553
kinds = ["line", "bar"]
15481554
for kind in kinds:
15491555
ax = _check_plot_works(df.plot, yerr=df_err, kind=kind)
@@ -1631,9 +1637,11 @@ def test_table(self):
16311637
assert len(ax.tables) == 1
16321638

16331639
def test_errorbar_scatter(self):
1634-
df = DataFrame(np.random.randn(5, 2), index=range(5), columns=["x", "y"])
1640+
df = DataFrame(
1641+
np.abs(np.random.randn(5, 2)), index=range(5), columns=["x", "y"]
1642+
)
16351643
df_err = DataFrame(
1636-
np.random.randn(5, 2) / 5, index=range(5), columns=["x", "y"]
1644+
np.abs(np.random.randn(5, 2)) / 5, index=range(5), columns=["x", "y"]
16371645
)
16381646

16391647
ax = _check_plot_works(df.plot.scatter, x="x", y="y")
@@ -1660,7 +1668,9 @@ def _check_errorbar_color(containers, expected, has_err="has_xerr"):
16601668
)
16611669

16621670
# GH 8081
1663-
df = DataFrame(np.random.randn(10, 5), columns=["a", "b", "c", "d", "e"])
1671+
df = DataFrame(
1672+
np.abs(np.random.randn(10, 5)), columns=["a", "b", "c", "d", "e"]
1673+
)
16641674
ax = df.plot.scatter(x="a", y="b", xerr="d", yerr="e", c="red")
16651675
self._check_has_errorbars(ax, xerr=1, yerr=1)
16661676
_check_errorbar_color(ax.containers, "red", has_err="has_xerr")

pandas/tests/plotting/frame/test_frame_color.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -655,6 +655,6 @@ def test_colors_of_columns_with_same_name(self):
655655

656656
def test_invalid_colormap(self):
657657
df = DataFrame(np.random.randn(3, 2), columns=["A", "B"])
658-
msg = "'invalid_colormap' is not a valid value for name; supported values are "
659-
with pytest.raises(ValueError, match=msg):
658+
msg = "(is not a valid value)|(is not a known colormap)"
659+
with pytest.raises((ValueError, KeyError), match=msg):
660660
df.plot(colormap="invalid_colormap")

pandas/tests/plotting/test_datetimelike.py

+7
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,11 @@
3939
from pandas.core.indexes.timedeltas import timedelta_range
4040
from pandas.tests.plotting.common import TestPlotBase
4141

42+
try:
43+
from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0
44+
except ImportError:
45+
mpl_ge_3_6_0 = lambda: True
46+
4247
from pandas.tseries.offsets import WeekOfMonth
4348

4449

@@ -260,6 +265,7 @@ def test_plot_multiple_inferred_freq(self):
260265
ser = Series(np.random.randn(len(dr)), index=dr)
261266
_check_plot_works(ser.plot)
262267

268+
@pytest.mark.xfail(mpl_ge_3_6_0(), reason="Api changed")
263269
def test_uhf(self):
264270
import pandas.plotting._matplotlib.converter as conv
265271

@@ -1209,6 +1215,7 @@ def test_secondary_legend(self):
12091215
# TODO: color cycle problems
12101216
assert len(colors) == 4
12111217

1218+
@pytest.mark.xfail(mpl_ge_3_6_0(), reason="Api changed")
12121219
def test_format_date_axis(self):
12131220
rng = date_range("1/1/2012", periods=12, freq="M")
12141221
df = DataFrame(np.random.randn(len(rng), 3), rng)

pandas/tests/plotting/test_hist_method.py

+6
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@
1818
_check_plot_works,
1919
)
2020

21+
try:
22+
from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0
23+
except ImportError:
24+
mpl_ge_3_6_0 = lambda: True
25+
2126

2227
@pytest.fixture
2328
def ts():
@@ -191,6 +196,7 @@ def test_hist_kwargs(self, ts):
191196
ax = ts.plot.hist(align="left", stacked=True, ax=ax)
192197
tm.close()
193198

199+
@pytest.mark.xfail(mpl_ge_3_6_0(), reason="Api changed")
194200
@td.skip_if_no_scipy
195201
def test_hist_kde(self, ts):
196202

pandas/tests/plotting/test_series.py

+12-4
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@
2121

2222
import pandas.plotting as plotting
2323

24+
try:
25+
from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0
26+
except ImportError:
27+
mpl_ge_3_6_0 = lambda: True
28+
2429

2530
@pytest.fixture
2631
def ts():
@@ -493,6 +498,7 @@ def test_kde_missing_vals(self):
493498
# gh-14821: check if the values have any missing values
494499
assert any(~np.isnan(axes.lines[0].get_xdata()))
495500

501+
@pytest.mark.xfail(mpl_ge_3_6_0(), reason="Api changed")
496502
def test_boxplot_series(self, ts):
497503
_, ax = self.plt.subplots()
498504
ax = ts.plot.box(logy=True, ax=ax)
@@ -575,8 +581,10 @@ def test_errorbar_asymmetrical(self):
575581
def test_errorbar_plot(self):
576582

577583
s = Series(np.arange(10), name="x")
578-
s_err = np.random.randn(10)
579-
d_err = DataFrame(np.random.randn(10, 2), index=s.index, columns=["x", "y"])
584+
s_err = np.abs(np.random.randn(10))
585+
d_err = DataFrame(
586+
np.abs(np.random.randn(10, 2)), index=s.index, columns=["x", "y"]
587+
)
580588
# test line and bar plots
581589
kinds = ["line", "bar"]
582590
for kind in kinds:
@@ -597,8 +605,8 @@ def test_errorbar_plot(self):
597605
# test time series plotting
598606
ix = date_range("1/1/2000", "1/1/2001", freq="M")
599607
ts = Series(np.arange(12), index=ix, name="x")
600-
ts_err = Series(np.random.randn(12), index=ix)
601-
td_err = DataFrame(np.random.randn(12, 2), index=ix, columns=["x", "y"])
608+
ts_err = Series(np.abs(np.random.randn(12)), index=ix)
609+
td_err = DataFrame(np.abs(np.random.randn(12, 2)), index=ix, columns=["x", "y"])
602610

603611
ax = _check_plot_works(ts.plot, yerr=ts_err)
604612
self._check_has_errorbars(ax, xerr=0, yerr=1)

0 commit comments

Comments
 (0)