Skip to content

Commit 4850b28

Browse files
TomAugspurgerjreback
authored andcommitted
Fix matplotlib converter registering warning (#26770)
1 parent 984514e commit 4850b28

File tree

12 files changed

+69
-56
lines changed

12 files changed

+69
-56
lines changed

pandas/plotting/_core.py

+7-10
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,16 @@
55
from pandas.core.dtypes.common import is_integer, is_list_like
66
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
77

8-
import pandas
98
from pandas.core.base import PandasObject
109
from pandas.core.generic import _shared_doc_kwargs, _shared_docs
1110

12-
# Automatically registering converters was deprecated in 0.21, but
13-
# the deprecation warning wasn't showing until 0.24
14-
# This block will be eventually removed, but it's not clear when
15-
if pandas.get_option('plotting.matplotlib.register_converters'):
16-
try:
17-
from .misc import register
18-
register(explicit=False)
19-
except ImportError:
20-
pass
11+
# Trigger matplotlib import, which implicitly registers our
12+
# converts. Implicit registration is deprecated, and when enforced
13+
# we can lazily import matplotlib.
14+
try:
15+
import pandas.plotting._matplotlib # noqa
16+
except ImportError:
17+
pass
2118

2219
df_kind = """- 'scatter' : scatter plot
2320
- 'hexbin' : hexbin plot"""

pandas/plotting/_matplotlib/__init__.py

+6
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from pandas._config import get_option
2+
13
from pandas.plotting._matplotlib.boxplot import (
24
BoxPlot, boxplot, boxplot_frame, boxplot_frame_groupby)
35
from pandas.plotting._matplotlib.converter import deregister, register
@@ -11,6 +13,10 @@
1113
from pandas.plotting._matplotlib.timeseries import tsplot
1214
from pandas.plotting._matplotlib.tools import table
1315

16+
if get_option("plotting.matplotlib.register_converters"):
17+
register(explicit=False)
18+
19+
1420
__all__ = ['LinePlot', 'BarPlot', 'BarhPlot', 'HistPlot', 'BoxPlot', 'KdePlot',
1521
'AreaPlot', 'PiePlot', 'ScatterPlot', 'HexBinPlot', 'hist_series',
1622
'hist_frame', 'boxplot', 'boxplot_frame', 'boxplot_frame_groupby',

pandas/plotting/_matplotlib/boxplot.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from collections import namedtuple
22
import warnings
33

4-
from matplotlib import pyplot as plt
54
from matplotlib.artist import setp
65
import numpy as np
76

@@ -11,6 +10,7 @@
1110
import pandas as pd
1211

1312
from pandas.io.formats.printing import pprint_thing
13+
from pandas.plotting._matplotlib import converter
1414
from pandas.plotting._matplotlib.core import LinePlot, MPLPlot
1515
from pandas.plotting._matplotlib.style import _get_standard_colors
1616
from pandas.plotting._matplotlib.tools import _flatten, _subplots
@@ -215,6 +215,7 @@ def boxplot(data, column=None, by=None, ax=None, fontsize=None,
215215
rot=0, grid=True, figsize=None, layout=None, return_type=None,
216216
**kwds):
217217

218+
import matplotlib.pyplot as plt
218219
# validate return_type:
219220
if return_type not in BoxPlot._valid_return_types:
220221
raise ValueError("return_type must be {'axes', 'dict', 'both'}")
@@ -296,6 +297,8 @@ def plot_group(keys, values, ax):
296297
def boxplot_frame(self, column=None, by=None, ax=None, fontsize=None, rot=0,
297298
grid=True, figsize=None, layout=None,
298299
return_type=None, **kwds):
300+
import matplotlib.pyplot as plt
301+
converter._WARN = False # no warning for pandas plots
299302
ax = boxplot(self, column=column, by=by, ax=ax, fontsize=fontsize,
300303
grid=grid, rot=rot, figsize=figsize, layout=layout,
301304
return_type=return_type, **kwds)
@@ -306,6 +309,7 @@ def boxplot_frame(self, column=None, by=None, ax=None, fontsize=None, rot=0,
306309
def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None,
307310
rot=0, grid=True, ax=None, figsize=None,
308311
layout=None, sharex=False, sharey=True, **kwds):
312+
converter._WARN = False # no warning for pandas plots
309313
if subplots is True:
310314
naxes = len(grouped)
311315
fig, axes = _subplots(naxes=naxes, squeeze=False,

pandas/plotting/_matplotlib/core.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
from typing import Optional # noqa
33
import warnings
44

5-
import matplotlib.pyplot as plt
65
import numpy as np
76

87
from pandas._config import get_option
@@ -61,6 +60,8 @@ def __init__(self, data, kind=None, by=None, subplots=False, sharex=None,
6160
secondary_y=False, colormap=None,
6261
table=False, layout=None, **kwds):
6362

63+
import matplotlib.pyplot as plt
64+
converter._WARN = False # no warning for pandas plots
6465
self.data = data
6566
self.by = by
6667

@@ -103,7 +104,7 @@ def __init__(self, data, kind=None, by=None, subplots=False, sharex=None,
103104
self.rot = self._default_rot
104105

105106
if grid is None:
106-
grid = False if secondary_y else self.plt.rcParams['axes.grid']
107+
grid = False if secondary_y else plt.rcParams['axes.grid']
107108

108109
self.grid = grid
109110
self.legend = legend
@@ -618,6 +619,8 @@ def _get_ax(self, i):
618619

619620
@classmethod
620621
def get_default_ax(cls, ax):
622+
import matplotlib.pyplot as plt
623+
621624
if ax is None and len(plt.get_fignums()) > 0:
622625
with plt.rc_context():
623626
ax = plt.gca()

pandas/plotting/_matplotlib/hist.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import warnings
22

3-
import matplotlib.pyplot as plt
43
import numpy as np
54

65
from pandas.core.dtypes.common import is_integer, is_list_like
@@ -10,6 +9,7 @@
109
import pandas.core.common as com
1110

1211
from pandas.io.formats.printing import pprint_thing
12+
from pandas.plotting._matplotlib import converter
1313
from pandas.plotting._matplotlib.core import LinePlot, MPLPlot
1414
from pandas.plotting._matplotlib.tools import (
1515
_flatten, _set_ticks_props, _subplots)
@@ -203,6 +203,7 @@ def _grouped_hist(data, column=None, by=None, ax=None, bins=50, figsize=None,
203203
def plot_group(group, ax):
204204
ax.hist(group.dropna().values, bins=bins, **kwargs)
205205

206+
converter._WARN = False # no warning for pandas plots
206207
xrot = xrot or rot
207208

208209
fig, axes = _grouped_plot(plot_group, data, column=column,
@@ -220,6 +221,7 @@ def plot_group(group, ax):
220221
def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None,
221222
xrot=None, ylabelsize=None, yrot=None, figsize=None,
222223
bins=10, **kwds):
224+
import matplotlib.pyplot as plt
223225
if by is None:
224226
if kwds.get('layout', None) is not None:
225227
raise ValueError("The 'layout' keyword is not supported when "
@@ -261,6 +263,7 @@ def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None,
261263
def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None,
262264
xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False,
263265
sharey=False, figsize=None, layout=None, bins=10, **kwds):
266+
converter._WARN = False # no warning for pandas plots
264267
if by is not None:
265268
axes = _grouped_hist(data, column=column, by=by, ax=ax, grid=grid,
266269
figsize=figsize, sharex=sharex, sharey=sharey,

pandas/plotting/_matplotlib/misc.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import matplotlib.lines as mlines
44
import matplotlib.patches as patches
5-
import matplotlib.pyplot as plt
65
import numpy as np
76

87
from pandas.core.dtypes.missing import notna
@@ -105,6 +104,7 @@ def _get_marker_compat(marker):
105104

106105

107106
def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds):
107+
import matplotlib.pyplot as plt
108108

109109
def normalize(series):
110110
a = min(series)
@@ -169,6 +169,7 @@ def normalize(series):
169169

170170
def andrews_curves(frame, class_column, ax=None, samples=200, color=None,
171171
colormap=None, **kwds):
172+
import matplotlib.pyplot as plt
172173

173174
def function(amplitudes):
174175
def f(t):
@@ -224,6 +225,7 @@ def f(t):
224225

225226
def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds):
226227

228+
import matplotlib.pyplot as plt
227229
# random.sample(ndarray, int) fails on python 3.3, sigh
228230
data = list(series.values)
229231
samplings = [random.sample(data, size) for _ in range(samples)]
@@ -270,6 +272,7 @@ def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None,
270272
use_columns=False, xticks=None, colormap=None,
271273
axvlines=True, axvlines_kwds=None, sort_labels=False,
272274
**kwds):
275+
import matplotlib.pyplot as plt
273276
if axvlines_kwds is None:
274277
axvlines_kwds = {'linewidth': 1, 'color': 'black'}
275278

@@ -336,6 +339,7 @@ def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None,
336339

337340
def lag_plot(series, lag=1, ax=None, **kwds):
338341
# workaround because `c='b'` is hardcoded in matplotlibs scatter method
342+
import matplotlib.pyplot as plt
339343
kwds.setdefault('c', plt.rcParams['patch.facecolor'])
340344

341345
data = series.values
@@ -350,6 +354,8 @@ def lag_plot(series, lag=1, ax=None, **kwds):
350354

351355

352356
def autocorrelation_plot(series, ax=None, **kwds):
357+
import matplotlib.pyplot as plt
358+
353359
n = len(series)
354360
data = np.asarray(series)
355361
if ax is None:

pandas/plotting/_matplotlib/style.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
import matplotlib.cm as cm
55
import matplotlib.colors
6-
import matplotlib.pyplot as plt
76
import numpy as np
87

98
from pandas.core.dtypes.common import is_list_like
@@ -13,6 +12,7 @@
1312

1413
def _get_standard_colors(num_colors=None, colormap=None, color_type='default',
1514
color=None):
15+
import matplotlib.pyplot as plt
1616
if color is None and colormap is not None:
1717
if isinstance(colormap, str):
1818
cmap = colormap

pandas/plotting/_matplotlib/timeseries.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
import functools
44
import warnings
55

6-
from matplotlib import pylab
7-
import matplotlib.pyplot as plt
86
import numpy as np
97

108
from pandas._libs.tslibs.frequencies import (
@@ -42,6 +40,7 @@ def tsplot(series, plotf, ax=None, **kwargs):
4240
.. deprecated:: 0.23.0
4341
Use Series.plot() instead
4442
"""
43+
import matplotlib.pyplot as plt
4544
warnings.warn("'tsplot' is deprecated and will be removed in a "
4645
"future version. Please use Series.plot() instead.",
4746
FutureWarning, stacklevel=2)
@@ -323,6 +322,7 @@ def format_dateaxis(subplot, freq, index):
323322
default, changing the limits of the x axis will intelligently change
324323
the positions of the ticks.
325324
"""
325+
from matplotlib import pylab
326326

327327
# handle index specific formatting
328328
# Note: DatetimeIndex does not use this

pandas/plotting/_matplotlib/tools.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
from math import ceil
33
import warnings
44

5-
import matplotlib.pyplot as plt
65
import matplotlib.table
76
import matplotlib.ticker as ticker
87
import numpy as np
@@ -168,6 +167,7 @@ def _subplots(naxes=None, sharex=False, sharey=False, squeeze=True,
168167
# Four polar axes
169168
plt.subplots(2, 2, subplot_kw=dict(polar=True))
170169
"""
170+
import matplotlib.pyplot as plt
171171
if subplot_kw is None:
172172
subplot_kw = {}
173173

@@ -345,6 +345,7 @@ def _get_xlim(lines):
345345

346346
def _set_ticks_props(axes, xlabelsize=None, xrot=None,
347347
ylabelsize=None, yrot=None):
348+
import matplotlib.pyplot as plt
348349
for ax in _flatten(axes):
349350
if xlabelsize is not None:
350351
plt.setp(ax.get_xticklabels(), fontsize=xlabelsize)

pandas/tests/plotting/test_converter.py

+22-3
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,30 @@
1212
from pandas import Index, Period, Series, Timestamp, date_range
1313
import pandas.util.testing as tm
1414

15+
from pandas.plotting import (
16+
deregister_matplotlib_converters, register_matplotlib_converters)
1517
from pandas.tseries.offsets import Day, Micro, Milli, Second
1618

17-
converter = pytest.importorskip('pandas.plotting._converter')
18-
from pandas.plotting import (deregister_matplotlib_converters, # isort:skip
19-
register_matplotlib_converters)
19+
try:
20+
from pandas.plotting._matplotlib import converter
21+
except ImportError:
22+
# try / except, rather than skip, to avoid internal refactoring
23+
# causing an improprer skip
24+
pass
25+
26+
pytest.importorskip('matplotlib.pyplot')
27+
28+
29+
def test_initial_warning():
30+
code = (
31+
"import pandas as pd; import matplotlib.pyplot as plt; "
32+
"s = pd.Series(1, pd.date_range('2000', periods=12)); "
33+
"fig, ax = plt.subplots(); "
34+
"ax.plot(s.index, s.values)"
35+
)
36+
call = [sys.executable, '-c', code]
37+
out = subprocess.check_output(call, stderr=subprocess.STDOUT).decode()
38+
assert 'Using an implicitly' in out
2039

2140

2241
def test_timtetonum_accepts_unicode():

0 commit comments

Comments
 (0)