PageRenderTime 37ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/pandas/tests/test_graphics.py

https://github.com/thouis/pandas
Python | 688 lines | 530 code | 131 blank | 27 comment | 40 complexity | 21d22865c8e31cae39f5655883d00da4 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. import nose
  2. import os
  3. import string
  4. import unittest
  5. from datetime import datetime
  6. from pandas import Series, DataFrame, MultiIndex, PeriodIndex, date_range
  7. import pandas.util.testing as tm
  8. import numpy as np
  9. from numpy.testing import assert_array_equal
  10. from numpy.testing.decorators import slow
  11. import pandas.tools.plotting as plotting
  12. def _skip_if_no_scipy():
  13. try:
  14. import scipy
  15. except ImportError:
  16. raise nose.SkipTest
  17. class TestSeriesPlots(unittest.TestCase):
  18. @classmethod
  19. def setUpClass(cls):
  20. import sys
  21. # if 'IPython' in sys.modules:
  22. # raise nose.SkipTest
  23. try:
  24. import matplotlib as mpl
  25. mpl.use('Agg', warn=False)
  26. except ImportError:
  27. raise nose.SkipTest
  28. def setUp(self):
  29. self.ts = tm.makeTimeSeries()
  30. self.ts.name = 'ts'
  31. self.series = tm.makeStringSeries()
  32. self.series.name = 'series'
  33. self.iseries = tm.makePeriodSeries()
  34. self.iseries.name = 'iseries'
  35. @slow
  36. def test_plot(self):
  37. _check_plot_works(self.ts.plot, label='foo')
  38. _check_plot_works(self.ts.plot, use_index=False)
  39. _check_plot_works(self.ts.plot, rot=0)
  40. _check_plot_works(self.ts.plot, style='.', logy=True)
  41. _check_plot_works(self.ts.plot, style='.', logx=True)
  42. _check_plot_works(self.ts.plot, style='.', loglog=True)
  43. _check_plot_works(self.ts[:10].plot, kind='bar')
  44. _check_plot_works(self.series[:5].plot, kind='bar')
  45. _check_plot_works(self.series[:5].plot, kind='line')
  46. _check_plot_works(self.series[:5].plot, kind='barh')
  47. _check_plot_works(self.series[:10].plot, kind='barh')
  48. Series(np.random.randn(10)).plot(kind='bar',color='black')
  49. @slow
  50. def test_bar_colors(self):
  51. import matplotlib.pyplot as plt
  52. import matplotlib.colors as colors
  53. default_colors = 'brgyk'
  54. custom_colors = 'rgcby'
  55. plt.close('all')
  56. df = DataFrame(np.random.randn(5, 5))
  57. ax = df.plot(kind='bar')
  58. rects = ax.patches
  59. conv = colors.colorConverter
  60. for i, rect in enumerate(rects[::5]):
  61. xp = conv.to_rgba(default_colors[i])
  62. rs = rect.get_facecolor()
  63. self.assert_(xp == rs)
  64. plt.close('all')
  65. ax = df.plot(kind='bar', color=custom_colors)
  66. rects = ax.patches
  67. conv = colors.colorConverter
  68. for i, rect in enumerate(rects[::5]):
  69. xp = conv.to_rgba(custom_colors[i])
  70. rs = rect.get_facecolor()
  71. self.assert_(xp == rs)
  72. plt.close('all')
  73. df.ix[:, [0]].plot(kind='bar', color='DodgerBlue')
  74. @slow
  75. def test_bar_linewidth(self):
  76. df = DataFrame(np.random.randn(5, 5))
  77. # regular
  78. ax = df.plot(kind='bar', linewidth=2)
  79. for r in ax.patches:
  80. self.assert_(r.get_linewidth() == 2)
  81. # stacked
  82. ax = df.plot(kind='bar', stacked=True, linewidth=2)
  83. for r in ax.patches:
  84. self.assert_(r.get_linewidth() == 2)
  85. # subplots
  86. axes = df.plot(kind='bar', linewidth=2, subplots=True)
  87. for ax in axes:
  88. for r in ax.patches:
  89. self.assert_(r.get_linewidth() == 2)
  90. @slow
  91. def test_rotation(self):
  92. df = DataFrame(np.random.randn(5, 5))
  93. ax = df.plot(rot=30)
  94. for l in ax.get_xticklabels():
  95. self.assert_(l.get_rotation() == 30)
  96. @slow
  97. def test_irregular_datetime(self):
  98. rng = date_range('1/1/2000', '3/1/2000')
  99. rng = rng[[0,1,2,3,5,9,10,11,12]]
  100. ser = Series(np.random.randn(len(rng)), rng)
  101. ax = ser.plot()
  102. xp = datetime(1999, 1, 1).toordinal()
  103. ax.set_xlim('1/1/1999', '1/1/2001')
  104. self.assert_(xp == ax.get_xlim()[0])
  105. @slow
  106. def test_hist(self):
  107. _check_plot_works(self.ts.hist)
  108. _check_plot_works(self.ts.hist, grid=False)
  109. _check_plot_works(self.ts.hist, by=self.ts.index.month)
  110. @slow
  111. def test_kde(self):
  112. _skip_if_no_scipy()
  113. _check_plot_works(self.ts.plot, kind='kde')
  114. _check_plot_works(self.ts.plot, kind='density')
  115. ax = self.ts.plot(kind='kde', logy=True)
  116. self.assert_(ax.get_yscale() == 'log')
  117. @slow
  118. def test_autocorrelation_plot(self):
  119. from pandas.tools.plotting import autocorrelation_plot
  120. _check_plot_works(autocorrelation_plot, self.ts)
  121. _check_plot_works(autocorrelation_plot, self.ts.values)
  122. @slow
  123. def test_lag_plot(self):
  124. from pandas.tools.plotting import lag_plot
  125. _check_plot_works(lag_plot, self.ts)
  126. @slow
  127. def test_bootstrap_plot(self):
  128. from pandas.tools.plotting import bootstrap_plot
  129. _check_plot_works(bootstrap_plot, self.ts, size=10)
  130. class TestDataFramePlots(unittest.TestCase):
  131. @classmethod
  132. def setUpClass(cls):
  133. #import sys
  134. #if 'IPython' in sys.modules:
  135. # raise nose.SkipTest
  136. try:
  137. import matplotlib as mpl
  138. mpl.use('Agg', warn=False)
  139. except ImportError:
  140. raise nose.SkipTest
  141. @slow
  142. def test_plot(self):
  143. df = tm.makeTimeDataFrame()
  144. _check_plot_works(df.plot, grid=False)
  145. _check_plot_works(df.plot, subplots=True)
  146. _check_plot_works(df.plot, subplots=True, use_index=False)
  147. df = DataFrame({'x':[1,2], 'y':[3,4]})
  148. self._check_plot_fails(df.plot, kind='line', blarg=True)
  149. df = DataFrame(np.random.rand(10, 3),
  150. index=list(string.ascii_letters[:10]))
  151. _check_plot_works(df.plot, use_index=True)
  152. _check_plot_works(df.plot, sort_columns=False)
  153. _check_plot_works(df.plot, yticks=[1, 5, 10])
  154. _check_plot_works(df.plot, xticks=[1, 5, 10])
  155. _check_plot_works(df.plot, ylim=(-100, 100), xlim=(-100, 100))
  156. _check_plot_works(df.plot, subplots=True, title='blah')
  157. _check_plot_works(df.plot, title='blah')
  158. tuples = zip(list(string.ascii_letters[:10]), range(10))
  159. df = DataFrame(np.random.rand(10, 3),
  160. index=MultiIndex.from_tuples(tuples))
  161. _check_plot_works(df.plot, use_index=True)
  162. # unicode
  163. index = MultiIndex.from_tuples([(u'\u03b1', 0),
  164. (u'\u03b1', 1),
  165. (u'\u03b2', 2),
  166. (u'\u03b2', 3),
  167. (u'\u03b3', 4),
  168. (u'\u03b3', 5),
  169. (u'\u03b4', 6),
  170. (u'\u03b4', 7)], names=['i0', 'i1'])
  171. columns = MultiIndex.from_tuples([('bar', u'\u0394'),
  172. ('bar', u'\u0395')], names=['c0', 'c1'])
  173. df = DataFrame(np.random.randint(0, 10, (8, 2)),
  174. columns=columns,
  175. index=index)
  176. _check_plot_works(df.plot, title=u'\u03A3')
  177. @slow
  178. def test_plot_xy(self):
  179. import matplotlib.pyplot as plt
  180. # columns.inferred_type == 'string'
  181. df = tm.makeTimeDataFrame()
  182. self._check_data(df.plot(x=0, y=1),
  183. df.set_index('A')['B'].plot())
  184. self._check_data(df.plot(x=0), df.set_index('A').plot())
  185. self._check_data(df.plot(y=0), df.B.plot())
  186. self._check_data(df.plot(x='A', y='B'),
  187. df.set_index('A').B.plot())
  188. self._check_data(df.plot(x='A'), df.set_index('A').plot())
  189. self._check_data(df.plot(y='B'), df.B.plot())
  190. # columns.inferred_type == 'integer'
  191. df.columns = range(1, len(df.columns) + 1)
  192. self._check_data(df.plot(x=1, y=2),
  193. df.set_index(1)[2].plot())
  194. self._check_data(df.plot(x=1), df.set_index(1).plot())
  195. self._check_data(df.plot(y=1), df[1].plot())
  196. # figsize and title
  197. plt.close('all')
  198. ax = df.plot(x=1, y=2, title='Test', figsize=(16, 8))
  199. self.assert_(ax.title.get_text() == 'Test')
  200. self.assert_((np.round(ax.figure.get_size_inches())
  201. == np.array((16., 8.))).all())
  202. # columns.inferred_type == 'mixed'
  203. # TODO add MultiIndex test
  204. @slow
  205. def test_xcompat(self):
  206. import pandas as pd
  207. import matplotlib.pyplot as plt
  208. df = tm.makeTimeDataFrame()
  209. ax = df.plot(x_compat=True)
  210. lines = ax.get_lines()
  211. self.assert_(not isinstance(lines[0].get_xdata(), PeriodIndex))
  212. plt.close('all')
  213. pd.plot_params['xaxis.compat'] = True
  214. ax = df.plot()
  215. lines = ax.get_lines()
  216. self.assert_(not isinstance(lines[0].get_xdata(), PeriodIndex))
  217. plt.close('all')
  218. pd.plot_params['x_compat'] = False
  219. ax = df.plot()
  220. lines = ax.get_lines()
  221. self.assert_(isinstance(lines[0].get_xdata(), PeriodIndex))
  222. plt.close('all')
  223. #useful if you're plotting a bunch together
  224. with pd.plot_params.use('x_compat', True):
  225. ax = df.plot()
  226. lines = ax.get_lines()
  227. self.assert_(not isinstance(lines[0].get_xdata(), PeriodIndex))
  228. plt.close('all')
  229. ax = df.plot()
  230. lines = ax.get_lines()
  231. self.assert_(isinstance(lines[0].get_xdata(), PeriodIndex))
  232. def _check_data(self, xp, rs):
  233. xp_lines = xp.get_lines()
  234. rs_lines = rs.get_lines()
  235. def check_line(xpl, rsl):
  236. xpdata = xpl.get_xydata()
  237. rsdata = rsl.get_xydata()
  238. assert_array_equal(xpdata, rsdata)
  239. [check_line(xpl, rsl) for xpl, rsl in zip(xp_lines, rs_lines)]
  240. @slow
  241. def test_subplots(self):
  242. df = DataFrame(np.random.rand(10, 3),
  243. index=list(string.ascii_letters[:10]))
  244. axes = df.plot(subplots=True, sharex=True, legend=True)
  245. for ax in axes:
  246. self.assert_(ax.get_legend() is not None)
  247. axes = df.plot(subplots=True, sharex=True)
  248. for ax in axes[:-2]:
  249. [self.assert_(not label.get_visible())
  250. for label in ax.get_xticklabels()]
  251. [self.assert_(label.get_visible())
  252. for label in ax.get_yticklabels()]
  253. [self.assert_(label.get_visible())
  254. for label in axes[-1].get_xticklabels()]
  255. [self.assert_(label.get_visible())
  256. for label in axes[-1].get_yticklabels()]
  257. axes = df.plot(subplots=True, sharex=False)
  258. for ax in axes:
  259. [self.assert_(label.get_visible())
  260. for label in ax.get_xticklabels()]
  261. [self.assert_(label.get_visible())
  262. for label in ax.get_yticklabels()]
  263. @slow
  264. def test_plot_bar(self):
  265. df = DataFrame(np.random.randn(6, 4),
  266. index=list(string.ascii_letters[:6]),
  267. columns=['one', 'two', 'three', 'four'])
  268. _check_plot_works(df.plot, kind='bar')
  269. _check_plot_works(df.plot, kind='bar', legend=False)
  270. _check_plot_works(df.plot, kind='bar', subplots=True)
  271. _check_plot_works(df.plot, kind='bar', stacked=True)
  272. df = DataFrame(np.random.randn(10, 15),
  273. index=list(string.ascii_letters[:10]),
  274. columns=range(15))
  275. _check_plot_works(df.plot, kind='bar')
  276. df = DataFrame({'a': [0, 1], 'b': [1, 0]})
  277. _check_plot_works(df.plot, kind='bar')
  278. @slow
  279. def test_bar_stacked_center(self):
  280. #GH2157
  281. df = DataFrame({'A' : [3] * 5, 'B' : range(5)}, index = range(5))
  282. ax = df.plot(kind='bar', stacked='True', grid=True)
  283. self.assertEqual(ax.xaxis.get_ticklocs()[0],
  284. ax.patches[0].get_x() + ax.patches[0].get_width() / 2)
  285. @slow
  286. def test_bar_center(self):
  287. df = DataFrame({'A' : [3] * 5, 'B' : range(5)}, index = range(5))
  288. ax = df.plot(kind='bar', grid=True)
  289. self.assertEqual(ax.xaxis.get_ticklocs()[0],
  290. ax.patches[0].get_x() + ax.patches[0].get_width())
  291. @slow
  292. def test_boxplot(self):
  293. df = DataFrame(np.random.randn(6, 4),
  294. index=list(string.ascii_letters[:6]),
  295. columns=['one', 'two', 'three', 'four'])
  296. df['indic'] = ['foo', 'bar'] * 3
  297. df['indic2'] = ['foo', 'bar', 'foo'] * 2
  298. _check_plot_works(df.boxplot)
  299. _check_plot_works(df.boxplot, column=['one', 'two'])
  300. _check_plot_works(df.boxplot, column=['one', 'two'],
  301. by='indic')
  302. _check_plot_works(df.boxplot, column='one', by=['indic', 'indic2'])
  303. _check_plot_works(df.boxplot, by='indic')
  304. _check_plot_works(df.boxplot, by=['indic', 'indic2'])
  305. _check_plot_works(lambda x: plotting.boxplot(x), df['one'])
  306. _check_plot_works(df.boxplot, notch=1)
  307. _check_plot_works(df.boxplot, by='indic', notch=1)
  308. df = DataFrame(np.random.rand(10,2), columns=['Col1', 'Col2'] )
  309. df['X'] = Series(['A','A','A','A','A','B','B','B','B','B'])
  310. _check_plot_works(df.boxplot, by='X')
  311. @slow
  312. def test_kde(self):
  313. _skip_if_no_scipy()
  314. df = DataFrame(np.random.randn(100, 4))
  315. _check_plot_works(df.plot, kind='kde')
  316. _check_plot_works(df.plot, kind='kde', subplots=True)
  317. axes = df.plot(kind='kde', logy=True, subplots=True)
  318. for ax in axes:
  319. self.assert_(ax.get_yscale() == 'log')
  320. @slow
  321. def test_hist(self):
  322. df = DataFrame(np.random.randn(100, 4))
  323. _check_plot_works(df.hist)
  324. _check_plot_works(df.hist, grid=False)
  325. #make sure layout is handled
  326. df = DataFrame(np.random.randn(100, 3))
  327. _check_plot_works(df.hist)
  328. axes = df.hist(grid=False)
  329. self.assert_(not axes[1, 1].get_visible())
  330. df = DataFrame(np.random.randn(100, 1))
  331. _check_plot_works(df.hist)
  332. #make sure layout is handled
  333. df = DataFrame(np.random.randn(100, 6))
  334. _check_plot_works(df.hist)
  335. #make sure sharex, sharey is handled
  336. _check_plot_works(df.hist, sharex=True, sharey=True)
  337. #make sure kwargs are handled
  338. ser = df[0]
  339. xf, yf = 20, 20
  340. xrot, yrot = 30, 30
  341. ax = ser.hist(xlabelsize=xf, xrot=30, ylabelsize=yf, yrot=30)
  342. ytick = ax.get_yticklabels()[0]
  343. xtick = ax.get_xticklabels()[0]
  344. self.assertAlmostEqual(ytick.get_fontsize(), yf)
  345. self.assertAlmostEqual(ytick.get_rotation(), yrot)
  346. self.assertAlmostEqual(xtick.get_fontsize(), xf)
  347. self.assertAlmostEqual(xtick.get_rotation(), xrot)
  348. xf, yf = 20, 20
  349. xrot, yrot = 30, 30
  350. axes = df.hist(xlabelsize=xf, xrot=30, ylabelsize=yf, yrot=30)
  351. for i, ax in enumerate(axes.ravel()):
  352. if i < len(df.columns):
  353. ytick = ax.get_yticklabels()[0]
  354. xtick = ax.get_xticklabels()[0]
  355. self.assertAlmostEqual(ytick.get_fontsize(), yf)
  356. self.assertAlmostEqual(ytick.get_rotation(), yrot)
  357. self.assertAlmostEqual(xtick.get_fontsize(), xf)
  358. self.assertAlmostEqual(xtick.get_rotation(), xrot)
  359. @slow
  360. def test_scatter(self):
  361. _skip_if_no_scipy()
  362. df = DataFrame(np.random.randn(100, 4))
  363. import pandas.tools.plotting as plt
  364. def scat(**kwds):
  365. return plt.scatter_matrix(df, **kwds)
  366. _check_plot_works(scat)
  367. _check_plot_works(scat, marker='+')
  368. _check_plot_works(scat, vmin=0)
  369. _check_plot_works(scat, diagonal='kde')
  370. _check_plot_works(scat, diagonal='density')
  371. _check_plot_works(scat, diagonal='hist')
  372. def scat2(x, y, by=None, ax=None, figsize=None):
  373. return plt.scatter_plot(df, x, y, by, ax, figsize=None)
  374. _check_plot_works(scat2, 0, 1)
  375. grouper = Series(np.repeat([1, 2, 3, 4, 5], 20), df.index)
  376. _check_plot_works(scat2, 0, 1, by=grouper)
  377. @slow
  378. def test_andrews_curves(self):
  379. from pandas import read_csv
  380. from pandas.tools.plotting import andrews_curves
  381. path = os.path.join(curpath(), 'data/iris.csv')
  382. df = read_csv(path)
  383. _check_plot_works(andrews_curves, df, 'Name')
  384. @slow
  385. def test_parallel_coordinates(self):
  386. from pandas import read_csv
  387. from pandas.tools.plotting import parallel_coordinates
  388. path = os.path.join(curpath(), 'data/iris.csv')
  389. df = read_csv(path)
  390. _check_plot_works(parallel_coordinates, df, 'Name')
  391. _check_plot_works(parallel_coordinates, df, 'Name',
  392. colors=('#556270', '#4ECDC4', '#C7F464'))
  393. _check_plot_works(parallel_coordinates, df, 'Name',
  394. colors=['dodgerblue', 'aquamarine', 'seagreen'])
  395. _check_plot_works(parallel_coordinates, df, 'Name',
  396. colors=('#556270', '#4ECDC4', '#C7F464'))
  397. _check_plot_works(parallel_coordinates, df, 'Name',
  398. colors=['dodgerblue', 'aquamarine', 'seagreen'])
  399. df = read_csv(path, header=None, skiprows=1, names=[1,2,4,8, 'Name'])
  400. _check_plot_works(parallel_coordinates, df, 'Name', use_columns=True)
  401. _check_plot_works(parallel_coordinates, df, 'Name',
  402. xticks=[1, 5, 25, 125])
  403. @slow
  404. def test_radviz(self):
  405. from pandas import read_csv
  406. from pandas.tools.plotting import radviz
  407. path = os.path.join(curpath(), 'data/iris.csv')
  408. df = read_csv(path)
  409. _check_plot_works(radviz, df, 'Name')
  410. @slow
  411. def test_plot_int_columns(self):
  412. df = DataFrame(np.random.randn(100, 4)).cumsum()
  413. _check_plot_works(df.plot, legend=True)
  414. @slow
  415. def test_legend_name(self):
  416. multi = DataFrame(np.random.randn(4, 4),
  417. columns=[np.array(['a', 'a', 'b', 'b']),
  418. np.array(['x', 'y', 'x', 'y'])])
  419. multi.columns.names = ['group', 'individual']
  420. ax = multi.plot()
  421. leg_title = ax.legend_.get_title()
  422. self.assert_(leg_title.get_text(), 'group,individual')
  423. def _check_plot_fails(self, f, *args, **kwargs):
  424. self.assertRaises(Exception, f, *args, **kwargs)
  425. @slow
  426. def test_style_by_column(self):
  427. import matplotlib.pyplot as plt
  428. fig = plt.gcf()
  429. df = DataFrame(np.random.randn(100, 3))
  430. for markers in [{0: '^', 1: '+', 2: 'o'},
  431. {0: '^', 1: '+'},
  432. ['^', '+', 'o'],
  433. ['^', '+']]:
  434. fig.clf()
  435. fig.add_subplot(111)
  436. ax = df.plot(style=markers)
  437. for i, l in enumerate(ax.get_lines()[:len(markers)]):
  438. self.assertEqual(l.get_marker(), markers[i])
  439. @slow
  440. def test_line_colors(self):
  441. import matplotlib.pyplot as plt
  442. import sys
  443. from StringIO import StringIO
  444. custom_colors = 'rgcby'
  445. plt.close('all')
  446. df = DataFrame(np.random.randn(5, 5))
  447. ax = df.plot(color=custom_colors)
  448. lines = ax.get_lines()
  449. for i, l in enumerate(lines):
  450. xp = custom_colors[i]
  451. rs = l.get_color()
  452. self.assert_(xp == rs)
  453. tmp = sys.stderr
  454. sys.stderr = StringIO()
  455. try:
  456. plt.close('all')
  457. ax2 = df.plot(colors=custom_colors)
  458. lines2 = ax2.get_lines()
  459. for l1, l2 in zip(lines, lines2):
  460. self.assert_(l1.get_color(), l2.get_color())
  461. finally:
  462. sys.stderr = tmp
  463. # make color a list if plotting one column frame
  464. # handles cases like df.plot(color='DodgerBlue')
  465. plt.close('all')
  466. df.ix[:, [0]].plot(color='DodgerBlue')
  467. @slow
  468. def test_default_color_cycle(self):
  469. import matplotlib.pyplot as plt
  470. plt.rcParams['axes.color_cycle'] = list('rgbk')
  471. plt.close('all')
  472. df = DataFrame(np.random.randn(5, 3))
  473. ax = df.plot()
  474. lines = ax.get_lines()
  475. for i, l in enumerate(lines):
  476. xp = plt.rcParams['axes.color_cycle'][i]
  477. rs = l.get_color()
  478. self.assert_(xp == rs)
  479. class TestDataFrameGroupByPlots(unittest.TestCase):
  480. @classmethod
  481. def setUpClass(cls):
  482. #import sys
  483. #if 'IPython' in sys.modules:
  484. # raise nose.SkipTest
  485. try:
  486. import matplotlib as mpl
  487. mpl.use('Agg', warn=False)
  488. except ImportError:
  489. raise nose.SkipTest
  490. @slow
  491. def test_boxplot(self):
  492. df = DataFrame(np.random.rand(10,2), columns=['Col1', 'Col2'] )
  493. df['X'] = Series(['A','A','A','A','A','B','B','B','B','B'])
  494. grouped = df.groupby(by='X')
  495. _check_plot_works(grouped.boxplot)
  496. _check_plot_works(grouped.boxplot, subplots=False)
  497. tuples = zip(list(string.ascii_letters[:10]), range(10))
  498. df = DataFrame(np.random.rand(10, 3),
  499. index=MultiIndex.from_tuples(tuples))
  500. grouped = df.groupby(level=1)
  501. _check_plot_works(grouped.boxplot)
  502. _check_plot_works(grouped.boxplot, subplots=False)
  503. grouped = df.unstack(level=1).groupby(level=0, axis=1)
  504. _check_plot_works(grouped.boxplot)
  505. _check_plot_works(grouped.boxplot, subplots=False)
  506. @slow
  507. def test_series_plot_color_kwargs(self):
  508. # #1890
  509. import matplotlib.pyplot as plt
  510. plt.close('all')
  511. ax = Series(np.arange(12) + 1).plot(color='green')
  512. line = ax.get_lines()[0]
  513. self.assert_(line.get_color() == 'green')
  514. @slow
  515. def test_time_series_plot_color_kwargs(self):
  516. # #1890
  517. import matplotlib.pyplot as plt
  518. plt.close('all')
  519. ax = Series(np.arange(12) + 1, index=date_range('1/1/2000', periods=12)).plot(color='green')
  520. line = ax.get_lines()[0]
  521. self.assert_(line.get_color() == 'green')
  522. @slow
  523. def test_grouped_hist(self):
  524. import matplotlib.pyplot as plt
  525. df = DataFrame(np.random.randn(500, 2), columns=['A', 'B'])
  526. df['C'] = np.random.randint(0, 4, 500)
  527. axes = plotting.grouped_hist(df.A, by=df.C)
  528. self.assert_(len(axes.ravel()) == 4)
  529. plt.close('all')
  530. axes = df.hist(by=df.C)
  531. self.assert_(axes.ndim == 2)
  532. self.assert_(len(axes.ravel()) == 4)
  533. for ax in axes.ravel():
  534. self.assert_(len(ax.patches) > 0)
  535. PNG_PATH = 'tmp.png'
  536. def _check_plot_works(f, *args, **kwargs):
  537. import matplotlib.pyplot as plt
  538. fig = plt.gcf()
  539. plt.clf()
  540. ax = fig.add_subplot(211)
  541. ret = f(*args, **kwargs)
  542. assert(ret is not None) # do something more intelligent
  543. ax = fig.add_subplot(212)
  544. try:
  545. kwargs['ax'] = ax
  546. ret = f(*args, **kwargs)
  547. assert(ret is not None) # do something more intelligent
  548. except Exception:
  549. pass
  550. plt.savefig(PNG_PATH)
  551. os.remove(PNG_PATH)
  552. def curpath():
  553. pth, _ = os.path.split(os.path.abspath(__file__))
  554. return pth
  555. if __name__ == '__main__':
  556. nose.runmodule(argv=[__file__,'-vvs','-x','--pdb', '--pdb-failure'],
  557. exit=False)