PageRenderTime 48ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/pandas/tseries/tests/test_plotting.py

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