Skip to content

Fix matplotlib converter registering warning #26770

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 21, 2019
17 changes: 7 additions & 10 deletions pandas/plotting/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,16 @@
from pandas.core.dtypes.common import is_integer, is_list_like
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries

import pandas
from pandas.core.base import PandasObject
from pandas.core.generic import _shared_doc_kwargs, _shared_docs

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

df_kind = """- 'scatter' : scatter plot
- 'hexbin' : hexbin plot"""
Expand Down
6 changes: 6 additions & 0 deletions pandas/plotting/_matplotlib/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from pandas._config import get_option

from pandas.plotting._matplotlib.boxplot import (
BoxPlot, boxplot, boxplot_frame, boxplot_frame_groupby)
from pandas.plotting._matplotlib.converter import deregister, register
Expand All @@ -11,6 +13,10 @@
from pandas.plotting._matplotlib.timeseries import tsplot
from pandas.plotting._matplotlib.tools import table

if get_option("plotting.matplotlib.register_converters"):
register(explicit=False)


__all__ = ['LinePlot', 'BarPlot', 'BarhPlot', 'HistPlot', 'BoxPlot', 'KdePlot',
'AreaPlot', 'PiePlot', 'ScatterPlot', 'HexBinPlot', 'hist_series',
'hist_frame', 'boxplot', 'boxplot_frame', 'boxplot_frame_groupby',
Expand Down
6 changes: 5 additions & 1 deletion pandas/plotting/_matplotlib/boxplot.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from collections import namedtuple
import warnings

from matplotlib import pyplot as plt
from matplotlib.artist import setp
import numpy as np

Expand All @@ -11,6 +10,7 @@
import pandas as pd

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

import matplotlib.pyplot as plt
# validate return_type:
if return_type not in BoxPlot._valid_return_types:
raise ValueError("return_type must be {'axes', 'dict', 'both'}")
Expand Down Expand Up @@ -296,6 +297,8 @@ def plot_group(keys, values, ax):
def boxplot_frame(self, column=None, by=None, ax=None, fontsize=None, rot=0,
grid=True, figsize=None, layout=None,
return_type=None, **kwds):
import matplotlib.pyplot as plt
converter._WARN = False # no warning for pandas plots
ax = boxplot(self, column=column, by=by, ax=ax, fontsize=fontsize,
grid=grid, rot=rot, figsize=figsize, layout=layout,
return_type=return_type, **kwds)
Expand All @@ -306,6 +309,7 @@ def boxplot_frame(self, column=None, by=None, ax=None, fontsize=None, rot=0,
def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None,
rot=0, grid=True, ax=None, figsize=None,
layout=None, sharex=False, sharey=True, **kwds):
converter._WARN = False # no warning for pandas plots
if subplots is True:
naxes = len(grouped)
fig, axes = _subplots(naxes=naxes, squeeze=False,
Expand Down
7 changes: 5 additions & 2 deletions pandas/plotting/_matplotlib/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from typing import Optional # noqa
import warnings

import matplotlib.pyplot as plt
import numpy as np

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

import matplotlib.pyplot as plt
converter._WARN = False # no warning for pandas plots
self.data = data
self.by = by

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

if grid is None:
grid = False if secondary_y else self.plt.rcParams['axes.grid']
grid = False if secondary_y else plt.rcParams['axes.grid']

self.grid = grid
self.legend = legend
Expand Down Expand Up @@ -618,6 +619,8 @@ def _get_ax(self, i):

@classmethod
def get_default_ax(cls, ax):
import matplotlib.pyplot as plt

if ax is None and len(plt.get_fignums()) > 0:
with plt.rc_context():
ax = plt.gca()
Expand Down
5 changes: 4 additions & 1 deletion pandas/plotting/_matplotlib/hist.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import warnings

import matplotlib.pyplot as plt
import numpy as np

from pandas.core.dtypes.common import is_integer, is_list_like
Expand All @@ -10,6 +9,7 @@
import pandas.core.common as com

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

converter._WARN = False # no warning for pandas plots
xrot = xrot or rot

fig, axes = _grouped_plot(plot_group, data, column=column,
Expand All @@ -220,6 +221,7 @@ def plot_group(group, ax):
def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None,
xrot=None, ylabelsize=None, yrot=None, figsize=None,
bins=10, **kwds):
import matplotlib.pyplot as plt
if by is None:
if kwds.get('layout', None) is not None:
raise ValueError("The 'layout' keyword is not supported when "
Expand Down Expand Up @@ -261,6 +263,7 @@ def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None,
def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None,
xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False,
sharey=False, figsize=None, layout=None, bins=10, **kwds):
converter._WARN = False # no warning for pandas plots
if by is not None:
axes = _grouped_hist(data, column=column, by=by, ax=ax, grid=grid,
figsize=figsize, sharex=sharex, sharey=sharey,
Expand Down
8 changes: 7 additions & 1 deletion pandas/plotting/_matplotlib/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import matplotlib.lines as mlines
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np

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


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

def normalize(series):
a = min(series)
Expand Down Expand Up @@ -169,6 +169,7 @@ def normalize(series):

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

def function(amplitudes):
def f(t):
Expand Down Expand Up @@ -224,6 +225,7 @@ def f(t):

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

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

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

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

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


def autocorrelation_plot(series, ax=None, **kwds):
import matplotlib.pyplot as plt

n = len(series)
data = np.asarray(series)
if ax is None:
Expand Down
2 changes: 1 addition & 1 deletion pandas/plotting/_matplotlib/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

import matplotlib.cm as cm
import matplotlib.colors
import matplotlib.pyplot as plt
import numpy as np

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

def _get_standard_colors(num_colors=None, colormap=None, color_type='default',
color=None):
import matplotlib.pyplot as plt
if color is None and colormap is not None:
if isinstance(colormap, str):
cmap = colormap
Expand Down
4 changes: 2 additions & 2 deletions pandas/plotting/_matplotlib/timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
import functools
import warnings

from matplotlib import pylab
import matplotlib.pyplot as plt
import numpy as np

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

# handle index specific formatting
# Note: DatetimeIndex does not use this
Expand Down
3 changes: 2 additions & 1 deletion pandas/plotting/_matplotlib/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from math import ceil
import warnings

import matplotlib.pyplot as plt
import matplotlib.table
import matplotlib.ticker as ticker
import numpy as np
Expand Down Expand Up @@ -168,6 +167,7 @@ def _subplots(naxes=None, sharex=False, sharey=False, squeeze=True,
# Four polar axes
plt.subplots(2, 2, subplot_kw=dict(polar=True))
"""
import matplotlib.pyplot as plt
if subplot_kw is None:
subplot_kw = {}

Expand Down Expand Up @@ -345,6 +345,7 @@ def _get_xlim(lines):

def _set_ticks_props(axes, xlabelsize=None, xrot=None,
ylabelsize=None, yrot=None):
import matplotlib.pyplot as plt
for ax in _flatten(axes):
if xlabelsize is not None:
plt.setp(ax.get_xticklabels(), fontsize=xlabelsize)
Expand Down
25 changes: 22 additions & 3 deletions pandas/tests/plotting/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,30 @@
from pandas import Index, Period, Series, Timestamp, date_range
import pandas.util.testing as tm

from pandas.plotting import (
deregister_matplotlib_converters, register_matplotlib_converters)
from pandas.tseries.offsets import Day, Micro, Milli, Second

converter = pytest.importorskip('pandas.plotting._converter')
from pandas.plotting import (deregister_matplotlib_converters, # isort:skip
register_matplotlib_converters)
try:
from pandas.plotting._matplotlib import converter
except ImportError:
# try / except, rather than skip, to avoid internal refactoring
# causing an improprer skip
pass

pytest.importorskip('matplotlib.pyplot')


def test_initial_warning():
code = (
"import pandas as pd; import matplotlib.pyplot as plt; "
"s = pd.Series(1, pd.date_range('2000', periods=12)); "
"fig, ax = plt.subplots(); "
"ax.plot(s.index, s.values)"
)
call = [sys.executable, '-c', code]
out = subprocess.check_output(call, stderr=subprocess.STDOUT).decode()
assert 'Using an implicitly' in out


def test_timtetonum_accepts_unicode():
Expand Down
Loading