Skip to content

BUG: suppress error raise by nonnumeric columns when plotting DataFrame ... #3287

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 2 commits into from
Apr 12, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions pandas/tests/test_graphics.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,17 @@ def test_plot(self):
index=index)
_check_plot_works(df.plot, title=u'\u03A3')

@slow
def test_nonnumeric_exclude(self):
import matplotlib.pyplot as plt
plt.close('all')

df = DataFrame({'A': ["x", "y", "z"], 'B': [1,2,3]})
ax = df.plot(raise_on_error=False) # it works
self.assert_(len(ax.get_lines()) == 1) #B was plotted

self.assertRaises(Exception, df.plot)

@slow
def test_label(self):
import matplotlib.pyplot as plt
Expand Down
71 changes: 45 additions & 26 deletions pandas/tools/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -691,8 +691,10 @@ class MPLPlot(object):
"""
_default_rot = 0

_pop_attributes = ['label', 'style', 'logy', 'logx', 'loglog']
_attr_defaults = {'logy': False, 'logx': False, 'loglog': False}
_pop_attributes = ['label', 'style', 'logy', 'logx', 'loglog',
'raise_on_error']
_attr_defaults = {'logy': False, 'logx': False, 'loglog': False,
'raise_on_error': True}

def __init__(self, data, kind=None, by=None, subplots=False, sharex=True,
sharey=False, use_index=True,
Expand Down Expand Up @@ -1170,17 +1172,27 @@ def _make_plot(self):
else:
args = (ax, x, y, style)

newline = plotf(*args, **kwds)[0]
lines.append(newline)
leg_label = label
if self.mark_right and self.on_right(i):
leg_label += ' (right)'
labels.append(leg_label)
ax.grid(self.grid)

if self._is_datetype():
left, right = _get_xlim(lines)
ax.set_xlim(left, right)
try:
newline = plotf(*args, **kwds)[0]
lines.append(newline)
leg_label = label
if self.mark_right and self.on_right(i):
leg_label += ' (right)'
labels.append(leg_label)
ax.grid(self.grid)

if self._is_datetype():
left, right = _get_xlim(lines)
ax.set_xlim(left, right)
except AttributeError as inst: # non-numeric
msg = ('Unable to plot data %s vs index %s,\n'
'error was: %s' % (str(y), str(x), str(inst)))
if not self.raise_on_error:
print msg
else:
msg = msg + ('\nConsider setting raise_on_error=False'
'to suppress')
raise Exception(msg)

self._make_legend(lines, labels)

Expand All @@ -1198,19 +1210,32 @@ def to_leg_label(label, i):
return label + ' (right)'
return label

def _plot(data, col_num, ax, label, style, **kwds):
try:
newlines = tsplot(data, plotf, ax=ax, label=label,
style=style, **kwds)
ax.grid(self.grid)
lines.append(newlines[0])
leg_label = to_leg_label(label, col_num)
labels.append(leg_label)
except AttributeError as inst: #non-numeric
msg = ('Unable to plot %s,\n'
'error was: %s' % (str(data), str(inst)))
if not self.raise_on_error:
print msg
else:
msg = msg + ('\nConsider setting raise_on_error=False'
'to suppress')
raise Exception(msg)

if isinstance(data, Series):
ax = self._get_ax(0) # self.axes[0]
style = self.style or ''
label = com.pprint_thing(self.label)
kwds = kwargs.copy()
self._maybe_add_color(colors, kwds, style, 0)

newlines = tsplot(data, plotf, ax=ax, label=label,
style=self.style, **kwds)
ax.grid(self.grid)
lines.append(newlines[0])
leg_label = to_leg_label(label, 0)
labels.append(leg_label)
_plot(data, 0, ax, label, self.style, **kwds)
else:
for i, col in enumerate(data.columns):
label = com.pprint_thing(col)
Expand All @@ -1220,13 +1245,7 @@ def to_leg_label(label, i):

self._maybe_add_color(colors, kwds, style, i)

newlines = tsplot(data[col], plotf, ax=ax, label=label,
style=style, **kwds)

lines.append(newlines[0])
leg_label = to_leg_label(label, i)
labels.append(leg_label)
ax.grid(self.grid)
_plot(data[col], i, ax, label, style, **kwds)

self._make_legend(lines, labels)

Expand Down
20 changes: 20 additions & 0 deletions pandas/tseries/tests/test_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,26 @@ def test_frame_inferred(self):
df = DataFrame(np.random.randn(len(idx), 3), index=idx)
df.plot()

@slow
def test_nonnumeric_exclude(self):
import matplotlib.pyplot as plt
plt.close('all')

idx = date_range('1/1/1987', freq='A', periods=3)
df = DataFrame({'A': ["x", "y", "z"], 'B': [1,2,3]}, idx)
self.assertRaises(Exception, df.plot)

plt.close('all')
ax = df.plot(raise_on_error=False) # it works
self.assert_(len(ax.get_lines()) == 1) #B was plotted

plt.close('all')
self.assertRaises(Exception, df.A.plot)

plt.close('all')
ax = df['A'].plot(raise_on_error=False) # it works
self.assert_(len(ax.get_lines()) == 0)

@slow
def test_tsplot(self):
from pandas.tseries.plotting import tsplot
Expand Down