Skip to content

Commit d8070fa

Browse files
committed
Merge pull request #3287 from changhiskhan/nonnumeric-plot
BUG: suppress error raise by nonnumeric columns when plotting DataFrame ...
2 parents 1c081e3 + b00df5e commit d8070fa

File tree

3 files changed

+76
-26
lines changed

3 files changed

+76
-26
lines changed

pandas/tests/test_graphics.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,17 @@ def test_plot(self):
243243
index=index)
244244
_check_plot_works(df.plot, title=u'\u03A3')
245245

246+
@slow
247+
def test_nonnumeric_exclude(self):
248+
import matplotlib.pyplot as plt
249+
plt.close('all')
250+
251+
df = DataFrame({'A': ["x", "y", "z"], 'B': [1,2,3]})
252+
ax = df.plot(raise_on_error=False) # it works
253+
self.assert_(len(ax.get_lines()) == 1) #B was plotted
254+
255+
self.assertRaises(Exception, df.plot)
256+
246257
@slow
247258
def test_label(self):
248259
import matplotlib.pyplot as plt

pandas/tools/plotting.py

Lines changed: 45 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -692,8 +692,10 @@ class MPLPlot(object):
692692
"""
693693
_default_rot = 0
694694

695-
_pop_attributes = ['label', 'style', 'logy', 'logx', 'loglog']
696-
_attr_defaults = {'logy': False, 'logx': False, 'loglog': False}
695+
_pop_attributes = ['label', 'style', 'logy', 'logx', 'loglog',
696+
'raise_on_error']
697+
_attr_defaults = {'logy': False, 'logx': False, 'loglog': False,
698+
'raise_on_error': True}
697699

698700
def __init__(self, data, kind=None, by=None, subplots=False, sharex=True,
699701
sharey=False, use_index=True,
@@ -1172,17 +1174,27 @@ def _make_plot(self):
11721174
else:
11731175
args = (ax, x, y, style)
11741176

1175-
newline = plotf(*args, **kwds)[0]
1176-
lines.append(newline)
1177-
leg_label = label
1178-
if self.mark_right and self.on_right(i):
1179-
leg_label += ' (right)'
1180-
labels.append(leg_label)
1181-
ax.grid(self.grid)
1182-
1183-
if self._is_datetype():
1184-
left, right = _get_xlim(lines)
1185-
ax.set_xlim(left, right)
1177+
try:
1178+
newline = plotf(*args, **kwds)[0]
1179+
lines.append(newline)
1180+
leg_label = label
1181+
if self.mark_right and self.on_right(i):
1182+
leg_label += ' (right)'
1183+
labels.append(leg_label)
1184+
ax.grid(self.grid)
1185+
1186+
if self._is_datetype():
1187+
left, right = _get_xlim(lines)
1188+
ax.set_xlim(left, right)
1189+
except AttributeError as inst: # non-numeric
1190+
msg = ('Unable to plot data %s vs index %s,\n'
1191+
'error was: %s' % (str(y), str(x), str(inst)))
1192+
if not self.raise_on_error:
1193+
print msg
1194+
else:
1195+
msg = msg + ('\nConsider setting raise_on_error=False'
1196+
'to suppress')
1197+
raise Exception(msg)
11861198

11871199
self._make_legend(lines, labels)
11881200

@@ -1200,19 +1212,32 @@ def to_leg_label(label, i):
12001212
return label + ' (right)'
12011213
return label
12021214

1215+
def _plot(data, col_num, ax, label, style, **kwds):
1216+
try:
1217+
newlines = tsplot(data, plotf, ax=ax, label=label,
1218+
style=style, **kwds)
1219+
ax.grid(self.grid)
1220+
lines.append(newlines[0])
1221+
leg_label = to_leg_label(label, col_num)
1222+
labels.append(leg_label)
1223+
except AttributeError as inst: #non-numeric
1224+
msg = ('Unable to plot %s,\n'
1225+
'error was: %s' % (str(data), str(inst)))
1226+
if not self.raise_on_error:
1227+
print msg
1228+
else:
1229+
msg = msg + ('\nConsider setting raise_on_error=False'
1230+
'to suppress')
1231+
raise Exception(msg)
1232+
12031233
if isinstance(data, Series):
12041234
ax = self._get_ax(0) # self.axes[0]
12051235
style = self.style or ''
12061236
label = com.pprint_thing(self.label)
12071237
kwds = kwargs.copy()
12081238
self._maybe_add_color(colors, kwds, style, 0)
12091239

1210-
newlines = tsplot(data, plotf, ax=ax, label=label,
1211-
style=self.style, **kwds)
1212-
ax.grid(self.grid)
1213-
lines.append(newlines[0])
1214-
leg_label = to_leg_label(label, 0)
1215-
labels.append(leg_label)
1240+
_plot(data, 0, ax, label, self.style, **kwds)
12161241
else:
12171242
for i, col in enumerate(data.columns):
12181243
label = com.pprint_thing(col)
@@ -1222,13 +1247,7 @@ def to_leg_label(label, i):
12221247

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

1225-
newlines = tsplot(data[col], plotf, ax=ax, label=label,
1226-
style=style, **kwds)
1227-
1228-
lines.append(newlines[0])
1229-
leg_label = to_leg_label(label, i)
1230-
labels.append(leg_label)
1231-
ax.grid(self.grid)
1250+
_plot(data[col], i, ax, label, style, **kwds)
12321251

12331252
self._make_legend(lines, labels)
12341253

pandas/tseries/tests/test_plotting.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,26 @@ def test_frame_inferred(self):
8080
df = DataFrame(np.random.randn(len(idx), 3), index=idx)
8181
df.plot()
8282

83+
@slow
84+
def test_nonnumeric_exclude(self):
85+
import matplotlib.pyplot as plt
86+
plt.close('all')
87+
88+
idx = date_range('1/1/1987', freq='A', periods=3)
89+
df = DataFrame({'A': ["x", "y", "z"], 'B': [1,2,3]}, idx)
90+
self.assertRaises(Exception, df.plot)
91+
92+
plt.close('all')
93+
ax = df.plot(raise_on_error=False) # it works
94+
self.assert_(len(ax.get_lines()) == 1) #B was plotted
95+
96+
plt.close('all')
97+
self.assertRaises(Exception, df.A.plot)
98+
99+
plt.close('all')
100+
ax = df['A'].plot(raise_on_error=False) # it works
101+
self.assert_(len(ax.get_lines()) == 0)
102+
83103
@slow
84104
def test_tsplot(self):
85105
from pandas.tseries.plotting import tsplot

0 commit comments

Comments
 (0)