PageRenderTime 70ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 1ms

/pandas/tseries/tests/test_plotting.py

https://github.com/kljensen/pandas
Python | 915 lines | 779 code | 118 blank | 18 comment | 58 complexity | 68c8953a746b9256bac152b9f7d6ae1e 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. import matplotlib.pyplot as plt
  242. plt.close('all')
  243. ser = tm.makeTimeSeries()
  244. ax = ser.plot()
  245. _test(ax)
  246. df = DataFrame({'a' : ser, 'b' : ser + 1})
  247. ax = df.plot()
  248. _test(ax)
  249. df = DataFrame({'a' : ser, 'b' : ser + 1})
  250. axes = df.plot(subplots=True)
  251. [_test(ax) for ax in axes]
  252. def test_get_finder(self):
  253. import pandas.tseries.converter as conv
  254. self.assertEqual(conv.get_finder('B'), conv._daily_finder)
  255. self.assertEqual(conv.get_finder('D'), conv._daily_finder)
  256. self.assertEqual(conv.get_finder('M'), conv._monthly_finder)
  257. self.assertEqual(conv.get_finder('Q'), conv._quarterly_finder)
  258. self.assertEqual(conv.get_finder('A'), conv._annual_finder)
  259. self.assertEqual(conv.get_finder('W'), conv._daily_finder)
  260. @slow
  261. def test_finder_daily(self):
  262. xp = Period('1999-1-1', freq='B').ordinal
  263. day_lst = [10, 40, 252, 400, 950, 2750, 10000]
  264. for n in day_lst:
  265. rng = bdate_range('1999-1-1', periods=n)
  266. ser = Series(np.random.randn(len(rng)), rng)
  267. ax = ser.plot()
  268. xaxis = ax.get_xaxis()
  269. rs = xaxis.get_majorticklocs()[0]
  270. self.assertEqual(xp, rs)
  271. (vmin, vmax) = ax.get_xlim()
  272. ax.set_xlim(vmin + 0.9, vmax)
  273. rs = xaxis.get_majorticklocs()[0]
  274. self.assertEqual(xp, rs)
  275. @slow
  276. def test_finder_quarterly(self):
  277. import matplotlib.pyplot as plt
  278. xp = Period('1988Q1').ordinal
  279. yrs = [3.5, 11]
  280. plt.close('all')
  281. for n in yrs:
  282. rng = period_range('1987Q2', periods=int(n * 4), freq='Q')
  283. ser = Series(np.random.randn(len(rng)), rng)
  284. ax = ser.plot()
  285. xaxis = ax.get_xaxis()
  286. rs = xaxis.get_majorticklocs()[0]
  287. self.assert_(rs == xp)
  288. (vmin, vmax) = ax.get_xlim()
  289. ax.set_xlim(vmin + 0.9, vmax)
  290. rs = xaxis.get_majorticklocs()[0]
  291. self.assertEqual(xp, rs)
  292. @slow
  293. def test_finder_monthly(self):
  294. import matplotlib.pyplot as plt
  295. xp = Period('Jan 1988').ordinal
  296. yrs = [1.15, 2.5, 4, 11]
  297. plt.close('all')
  298. for n in yrs:
  299. rng = period_range('1987Q2', periods=int(n * 12), freq='M')
  300. ser = Series(np.random.randn(len(rng)), rng)
  301. ax = ser.plot()
  302. xaxis = ax.get_xaxis()
  303. rs = xaxis.get_majorticklocs()[0]
  304. self.assert_(rs == xp)
  305. (vmin, vmax) = ax.get_xlim()
  306. ax.set_xlim(vmin + 0.9, vmax)
  307. rs = xaxis.get_majorticklocs()[0]
  308. self.assertEqual(xp, rs)
  309. plt.close('all')
  310. @slow
  311. def test_finder_monthly_long(self):
  312. import matplotlib.pyplot as plt
  313. plt.close('all')
  314. rng = period_range('1988Q1', periods=24*12, freq='M')
  315. ser = Series(np.random.randn(len(rng)), rng)
  316. ax = ser.plot()
  317. xaxis = ax.get_xaxis()
  318. rs = xaxis.get_majorticklocs()[0]
  319. xp = Period('1989Q1', 'M').ordinal
  320. self.assert_(rs == xp)
  321. @slow
  322. def test_finder_annual(self):
  323. import matplotlib.pyplot as plt
  324. plt.close('all')
  325. xp = [1987, 1988, 1990, 1990, 1995, 2020, 2070, 2170]
  326. for i, nyears in enumerate([5, 10, 19, 49, 99, 199, 599, 1001]):
  327. rng = period_range('1987', periods=nyears, freq='A')
  328. ser = Series(np.random.randn(len(rng)), rng)
  329. ax = ser.plot()
  330. xaxis = ax.get_xaxis()
  331. rs = xaxis.get_majorticklocs()[0]
  332. self.assert_(rs == Period(xp[i], freq='A').ordinal)
  333. plt.close('all')
  334. @slow
  335. def test_finder_minutely(self):
  336. import matplotlib.pyplot as plt
  337. plt.close('all')
  338. nminutes = 50 * 24 * 60
  339. rng = date_range('1/1/1999', freq='Min', periods=nminutes)
  340. ser = Series(np.random.randn(len(rng)), rng)
  341. ax = ser.plot()
  342. xaxis = ax.get_xaxis()
  343. rs = xaxis.get_majorticklocs()[0]
  344. xp = Period('1/1/1999', freq='Min').ordinal
  345. self.assertEqual(rs, xp)
  346. @slow
  347. def test_finder_hourly(self):
  348. import matplotlib.pyplot as plt
  349. plt.close('all')
  350. nhours = 23
  351. rng = date_range('1/1/1999', freq='H', periods=nhours)
  352. ser = Series(np.random.randn(len(rng)), rng)
  353. ax = ser.plot()
  354. xaxis = ax.get_xaxis()
  355. rs = xaxis.get_majorticklocs()[0]
  356. xp = Period('1/1/1999', freq='H').ordinal
  357. self.assertEqual(rs, xp)
  358. @slow
  359. def test_gaps(self):
  360. import matplotlib.pyplot as plt
  361. plt.close('all')
  362. ts = tm.makeTimeSeries()
  363. ts[5:25] = np.nan
  364. ax = ts.plot()
  365. lines = ax.get_lines()
  366. self.assert_(len(lines) == 1)
  367. l = lines[0]
  368. data = l.get_xydata()
  369. self.assert_(isinstance(data, np.ma.core.MaskedArray))
  370. mask = data.mask
  371. self.assert_(mask[5:25, 1].all())
  372. # irregular
  373. plt.close('all')
  374. ts = tm.makeTimeSeries()
  375. ts = ts[[0, 1, 2, 5, 7, 9, 12, 15, 20]]
  376. ts[2:5] = np.nan
  377. ax = ts.plot()
  378. lines = ax.get_lines()
  379. self.assert_(len(lines) == 1)
  380. l = lines[0]
  381. data = l.get_xydata()
  382. self.assert_(isinstance(data, np.ma.core.MaskedArray))
  383. mask = data.mask
  384. self.assert_(mask[2:5, 1].all())
  385. # non-ts
  386. plt.close('all')
  387. idx = [0, 1, 2, 5, 7, 9, 12, 15, 20]
  388. ser = Series(np.random.randn(len(idx)), idx)
  389. ser[2:5] = np.nan
  390. ax = ser.plot()
  391. lines = ax.get_lines()
  392. self.assert_(len(lines) == 1)
  393. l = lines[0]
  394. data = l.get_xydata()
  395. self.assert_(isinstance(data, np.ma.core.MaskedArray))
  396. mask = data.mask
  397. self.assert_(mask[2:5, 1].all())
  398. @slow
  399. def test_gap_upsample(self):
  400. import matplotlib.pyplot as plt
  401. plt.close('all')
  402. low = tm.makeTimeSeries()
  403. low[5:25] = np.nan
  404. ax = low.plot()
  405. idxh = date_range(low.index[0], low.index[-1], freq='12h')
  406. s = Series(np.random.randn(len(idxh)), idxh)
  407. s.plot(secondary_y=True)
  408. lines = ax.get_lines()
  409. self.assert_(len(lines) == 1)
  410. self.assert_(len(ax.right_ax.get_lines()) == 1)
  411. l = lines[0]
  412. data = l.get_xydata()
  413. self.assert_(isinstance(data, np.ma.core.MaskedArray))
  414. mask = data.mask
  415. self.assert_(mask[5:25, 1].all())
  416. @slow
  417. def test_secondary_y(self):
  418. import matplotlib.pyplot as plt
  419. plt.close('all')
  420. ser = Series(np.random.randn(10))
  421. ser2 = Series(np.random.randn(10))
  422. ax = ser.plot(secondary_y=True).right_ax
  423. fig = ax.get_figure()
  424. axes = fig.get_axes()
  425. l = ax.get_lines()[0]
  426. xp = Series(l.get_ydata(), l.get_xdata())
  427. assert_series_equal(ser, xp)
  428. self.assert_(ax.get_yaxis().get_ticks_position() == 'right')
  429. self.assert_(not axes[0].get_yaxis().get_visible())
  430. ax2 = ser2.plot()
  431. self.assert_(ax2.get_yaxis().get_ticks_position() == 'left')
  432. plt.close('all')
  433. ax = ser2.plot()
  434. ax2 = ser.plot(secondary_y=True).right_ax
  435. self.assert_(ax.get_yaxis().get_visible())
  436. plt.close('all')
  437. @slow
  438. def test_secondary_y_ts(self):
  439. import matplotlib.pyplot as plt
  440. plt.close('all')
  441. idx = date_range('1/1/2000', periods=10)
  442. ser = Series(np.random.randn(10), idx)
  443. ser2 = Series(np.random.randn(10), idx)
  444. ax = ser.plot(secondary_y=True).right_ax
  445. fig = ax.get_figure()
  446. axes = fig.get_axes()
  447. l = ax.get_lines()[0]
  448. xp = Series(l.get_ydata(), l.get_xdata()).to_timestamp()
  449. assert_series_equal(ser, xp)
  450. self.assert_(ax.get_yaxis().get_ticks_position() == 'right')
  451. self.assert_(not axes[0].get_yaxis().get_visible())
  452. ax2 = ser2.plot()
  453. self.assert_(ax2.get_yaxis().get_ticks_position() == 'left')
  454. plt.close('all')
  455. ax = ser2.plot()
  456. ax2 = ser.plot(secondary_y=True)
  457. self.assert_(ax.get_yaxis().get_visible())
  458. @slow
  459. def test_secondary_kde(self):
  460. import matplotlib.pyplot as plt
  461. plt.close('all')
  462. ser = Series(np.random.randn(10))
  463. ax = ser.plot(secondary_y=True, kind='density').right_ax
  464. fig = ax.get_figure()
  465. axes = fig.get_axes()
  466. self.assert_(axes[1].get_yaxis().get_ticks_position() == 'right')
  467. @slow
  468. def test_secondary_bar(self):
  469. import matplotlib.pyplot as plt
  470. plt.close('all')
  471. ser = Series(np.random.randn(10))
  472. ax = ser.plot(secondary_y=True, kind='bar')
  473. fig = ax.get_figure()
  474. axes = fig.get_axes()
  475. self.assert_(axes[1].get_yaxis().get_ticks_position() == 'right')
  476. @slow
  477. def test_secondary_frame(self):
  478. import matplotlib.pyplot as plt
  479. plt.close('all')
  480. df = DataFrame(np.random.randn(5, 3), columns=['a', 'b', 'c'])
  481. axes = df.plot(secondary_y=['a', 'c'], subplots=True)
  482. self.assert_(axes[0].get_yaxis().get_ticks_position() == 'right')
  483. self.assert_(axes[1].get_yaxis().get_ticks_position() == 'default')
  484. self.assert_(axes[2].get_yaxis().get_ticks_position() == 'right')
  485. @slow
  486. def test_mixed_freq_regular_first(self):
  487. import matplotlib.pyplot as plt
  488. plt.close('all')
  489. s1 = tm.makeTimeSeries()
  490. s2 = s1[[0, 5, 10, 11, 12, 13, 14, 15]]
  491. s1.plot()
  492. ax2 = s2.plot(style='g')
  493. lines = ax2.get_lines()
  494. idx1 = lines[0].get_xdata()
  495. idx2 = lines[1].get_xdata()
  496. self.assert_(idx1.equals(s1.index.to_period('B')))
  497. self.assert_(idx2.equals(s2.index.to_period('B')))
  498. left, right = ax2.get_xlim()
  499. pidx = s1.index.to_period()
  500. self.assert_(left == pidx[0].ordinal)
  501. self.assert_(right == pidx[-1].ordinal)
  502. plt.close('all')
  503. @slow
  504. def test_mixed_freq_irregular_first(self):
  505. import matplotlib.pyplot as plt
  506. plt.close('all')
  507. s1 = tm.makeTimeSeries()
  508. s2 = s1[[0, 5, 10, 11, 12, 13, 14, 15]]
  509. s2.plot(style='g')
  510. ax = s1.plot()
  511. self.assert_(not hasattr(ax, 'freq'))
  512. lines = ax.get_lines()
  513. x1 = lines[0].get_xdata()
  514. assert_array_equal(x1, s2.index.asobject.values)
  515. x2 = lines[1].get_xdata()
  516. assert_array_equal(x2, s1.index.asobject.values)
  517. plt.close('all')
  518. @slow
  519. def test_mixed_freq_hf_first(self):
  520. import matplotlib.pyplot as plt
  521. plt.close('all')
  522. idxh = date_range('1/1/1999', periods=365, freq='D')
  523. idxl = date_range('1/1/1999', periods=12, freq='M')
  524. high = Series(np.random.randn(len(idxh)), idxh)
  525. low = Series(np.random.randn(len(idxl)), idxl)
  526. high.plot()
  527. ax = low.plot()
  528. for l in ax.get_lines():
  529. self.assert_(l.get_xdata().freq == 'D')
  530. @slow
  531. def test_mixed_freq_lf_first(self):
  532. import matplotlib.pyplot as plt
  533. plt.close('all')
  534. idxh = date_range('1/1/1999', periods=365, freq='D')
  535. idxl = date_range('1/1/1999', periods=12, freq='M')
  536. high = Series(np.random.randn(len(idxh)), idxh)
  537. low = Series(np.random.randn(len(idxl)), idxl)
  538. low.plot()
  539. ax = high.plot()
  540. for l in ax.get_lines():
  541. self.assert_(l.get_xdata().freq == 'D')
  542. plt.close('all')
  543. idxh = date_range('1/1/1999', periods=240, freq='T')
  544. idxl = date_range('1/1/1999', periods=4, freq='H')
  545. high = Series(np.random.randn(len(idxh)), idxh)
  546. low = Series(np.random.randn(len(idxl)), idxl)
  547. low.plot()
  548. ax = high.plot()
  549. for l in ax.get_lines():
  550. self.assert_(l.get_xdata().freq == 'T')
  551. @slow
  552. def test_mixed_freq_irreg_period(self):
  553. ts = tm.makeTimeSeries()
  554. irreg = ts[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 18, 29]]
  555. rng = period_range('1/3/2000', periods=30, freq='B')
  556. ps = Series(np.random.randn(len(rng)), rng)
  557. irreg.plot()
  558. ps.plot()
  559. @slow
  560. def test_to_weekly_resampling(self):
  561. import matplotlib.pyplot as plt
  562. plt.close('all')
  563. idxh = date_range('1/1/1999', periods=52, freq='W')
  564. idxl = date_range('1/1/1999', periods=12, freq='M')
  565. high = Series(np.random.randn(len(idxh)), idxh)
  566. low = Series(np.random.randn(len(idxl)), idxl)
  567. high.plot()
  568. ax = low.plot()
  569. for l in ax.get_lines():
  570. self.assert_(l.get_xdata().freq.startswith('W'))
  571. @slow
  572. def test_from_weekly_resampling(self):
  573. import matplotlib.pyplot as plt
  574. plt.close('all')
  575. idxh = date_range('1/1/1999', periods=52, freq='W')
  576. idxl = date_range('1/1/1999', periods=12, freq='M')
  577. high = Series(np.random.randn(len(idxh)), idxh)
  578. low = Series(np.random.randn(len(idxl)), idxl)
  579. low.plot()
  580. ax = high.plot()
  581. for l in ax.get_lines():
  582. self.assert_(l.get_xdata().freq.startswith('W'))
  583. @slow
  584. def test_irreg_dtypes(self):
  585. import matplotlib.pyplot as plt
  586. #date
  587. idx = [date(2000, 1, 1), date(2000, 1, 5), date(2000, 1, 20)]
  588. df = DataFrame(np.random.randn(len(idx), 3), Index(idx, dtype=object))
  589. _check_plot_works(df.plot)
  590. #np.datetime64
  591. idx = date_range('1/1/2000', periods=10)
  592. idx = idx[[0, 2, 5, 9]].asobject
  593. df = DataFrame(np.random.randn(len(idx), 3), idx)
  594. _check_plot_works(df.plot)
  595. @slow
  596. def test_time(self):
  597. import matplotlib.pyplot as plt
  598. plt.close('all')
  599. t = datetime(1, 1, 1, 3, 30, 0)
  600. deltas = np.random.randint(1, 20, 3).cumsum()
  601. ts = np.array([(t + timedelta(minutes=int(x))).time() for x in deltas])
  602. df = DataFrame({'a' : np.random.randn(len(ts)),
  603. 'b' : np.random.randn(len(ts))},
  604. index=ts)
  605. ax = df.plot()
  606. # verify tick labels
  607. ticks = ax.get_xticks()
  608. labels = ax.get_xticklabels()
  609. for t, l in zip(ticks, labels):
  610. m, s = divmod(int(t), 60)
  611. h, m = divmod(m, 60)
  612. xp = l.get_text()
  613. if len(xp) > 0:
  614. rs = time(h, m, s).strftime('%H:%M:%S')
  615. self.assert_(xp, rs)
  616. # change xlim
  617. ax.set_xlim('1:30', '5:00')
  618. # check tick labels again
  619. ticks = ax.get_xticks()
  620. labels = ax.get_xticklabels()
  621. for t, l in zip(ticks, labels):
  622. m, s = divmod(int(t), 60)
  623. h, m = divmod(m, 60)
  624. xp = l.get_text()
  625. if len(xp) > 0:
  626. rs = time(h, m, s).strftime('%H:%M:%S')
  627. self.assert_(xp, rs)
  628. @slow
  629. def test_time_musec(self):
  630. import matplotlib.pyplot as plt
  631. plt.close('all')
  632. t = datetime(1, 1, 1, 3, 30, 0)
  633. deltas = np.random.randint(1, 20, 3).cumsum()
  634. ts = np.array([(t + timedelta(microseconds=int(x))).time()
  635. for x in deltas])
  636. df = DataFrame({'a' : np.random.randn(len(ts)),
  637. 'b' : np.random.randn(len(ts))},
  638. index=ts)
  639. ax = df.plot()
  640. # verify tick labels
  641. ticks = ax.get_xticks()
  642. labels = ax.get_xticklabels()
  643. for t, l in zip(ticks, labels):
  644. m, s = divmod(int(t), 60)
  645. us = int((t - int(t)) * 1e6)
  646. h, m = divmod(m, 60)
  647. xp = l.get_text()
  648. if len(xp) > 0:
  649. rs = time(h, m, s).strftime('%H:%M:%S.%f')
  650. self.assert_(xp, rs)
  651. @slow
  652. def test_secondary_upsample(self):
  653. import matplotlib.pyplot as plt
  654. plt.close('all')
  655. idxh = date_range('1/1/1999', periods=365, freq='D')
  656. idxl = date_range('1/1/1999', periods=12, freq='M')
  657. high = Series(np.random.randn(len(idxh)), idxh)
  658. low = Series(np.random.randn(len(idxl)), idxl)
  659. low.plot()
  660. ax = high.plot(secondary_y=True)
  661. for l in ax.get_lines():
  662. self.assert_(l.get_xdata().freq == 'D')
  663. for l in ax.right_ax.get_lines():
  664. self.assert_(l.get_xdata().freq == 'D')
  665. @slow
  666. def test_secondary_legend(self):
  667. import matplotlib.pyplot as plt
  668. fig = plt.gcf()
  669. plt.clf()
  670. ax = fig.add_subplot(211)
  671. #ts
  672. df = tm.makeTimeDataFrame()
  673. ax = df.plot(secondary_y=['A', 'B'])
  674. leg = ax.get_legend()
  675. self.assert_(len(leg.get_lines()) == 4)
  676. self.assert_(leg.get_texts()[0].get_text() == 'A (right)')
  677. self.assert_(leg.get_texts()[1].get_text() == 'B (right)')
  678. self.assert_(leg.get_texts()[2].get_text() == 'C')
  679. self.assert_(leg.get_texts()[3].get_text() == 'D')
  680. self.assert_(ax.right_ax.get_legend() is None)
  681. colors = set()
  682. for line in leg.get_lines():
  683. colors.add(line.get_color())
  684. # TODO: color cycle problems
  685. self.assert_(len(colors) == 4)
  686. plt.clf()
  687. ax = fig.add_subplot(211)
  688. ax = df.plot(secondary_y=['A', 'C'], mark_right=False)
  689. leg = ax.get_legend()
  690. self.assert_(len(leg.get_lines()) == 4)
  691. self.assert_(leg.get_texts()[0].get_text() == 'A')
  692. self.assert_(leg.get_texts()[1].get_text() == 'B')
  693. self.assert_(leg.get_texts()[2].get_text() == 'C')
  694. self.assert_(leg.get_texts()[3].get_text() == 'D')
  695. plt.clf()
  696. ax = fig.add_subplot(211)
  697. df = tm.makeTimeDataFrame()
  698. ax = df.plot(secondary_y=['C', 'D'])
  699. leg = ax.get_legend()
  700. self.assert_(len(leg.get_lines()) == 4)
  701. self.assert_(ax.right_ax.get_legend() is None)
  702. colors = set()
  703. for line in leg.get_lines():
  704. colors.add(line.get_color())
  705. # TODO: color cycle problems
  706. self.assert_(len(colors) == 4)
  707. #non-ts
  708. df = tm.makeDataFrame()
  709. plt.clf()
  710. ax = fig.add_subplot(211)
  711. ax = df.plot(secondary_y=['A', 'B'])
  712. leg = ax.get_legend()
  713. self.assert_(len(leg.get_lines()) == 4)
  714. self.assert_(ax.right_ax.get_legend() is None)
  715. colors = set()
  716. for line in leg.get_lines():
  717. colors.add(line.get_color())
  718. # TODO: color cycle problems
  719. self.assert_(len(colors) == 4)
  720. plt.clf()
  721. ax = fig.add_subplot(211)
  722. ax = df.plot(secondary_y=['C', 'D'])
  723. leg = ax.get_legend()
  724. self.assert_(len(leg.get_lines()) == 4)
  725. self.assert_(ax.right_ax.get_legend() is None)
  726. colors = set()
  727. for line in leg.get_lines():
  728. colors.add(line.get_color())
  729. # TODO: color cycle problems
  730. self.assert_(len(colors) == 4)
  731. @slow
  732. def test_format_date_axis(self):
  733. rng = date_range('1/1/2012', periods=12, freq='M')
  734. df = DataFrame(np.random.randn(len(rng), 3), rng)
  735. ax = df.plot()
  736. xaxis = ax.get_xaxis()
  737. for l in xaxis.get_ticklabels():
  738. if len(l.get_text()) > 0:
  739. self.assert_(l.get_rotation() == 30)
  740. @slow
  741. def test_ax_plot(self):
  742. x = DatetimeIndex(start='2012-01-02', periods=10,
  743. freq='D')
  744. y = range(len(x))
  745. import matplotlib.pyplot as plt
  746. fig = plt.figure()
  747. ax = fig.add_subplot(111)
  748. lines = ax.plot(x, y, label='Y')
  749. assert_array_equal(DatetimeIndex(lines[0].get_xdata()), x)
  750. @slow
  751. def test_mpl_nopandas(self):
  752. import matplotlib.pyplot as plt
  753. dates = [date(2008, 12, 31), date(2009, 1, 31)]
  754. values1 = np.arange(10.0, 11.0, 0.5)
  755. values2 = np.arange(11.0, 12.0, 0.5)
  756. kw = dict(fmt='-', lw=4)
  757. plt.close('all')
  758. fig = plt.figure()
  759. ax = fig.add_subplot(111)
  760. ax.plot_date([x.toordinal() for x in dates], values1, **kw)
  761. ax.plot_date([x.toordinal() for x in dates], values2, **kw)
  762. line1, line2 = ax.get_lines()
  763. assert_array_equal(np.array([x.toordinal() for x in dates]),
  764. line1.get_xydata()[:, 0])
  765. assert_array_equal(np.array([x.toordinal() for x in dates]),
  766. line2.get_xydata()[:, 0])
  767. PNG_PATH = 'tmp.png'
  768. def _check_plot_works(f, freq=None, series=None, *args, **kwargs):
  769. import matplotlib.pyplot as plt
  770. fig = plt.gcf()
  771. plt.clf()
  772. ax = fig.add_subplot(211)
  773. orig_ax = kwargs.pop('ax', plt.gca())
  774. orig_axfreq = getattr(orig_ax, 'freq', None)
  775. ret = f(*args, **kwargs)
  776. assert(ret is not None) # do something more intelligent
  777. ax = kwargs.pop('ax', plt.gca())
  778. if series is not None:
  779. dfreq = series.index.freq
  780. if isinstance(dfreq, DateOffset):
  781. dfreq = dfreq.rule_code
  782. if orig_axfreq is None:
  783. assert(ax.freq == dfreq)
  784. if freq is not None and orig_axfreq is None:
  785. assert(ax.freq == freq)
  786. ax = fig.add_subplot(212)
  787. try:
  788. kwargs['ax'] = ax
  789. ret = f(*args, **kwargs)
  790. assert(ret is not None) # do something more intelligent
  791. except Exception:
  792. pass
  793. plt.savefig(PNG_PATH)
  794. os.remove(PNG_PATH)
  795. if __name__ == '__main__':
  796. nose.runmodule(argv=[__file__,'-vvs','-x','--pdb', '--pdb-failure'],
  797. exit=False)