PageRenderTime 83ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/pandas/tseries/tests/test_plotting.py

https://github.com/lenolib/pandas
Python | 880 lines | 750 code | 112 blank | 18 comment | 54 complexity | f9b21a1598df8ab16835e94c9fd959c2 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. import os
  2. from datetime import datetime, timedelta, date, time
  3. import unittest
  4. import nose
  5. import numpy as np
  6. from numpy.testing.decorators import slow
  7. from numpy.testing import assert_array_equal
  8. from pandas import Index, Series, DataFrame, isnull, notnull
  9. from pandas.tseries.index import date_range, bdate_range
  10. from pandas.tseries.offsets import Minute, DateOffset
  11. from pandas.tseries.period import period_range, Period
  12. from pandas.tseries.resample import DatetimeIndex, TimeGrouper
  13. import pandas.tseries.offsets as offsets
  14. import pandas.tseries.frequencies as frequencies
  15. from pandas.util.testing import assert_series_equal, assert_almost_equal
  16. import pandas.util.testing as tm
  17. class TestTSPlot(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. freq = ['S', 'T', 'H', 'D', 'W', 'M', 'Q', 'Y']
  30. idx = [period_range('12/31/1999', freq=x, periods=100) for x in freq]
  31. self.period_ser = [Series(np.random.randn(len(x)), x) for x in idx]
  32. self.period_df = [DataFrame(np.random.randn(len(x), 3), index=x,
  33. columns=['A', 'B', 'C'])
  34. for x in idx]
  35. freq = ['S', 'T', 'H', 'D', 'W', 'M', 'Q-DEC', 'A', '1B30Min']
  36. idx = [date_range('12/31/1999', freq=x, periods=100) for x in freq]
  37. self.datetime_ser = [Series(np.random.randn(len(x)), x) for x in idx]
  38. self.datetime_df = [DataFrame(np.random.randn(len(x), 3), index=x,
  39. columns=['A', 'B', 'C'])
  40. for x in idx]
  41. @slow
  42. def test_frame_inferred(self):
  43. # inferred freq
  44. import matplotlib.pyplot as plt
  45. plt.close('all')
  46. idx = date_range('1/1/1987', freq='MS', periods=100)
  47. idx = DatetimeIndex(idx.values, freq=None)
  48. df = DataFrame(np.random.randn(len(idx), 3), index=idx)
  49. df.plot()
  50. # axes freq
  51. idx = idx[0:40] + idx[45:99]
  52. df2 = DataFrame(np.random.randn(len(idx), 3), index=idx)
  53. df2.plot()
  54. plt.close('all')
  55. @slow
  56. def test_tsplot(self):
  57. from pandas.tseries.plotting import tsplot
  58. import matplotlib.pyplot as plt
  59. plt.close('all')
  60. ax = plt.gca()
  61. ts = tm.makeTimeSeries()
  62. tsplot(ts, plt.Axes.plot)
  63. f = lambda *args, **kwds: tsplot(s, plt.Axes.plot, *args, **kwds)
  64. plt.close('all')
  65. for s in self.period_ser:
  66. _check_plot_works(f, s.index.freq, ax=ax, series=s)
  67. plt.close('all')
  68. for s in self.datetime_ser:
  69. _check_plot_works(f, s.index.freq.rule_code, ax=ax, series=s)
  70. plt.close('all')
  71. plt.close('all')
  72. ax = ts.plot(style='k')
  73. self.assert_((0., 0., 0.) == ax.get_lines()[0].get_color())
  74. @slow
  75. def test_high_freq(self):
  76. freaks = ['ms', 'us']
  77. for freq in freaks:
  78. rng = date_range('1/1/2012', periods=100000, freq=freq)
  79. ser = Series(np.random.randn(len(rng)), rng)
  80. _check_plot_works(ser.plot)
  81. def test_get_datevalue(self):
  82. from pandas.tseries.plotting import get_datevalue
  83. self.assert_(get_datevalue(None, 'D') is None)
  84. self.assert_(get_datevalue(1987, 'A') == 1987)
  85. self.assert_(get_datevalue(Period(1987, 'A'), 'M') ==
  86. Period('1987-12', 'M').ordinal)
  87. self.assert_(get_datevalue('1/1/1987', 'D') ==
  88. Period('1987-1-1', 'D').ordinal)
  89. @slow
  90. def test_line_plot_period_series(self):
  91. for s in self.period_ser:
  92. _check_plot_works(s.plot, s.index.freq)
  93. @slow
  94. def test_line_plot_datetime_series(self):
  95. for s in self.datetime_ser:
  96. _check_plot_works(s.plot, s.index.freq.rule_code)
  97. @slow
  98. def test_line_plot_period_frame(self):
  99. for df in self.period_df:
  100. _check_plot_works(df.plot, df.index.freq)
  101. @slow
  102. def test_line_plot_datetime_frame(self):
  103. for df in self.datetime_df:
  104. freq = df.index.to_period(df.index.freq.rule_code).freq
  105. _check_plot_works(df.plot, freq)
  106. @slow
  107. def test_line_plot_inferred_freq(self):
  108. for ser in self.datetime_ser:
  109. ser = Series(ser.values, Index(np.asarray(ser.index)))
  110. _check_plot_works(ser.plot, ser.index.inferred_freq)
  111. ser = ser[[0, 3, 5, 6]]
  112. _check_plot_works(ser.plot)
  113. @slow
  114. def test_fake_inferred_business(self):
  115. import matplotlib.pyplot as plt
  116. fig = plt.gcf()
  117. plt.clf()
  118. fig.add_subplot(111)
  119. rng = date_range('2001-1-1', '2001-1-10')
  120. ts = Series(range(len(rng)), rng)
  121. ts = ts[:3].append(ts[5:])
  122. ax = ts.plot()
  123. self.assert_(not hasattr(ax, 'freq'))
  124. @slow
  125. def test_plot_offset_freq(self):
  126. ser = tm.makeTimeSeries()
  127. _check_plot_works(ser.plot)
  128. dr = date_range(ser.index[0], freq='BQS', periods=10)
  129. ser = Series(np.random.randn(len(dr)), dr)
  130. _check_plot_works(ser.plot)
  131. @slow
  132. def test_plot_multiple_inferred_freq(self):
  133. dr = Index([datetime(2000, 1, 1),
  134. datetime(2000, 1, 6),
  135. datetime(2000, 1, 11)])
  136. ser = Series(np.random.randn(len(dr)), dr)
  137. _check_plot_works(ser.plot)
  138. @slow
  139. def test_uhf(self):
  140. import pandas.tseries.converter as conv
  141. import matplotlib.pyplot as plt
  142. fig = plt.gcf()
  143. plt.clf()
  144. fig.add_subplot(111)
  145. idx = date_range('2012-6-22 21:59:51.960928', freq='L', periods=500)
  146. df = DataFrame(np.random.randn(len(idx), 2), idx)
  147. ax = df.plot()
  148. axis = ax.get_xaxis()
  149. tlocs = axis.get_ticklocs()
  150. tlabels = axis.get_ticklabels()
  151. for loc, label in zip(tlocs, tlabels):
  152. xp = conv._from_ordinal(loc).strftime('%H:%M:%S.%f')
  153. rs = str(label.get_text())
  154. if len(rs) != 0:
  155. self.assert_(xp == rs)
  156. @slow
  157. def test_irreg_hf(self):
  158. import matplotlib.pyplot as plt
  159. fig = plt.gcf()
  160. plt.clf()
  161. fig.add_subplot(111)
  162. idx = date_range('2012-6-22 21:59:51', freq='S', periods=100)
  163. df = DataFrame(np.random.randn(len(idx), 2), idx)
  164. irreg = df.ix[[0, 1, 3, 4]]
  165. ax = irreg.plot()
  166. diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff()
  167. sec = 1. / 24 / 60 / 60
  168. self.assert_((np.fabs(diffs[1:] - [sec, sec*2, sec]) < 1e-8).all())
  169. plt.clf()
  170. fig.add_subplot(111)
  171. df2 = df.copy()
  172. df2.index = df.index.asobject
  173. ax = df2.plot()
  174. diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff()
  175. self.assert_((np.fabs(diffs[1:] - sec) < 1e-8).all())
  176. @slow
  177. def test_irregular_datetime64_repr_bug(self):
  178. import matplotlib.pyplot as plt
  179. ser = tm.makeTimeSeries()
  180. ser = ser[[0,1,2,7]]
  181. fig = plt.gcf()
  182. plt.clf()
  183. ax = fig.add_subplot(211)
  184. ret = ser.plot()
  185. assert(ret is not None)
  186. for rs, xp in zip(ax.get_lines()[0].get_xdata(), ser.index):
  187. assert(rs == xp)
  188. @slow
  189. def test_business_freq(self):
  190. import matplotlib.pyplot as plt
  191. plt.close('all')
  192. bts = tm.makePeriodSeries()
  193. ax = bts.plot()
  194. self.assert_(ax.get_lines()[0].get_xydata()[0, 0],
  195. bts.index[0].ordinal)
  196. idx = ax.get_lines()[0].get_xdata()
  197. self.assert_(idx.freqstr == 'B')
  198. @slow
  199. def test_business_freq_convert(self):
  200. import matplotlib.pyplot as plt
  201. plt.close('all')
  202. n = tm.N
  203. tm.N = 300
  204. bts = tm.makeTimeSeries().asfreq('BM')
  205. tm.N = n
  206. ts = bts.to_period('M')
  207. ax = bts.plot()
  208. self.assert_(ax.get_lines()[0].get_xydata()[0, 0], ts.index[0].ordinal)
  209. idx = ax.get_lines()[0].get_xdata()
  210. self.assert_(idx.freqstr == 'M')
  211. @slow
  212. def test_dataframe(self):
  213. bts = DataFrame({'a': tm.makeTimeSeries()})
  214. ax = bts.plot()
  215. idx = ax.get_lines()[0].get_xdata()
  216. @slow
  217. def test_axis_limits(self):
  218. def _test(ax):
  219. xlim = ax.get_xlim()
  220. ax.set_xlim(xlim[0] - 5, xlim[1] + 10)
  221. ax.get_figure().canvas.draw()
  222. result = ax.get_xlim()
  223. self.assertEqual(result[0], xlim[0] - 5)
  224. self.assertEqual(result[1], xlim[1] + 10)
  225. # string
  226. expected = (Period('1/1/2000', ax.freq),
  227. Period('4/1/2000', ax.freq))
  228. ax.set_xlim('1/1/2000', '4/1/2000')
  229. ax.get_figure().canvas.draw()
  230. result = ax.get_xlim()
  231. self.assertEqual(int(result[0]), expected[0].ordinal)
  232. self.assertEqual(int(result[1]), expected[1].ordinal)
  233. # datetim
  234. expected = (Period('1/1/2000', ax.freq),
  235. Period('4/1/2000', ax.freq))
  236. ax.set_xlim(datetime(2000, 1, 1), datetime(2000, 4, 1))
  237. ax.get_figure().canvas.draw()
  238. result = ax.get_xlim()
  239. self.assertEqual(int(result[0]), expected[0].ordinal)
  240. self.assertEqual(int(result[1]), expected[1].ordinal)
  241. ser = tm.makeTimeSeries()
  242. ax = ser.plot()
  243. _test(ax)
  244. df = DataFrame({'a' : ser, 'b' : ser + 1})
  245. ax = df.plot()
  246. _test(ax)
  247. df = DataFrame({'a' : ser, 'b' : ser + 1})
  248. axes = df.plot(subplots=True)
  249. [_test(ax) for ax in axes]
  250. def test_get_finder(self):
  251. import pandas.tseries.converter as conv
  252. self.assertEqual(conv.get_finder('B'), conv._daily_finder)
  253. self.assertEqual(conv.get_finder('D'), conv._daily_finder)
  254. self.assertEqual(conv.get_finder('M'), conv._monthly_finder)
  255. self.assertEqual(conv.get_finder('Q'), conv._quarterly_finder)
  256. self.assertEqual(conv.get_finder('A'), conv._annual_finder)
  257. self.assertEqual(conv.get_finder('W'), conv._daily_finder)
  258. @slow
  259. def test_finder_daily(self):
  260. xp = Period('1999-1-1', freq='B').ordinal
  261. day_lst = [10, 40, 252, 400, 950, 2750, 10000]
  262. for n in day_lst:
  263. rng = bdate_range('1999-1-1', periods=n)
  264. ser = Series(np.random.randn(len(rng)), rng)
  265. ax = ser.plot()
  266. xaxis = ax.get_xaxis()
  267. rs = xaxis.get_majorticklocs()[0]
  268. self.assertEqual(xp, rs)
  269. (vmin, vmax) = ax.get_xlim()
  270. ax.set_xlim(vmin + 0.9, vmax)
  271. rs = xaxis.get_majorticklocs()[0]
  272. self.assertEqual(xp, rs)
  273. @slow
  274. def test_finder_quarterly(self):
  275. import matplotlib.pyplot as plt
  276. xp = Period('1988Q1').ordinal
  277. yrs = [3.5, 11]
  278. plt.close('all')
  279. for n in yrs:
  280. rng = period_range('1987Q2', periods=int(n * 4), freq='Q')
  281. ser = Series(np.random.randn(len(rng)), rng)
  282. ax = ser.plot()
  283. xaxis = ax.get_xaxis()
  284. rs = xaxis.get_majorticklocs()[0]
  285. self.assert_(rs == xp)
  286. (vmin, vmax) = ax.get_xlim()
  287. ax.set_xlim(vmin + 0.9, vmax)
  288. rs = xaxis.get_majorticklocs()[0]
  289. self.assertEqual(xp, rs)
  290. @slow
  291. def test_finder_monthly(self):
  292. import matplotlib.pyplot as plt
  293. xp = Period('Jan 1988').ordinal
  294. yrs = [1.15, 2.5, 4, 11]
  295. plt.close('all')
  296. for n in yrs:
  297. rng = period_range('1987Q2', periods=int(n * 12), freq='M')
  298. ser = Series(np.random.randn(len(rng)), rng)
  299. ax = ser.plot()
  300. xaxis = ax.get_xaxis()
  301. rs = xaxis.get_majorticklocs()[0]
  302. self.assert_(rs == xp)
  303. (vmin, vmax) = ax.get_xlim()
  304. ax.set_xlim(vmin + 0.9, vmax)
  305. rs = xaxis.get_majorticklocs()[0]
  306. self.assertEqual(xp, rs)
  307. plt.close('all')
  308. @slow
  309. def test_finder_monthly_long(self):
  310. import matplotlib.pyplot as plt
  311. plt.close('all')
  312. rng = period_range('1988Q1', periods=24*12, freq='M')
  313. ser = Series(np.random.randn(len(rng)), rng)
  314. ax = ser.plot()
  315. xaxis = ax.get_xaxis()
  316. rs = xaxis.get_majorticklocs()[0]
  317. xp = Period('1989Q1', 'M').ordinal
  318. self.assert_(rs == xp)
  319. @slow
  320. def test_finder_annual(self):
  321. import matplotlib.pyplot as plt
  322. plt.close('all')
  323. xp = [1987, 1988, 1990, 1990, 1995, 2020, 2070, 2170]
  324. for i, nyears in enumerate([5, 10, 19, 49, 99, 199, 599, 1001]):
  325. rng = period_range('1987', periods=nyears, freq='A')
  326. ser = Series(np.random.randn(len(rng)), rng)
  327. ax = ser.plot()
  328. xaxis = ax.get_xaxis()
  329. rs = xaxis.get_majorticklocs()[0]
  330. self.assert_(rs == Period(xp[i], freq='A').ordinal)
  331. plt.close('all')
  332. @slow
  333. def test_finder_minutely(self):
  334. import matplotlib.pyplot as plt
  335. plt.close('all')
  336. nminutes = 50 * 24 * 60
  337. rng = date_range('1/1/1999', freq='Min', periods=nminutes)
  338. ser = Series(np.random.randn(len(rng)), rng)
  339. ax = ser.plot()
  340. xaxis = ax.get_xaxis()
  341. rs = xaxis.get_majorticklocs()[0]
  342. xp = Period('1/1/1999', freq='Min').ordinal
  343. self.assertEqual(rs, xp)
  344. @slow
  345. def test_finder_hourly(self):
  346. import matplotlib.pyplot as plt
  347. plt.close('all')
  348. nhours = 23
  349. rng = date_range('1/1/1999', freq='H', periods=nhours)
  350. ser = Series(np.random.randn(len(rng)), rng)
  351. ax = ser.plot()
  352. xaxis = ax.get_xaxis()
  353. rs = xaxis.get_majorticklocs()[0]
  354. xp = Period('1/1/1999', freq='H').ordinal
  355. self.assertEqual(rs, xp)
  356. @slow
  357. def test_gaps(self):
  358. import matplotlib.pyplot as plt
  359. plt.close('all')
  360. ts = tm.makeTimeSeries()
  361. ts[5:25] = np.nan
  362. ax = ts.plot()
  363. lines = ax.get_lines()
  364. self.assert_(len(lines) == 1)
  365. l = lines[0]
  366. data = l.get_xydata()
  367. self.assert_(isinstance(data, np.ma.core.MaskedArray))
  368. mask = data.mask
  369. self.assert_(mask[5:25, 1].all())
  370. # irregular
  371. plt.close('all')
  372. ts = tm.makeTimeSeries()
  373. ts = ts[[0, 1, 2, 5, 7, 9, 12, 15, 20]]
  374. ts[2:5] = np.nan
  375. ax = ts.plot()
  376. lines = ax.get_lines()
  377. self.assert_(len(lines) == 1)
  378. l = lines[0]
  379. data = l.get_xydata()
  380. self.assert_(isinstance(data, np.ma.core.MaskedArray))
  381. mask = data.mask
  382. self.assert_(mask[2:5, 1].all())
  383. # non-ts
  384. plt.close('all')
  385. idx = [0, 1, 2, 5, 7, 9, 12, 15, 20]
  386. ser = Series(np.random.randn(len(idx)), idx)
  387. ser[2:5] = np.nan
  388. ax = ser.plot()
  389. lines = ax.get_lines()
  390. self.assert_(len(lines) == 1)
  391. l = lines[0]
  392. data = l.get_xydata()
  393. self.assert_(isinstance(data, np.ma.core.MaskedArray))
  394. mask = data.mask
  395. self.assert_(mask[2:5, 1].all())
  396. @slow
  397. def test_gap_upsample(self):
  398. import matplotlib.pyplot as plt
  399. plt.close('all')
  400. low = tm.makeTimeSeries()
  401. low[5:25] = np.nan
  402. ax = low.plot()
  403. idxh = date_range(low.index[0], low.index[-1], freq='12h')
  404. s = Series(np.random.randn(len(idxh)), idxh)
  405. s.plot(secondary_y=True)
  406. lines = ax.get_lines()
  407. self.assert_(len(lines) == 1)
  408. self.assert_(len(ax.right_ax.get_lines()) == 1)
  409. l = lines[0]
  410. data = l.get_xydata()
  411. self.assert_(isinstance(data, np.ma.core.MaskedArray))
  412. mask = data.mask
  413. self.assert_(mask[5:25, 1].all())
  414. @slow
  415. def test_secondary_y(self):
  416. import matplotlib.pyplot as plt
  417. plt.close('all')
  418. ser = Series(np.random.randn(10))
  419. ser2 = Series(np.random.randn(10))
  420. ax = ser.plot(secondary_y=True).right_ax
  421. fig = ax.get_figure()
  422. axes = fig.get_axes()
  423. l = ax.get_lines()[0]
  424. xp = Series(l.get_ydata(), l.get_xdata())
  425. assert_series_equal(ser, xp)
  426. self.assert_(ax.get_yaxis().get_ticks_position() == 'right')
  427. self.assert_(not axes[0].get_yaxis().get_visible())
  428. ax2 = ser2.plot()
  429. self.assert_(ax2.get_yaxis().get_ticks_position() == 'left')
  430. plt.close('all')
  431. ax = ser2.plot()
  432. ax2 = ser.plot(secondary_y=True).right_ax
  433. self.assert_(ax.get_yaxis().get_visible())
  434. plt.close('all')
  435. @slow
  436. def test_secondary_y_ts(self):
  437. import matplotlib.pyplot as plt
  438. plt.close('all')
  439. idx = date_range('1/1/2000', periods=10)
  440. ser = Series(np.random.randn(10), idx)
  441. ser2 = Series(np.random.randn(10), idx)
  442. ax = ser.plot(secondary_y=True).right_ax
  443. fig = ax.get_figure()
  444. axes = fig.get_axes()
  445. l = ax.get_lines()[0]
  446. xp = Series(l.get_ydata(), l.get_xdata()).to_timestamp()
  447. assert_series_equal(ser, xp)
  448. self.assert_(ax.get_yaxis().get_ticks_position() == 'right')
  449. self.assert_(not axes[0].get_yaxis().get_visible())
  450. ax2 = ser2.plot()
  451. self.assert_(ax2.get_yaxis().get_ticks_position() == 'left')
  452. plt.close('all')
  453. ax = ser2.plot()
  454. ax2 = ser.plot(secondary_y=True)
  455. self.assert_(ax.get_yaxis().get_visible())
  456. @slow
  457. def test_secondary_kde(self):
  458. import matplotlib.pyplot as plt
  459. plt.close('all')
  460. ser = Series(np.random.randn(10))
  461. ax = ser.plot(secondary_y=True, kind='density').right_ax
  462. fig = ax.get_figure()
  463. axes = fig.get_axes()
  464. self.assert_(axes[1].get_yaxis().get_ticks_position() == 'right')
  465. @slow
  466. def test_secondary_bar(self):
  467. import matplotlib.pyplot as plt
  468. plt.close('all')
  469. ser = Series(np.random.randn(10))
  470. ax = ser.plot(secondary_y=True, kind='bar')
  471. fig = ax.get_figure()
  472. axes = fig.get_axes()
  473. self.assert_(axes[1].get_yaxis().get_ticks_position() == 'right')
  474. @slow
  475. def test_secondary_frame(self):
  476. import matplotlib.pyplot as plt
  477. plt.close('all')
  478. df = DataFrame(np.random.randn(5, 3), columns=['a', 'b', 'c'])
  479. axes = df.plot(secondary_y=['a', 'c'], subplots=True)
  480. self.assert_(axes[0].get_yaxis().get_ticks_position() == 'right')
  481. self.assert_(axes[1].get_yaxis().get_ticks_position() == 'default')
  482. self.assert_(axes[2].get_yaxis().get_ticks_position() == 'right')
  483. @slow
  484. def test_mixed_freq_regular_first(self):
  485. import matplotlib.pyplot as plt
  486. plt.close('all')
  487. s1 = tm.makeTimeSeries()
  488. s2 = s1[[0, 5, 10, 11, 12, 13, 14, 15]]
  489. s1.plot()
  490. ax2 = s2.plot(style='g')
  491. lines = ax2.get_lines()
  492. idx1 = lines[0].get_xdata()
  493. idx2 = lines[1].get_xdata()
  494. self.assert_(idx1.equals(s1.index.to_period('B')))
  495. self.assert_(idx2.equals(s2.index.to_period('B')))
  496. left, right = ax2.get_xlim()
  497. pidx = s1.index.to_period()
  498. self.assert_(left == pidx[0].ordinal)
  499. self.assert_(right == pidx[-1].ordinal)
  500. plt.close('all')
  501. @slow
  502. def test_mixed_freq_irregular_first(self):
  503. import matplotlib.pyplot as plt
  504. plt.close('all')
  505. s1 = tm.makeTimeSeries()
  506. s2 = s1[[0, 5, 10, 11, 12, 13, 14, 15]]
  507. s2.plot(style='g')
  508. ax = s1.plot()
  509. self.assert_(not hasattr(ax, 'freq'))
  510. lines = ax.get_lines()
  511. x1 = lines[0].get_xdata()
  512. assert_array_equal(x1, s2.index.asobject.values)
  513. x2 = lines[1].get_xdata()
  514. assert_array_equal(x2, s1.index.asobject.values)
  515. plt.close('all')
  516. @slow
  517. def test_mixed_freq_hf_first(self):
  518. import matplotlib.pyplot as plt
  519. plt.close('all')
  520. idxh = date_range('1/1/1999', periods=365, freq='D')
  521. idxl = date_range('1/1/1999', periods=12, freq='M')
  522. high = Series(np.random.randn(len(idxh)), idxh)
  523. low = Series(np.random.randn(len(idxl)), idxl)
  524. high.plot()
  525. ax = low.plot()
  526. for l in ax.get_lines():
  527. self.assert_(l.get_xdata().freq == 'D')
  528. @slow
  529. def test_mixed_freq_lf_first(self):
  530. import matplotlib.pyplot as plt
  531. plt.close('all')
  532. idxh = date_range('1/1/1999', periods=365, freq='D')
  533. idxl = date_range('1/1/1999', periods=12, freq='M')
  534. high = Series(np.random.randn(len(idxh)), idxh)
  535. low = Series(np.random.randn(len(idxl)), idxl)
  536. low.plot()
  537. ax = high.plot()
  538. for l in ax.get_lines():
  539. self.assert_(l.get_xdata().freq == 'D')
  540. plt.close('all')
  541. idxh = date_range('1/1/1999', periods=240, freq='T')
  542. idxl = date_range('1/1/1999', periods=4, freq='H')
  543. high = Series(np.random.randn(len(idxh)), idxh)
  544. low = Series(np.random.randn(len(idxl)), idxl)
  545. low.plot()
  546. ax = high.plot()
  547. for l in ax.get_lines():
  548. self.assert_(l.get_xdata().freq == 'T')
  549. @slow
  550. def test_mixed_freq_irreg_period(self):
  551. ts = tm.makeTimeSeries()
  552. irreg = ts[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 18, 29]]
  553. rng = period_range('1/3/2000', periods=30, freq='B')
  554. ps = Series(np.random.randn(len(rng)), rng)
  555. irreg.plot()
  556. ps.plot()
  557. @slow
  558. def test_to_weekly_resampling(self):
  559. import matplotlib.pyplot as plt
  560. plt.close('all')
  561. idxh = date_range('1/1/1999', periods=52, freq='W')
  562. idxl = date_range('1/1/1999', periods=12, freq='M')
  563. high = Series(np.random.randn(len(idxh)), idxh)
  564. low = Series(np.random.randn(len(idxl)), idxl)
  565. high.plot()
  566. ax = low.plot()
  567. for l in ax.get_lines():
  568. self.assert_(l.get_xdata().freq.startswith('W'))
  569. @slow
  570. def test_from_weekly_resampling(self):
  571. import matplotlib.pyplot as plt
  572. plt.close('all')
  573. idxh = date_range('1/1/1999', periods=52, freq='W')
  574. idxl = date_range('1/1/1999', periods=12, freq='M')
  575. high = Series(np.random.randn(len(idxh)), idxh)
  576. low = Series(np.random.randn(len(idxl)), idxl)
  577. low.plot()
  578. ax = high.plot()
  579. for l in ax.get_lines():
  580. self.assert_(l.get_xdata().freq.startswith('W'))
  581. @slow
  582. def test_irreg_dtypes(self):
  583. import matplotlib.pyplot as plt
  584. #date
  585. idx = [date(2000, 1, 1), date(2000, 1, 5), date(2000, 1, 20)]
  586. df = DataFrame(np.random.randn(len(idx), 3), Index(idx, dtype=object))
  587. _check_plot_works(df.plot)
  588. #np.datetime64
  589. idx = date_range('1/1/2000', periods=10)
  590. idx = idx[[0, 2, 5, 9]].asobject
  591. df = DataFrame(np.random.randn(len(idx), 3), idx)
  592. _check_plot_works(df.plot)
  593. @slow
  594. def test_time(self):
  595. import matplotlib.pyplot as plt
  596. plt.close('all')
  597. t = datetime(1, 1, 1, 3, 30, 0)
  598. deltas = np.random.randint(1, 20, 3).cumsum()
  599. ts = np.array([(t + timedelta(minutes=int(x))).time() for x in deltas])
  600. df = DataFrame({'a' : np.random.randn(len(ts)),
  601. 'b' : np.random.randn(len(ts))},
  602. index=ts)
  603. ax = df.plot()
  604. # verify tick labels
  605. ticks = ax.get_xticks()
  606. labels = ax.get_xticklabels()
  607. for t, l in zip(ticks, labels):
  608. m, s = divmod(int(t), 60)
  609. h, m = divmod(m, 60)
  610. xp = l.get_text()
  611. if len(xp) > 0:
  612. rs = time(h, m, s).strftime('%H:%M:%S')
  613. self.assert_(xp, rs)
  614. # change xlim
  615. ax.set_xlim('1:30', '5:00')
  616. # check tick labels again
  617. ticks = ax.get_xticks()
  618. labels = ax.get_xticklabels()
  619. for t, l in zip(ticks, labels):
  620. m, s = divmod(int(t), 60)
  621. h, m = divmod(m, 60)
  622. xp = l.get_text()
  623. if len(xp) > 0:
  624. rs = time(h, m, s).strftime('%H:%M:%S')
  625. self.assert_(xp, rs)
  626. @slow
  627. def test_time_musec(self):
  628. import matplotlib.pyplot as plt
  629. plt.close('all')
  630. t = datetime(1, 1, 1, 3, 30, 0)
  631. deltas = np.random.randint(1, 20, 3).cumsum()
  632. ts = np.array([(t + timedelta(microseconds=int(x))).time()
  633. for x in deltas])
  634. df = DataFrame({'a' : np.random.randn(len(ts)),
  635. 'b' : np.random.randn(len(ts))},
  636. index=ts)
  637. ax = df.plot()
  638. # verify tick labels
  639. ticks = ax.get_xticks()
  640. labels = ax.get_xticklabels()
  641. for t, l in zip(ticks, labels):
  642. m, s = divmod(int(t), 60)
  643. us = int((t - int(t)) * 1e6)
  644. h, m = divmod(m, 60)
  645. xp = l.get_text()
  646. if len(xp) > 0:
  647. rs = time(h, m, s).strftime('%H:%M:%S.%f')
  648. self.assert_(xp, rs)
  649. @slow
  650. def test_secondary_upsample(self):
  651. import matplotlib.pyplot as plt
  652. plt.close('all')
  653. idxh = date_range('1/1/1999', periods=365, freq='D')
  654. idxl = date_range('1/1/1999', periods=12, freq='M')
  655. high = Series(np.random.randn(len(idxh)), idxh)
  656. low = Series(np.random.randn(len(idxl)), idxl)
  657. low.plot()
  658. ax = high.plot(secondary_y=True)
  659. for l in ax.get_lines():
  660. self.assert_(l.get_xdata().freq == 'D')
  661. for l in ax.right_ax.get_lines():
  662. self.assert_(l.get_xdata().freq == 'D')
  663. @slow
  664. def test_secondary_legend(self):
  665. import matplotlib.pyplot as plt
  666. fig = plt.gcf()
  667. plt.clf()
  668. ax = fig.add_subplot(211)
  669. #ts
  670. df = tm.makeTimeDataFrame()
  671. ax = df.plot(secondary_y=['A', 'B'])
  672. leg = ax.get_legend()
  673. self.assert_(len(leg.get_lines()) == 4)
  674. self.assert_(leg.get_texts()[0].get_text() == 'A (right)')
  675. self.assert_(leg.get_texts()[1].get_text() == 'B (right)')
  676. self.assert_(leg.get_texts()[2].get_text() == 'C')
  677. self.assert_(leg.get_texts()[3].get_text() == 'D')
  678. self.assert_(ax.right_ax.get_legend() is None)
  679. colors = set()
  680. for line in leg.get_lines():
  681. colors.add(line.get_color())
  682. # TODO: color cycle problems
  683. self.assert_(len(colors) == 4)
  684. plt.clf()
  685. ax = fig.add_subplot(211)
  686. ax = df.plot(secondary_y=['A', 'C'], mark_right=False)
  687. leg = ax.get_legend()
  688. self.assert_(len(leg.get_lines()) == 4)
  689. self.assert_(leg.get_texts()[0].get_text() == 'A')
  690. self.assert_(leg.get_texts()[1].get_text() == 'B')
  691. self.assert_(leg.get_texts()[2].get_text() == 'C')
  692. self.assert_(leg.get_texts()[3].get_text() == 'D')
  693. plt.clf()
  694. ax = fig.add_subplot(211)
  695. df = tm.makeTimeDataFrame()
  696. ax = df.plot(secondary_y=['C', 'D'])
  697. leg = ax.get_legend()
  698. self.assert_(len(leg.get_lines()) == 4)
  699. self.assert_(ax.right_ax.get_legend() is None)
  700. colors = set()
  701. for line in leg.get_lines():
  702. colors.add(line.get_color())
  703. # TODO: color cycle problems
  704. self.assert_(len(colors) == 4)
  705. #non-ts
  706. df = tm.makeDataFrame()
  707. plt.clf()
  708. ax = fig.add_subplot(211)
  709. ax = df.plot(secondary_y=['A', 'B'])
  710. leg = ax.get_legend()
  711. self.assert_(len(leg.get_lines()) == 4)
  712. self.assert_(ax.right_ax.get_legend() is None)
  713. colors = set()
  714. for line in leg.get_lines():
  715. colors.add(line.get_color())
  716. # TODO: color cycle problems
  717. self.assert_(len(colors) == 4)
  718. plt.clf()
  719. ax = fig.add_subplot(211)
  720. ax = df.plot(secondary_y=['C', 'D'])
  721. leg = ax.get_legend()
  722. self.assert_(len(leg.get_lines()) == 4)
  723. self.assert_(ax.right_ax.get_legend() is None)
  724. colors = set()
  725. for line in leg.get_lines():
  726. colors.add(line.get_color())
  727. # TODO: color cycle problems
  728. self.assert_(len(colors) == 4)
  729. @slow
  730. def test_format_date_axis(self):
  731. rng = date_range('1/1/2012', periods=12, freq='M')
  732. df = DataFrame(np.random.randn(len(rng), 3), rng)
  733. ax = df.plot()
  734. xaxis = ax.get_xaxis()
  735. for l in xaxis.get_ticklabels():
  736. if len(l.get_text()) > 0:
  737. self.assert_(l.get_rotation() == 30)
  738. PNG_PATH = 'tmp.png'
  739. def _check_plot_works(f, freq=None, series=None, *args, **kwargs):
  740. import matplotlib.pyplot as plt
  741. fig = plt.gcf()
  742. plt.clf()
  743. ax = fig.add_subplot(211)
  744. orig_ax = kwargs.pop('ax', plt.gca())
  745. orig_axfreq = getattr(orig_ax, 'freq', None)
  746. ret = f(*args, **kwargs)
  747. assert(ret is not None) # do something more intelligent
  748. ax = kwargs.pop('ax', plt.gca())
  749. if series is not None:
  750. dfreq = series.index.freq
  751. if isinstance(dfreq, DateOffset):
  752. dfreq = dfreq.rule_code
  753. if orig_axfreq is None:
  754. assert(ax.freq == dfreq)
  755. if freq is not None and orig_axfreq is None:
  756. assert(ax.freq == freq)
  757. ax = fig.add_subplot(212)
  758. try:
  759. kwargs['ax'] = ax
  760. ret = f(*args, **kwargs)
  761. assert(ret is not None) # do something more intelligent
  762. except Exception:
  763. pass
  764. plt.savefig(PNG_PATH)
  765. os.remove(PNG_PATH)
  766. if __name__ == '__main__':
  767. nose.runmodule(argv=[__file__,'-vvs','-x','--pdb', '--pdb-failure'],
  768. exit=False)