test_subplots.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import itertools
  2. import platform
  3. import numpy as np
  4. import pytest
  5. import matplotlib as mpl
  6. from matplotlib.axes import Axes, SubplotBase
  7. import matplotlib.pyplot as plt
  8. from matplotlib.testing.decorators import check_figures_equal, image_comparison
  9. def check_shared(axs, x_shared, y_shared):
  10. """
  11. x_shared and y_shared are n x n boolean matrices; entry (i, j) indicates
  12. whether the x (or y) axes of subplots i and j should be shared.
  13. """
  14. for (i1, ax1), (i2, ax2), (i3, (name, shared)) in itertools.product(
  15. enumerate(axs),
  16. enumerate(axs),
  17. enumerate(zip("xy", [x_shared, y_shared]))):
  18. if i2 <= i1:
  19. continue
  20. assert axs[0]._shared_axes[name].joined(ax1, ax2) == shared[i1, i2], \
  21. "axes %i and %i incorrectly %ssharing %s axis" % (
  22. i1, i2, "not " if shared[i1, i2] else "", name)
  23. def check_ticklabel_visible(axs, x_visible, y_visible):
  24. """Check that the x and y ticklabel visibility is as specified."""
  25. for i, (ax, vx, vy) in enumerate(zip(axs, x_visible, y_visible)):
  26. for l in ax.get_xticklabels() + [ax.xaxis.offsetText]:
  27. assert l.get_visible() == vx, \
  28. f"Visibility of x axis #{i} is incorrectly {vx}"
  29. for l in ax.get_yticklabels() + [ax.yaxis.offsetText]:
  30. assert l.get_visible() == vy, \
  31. f"Visibility of y axis #{i} is incorrectly {vy}"
  32. # axis label "visibility" is toggled by label_outer by resetting the
  33. # label to empty, but it can also be empty to start with.
  34. if not vx:
  35. assert ax.get_xlabel() == ""
  36. if not vy:
  37. assert ax.get_ylabel() == ""
  38. def check_tick1_visible(axs, x_visible, y_visible):
  39. """
  40. Check that the x and y tick visibility is as specified.
  41. Note: This only checks the tick1line, i.e. bottom / left ticks.
  42. """
  43. for ax, visible, in zip(axs, x_visible):
  44. for tick in ax.xaxis.get_major_ticks():
  45. assert tick.tick1line.get_visible() == visible
  46. for ax, y_visible, in zip(axs, y_visible):
  47. for tick in ax.yaxis.get_major_ticks():
  48. assert tick.tick1line.get_visible() == visible
  49. def test_shared():
  50. rdim = (4, 4, 2)
  51. share = {
  52. 'all': np.ones(rdim[:2], dtype=bool),
  53. 'none': np.zeros(rdim[:2], dtype=bool),
  54. 'row': np.array([
  55. [False, True, False, False],
  56. [True, False, False, False],
  57. [False, False, False, True],
  58. [False, False, True, False]]),
  59. 'col': np.array([
  60. [False, False, True, False],
  61. [False, False, False, True],
  62. [True, False, False, False],
  63. [False, True, False, False]]),
  64. }
  65. visible = {
  66. 'x': {
  67. 'all': [False, False, True, True],
  68. 'col': [False, False, True, True],
  69. 'row': [True] * 4,
  70. 'none': [True] * 4,
  71. False: [True] * 4,
  72. True: [False, False, True, True],
  73. },
  74. 'y': {
  75. 'all': [True, False, True, False],
  76. 'col': [True] * 4,
  77. 'row': [True, False, True, False],
  78. 'none': [True] * 4,
  79. False: [True] * 4,
  80. True: [True, False, True, False],
  81. },
  82. }
  83. share[False] = share['none']
  84. share[True] = share['all']
  85. # test default
  86. f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2)
  87. axs = [a1, a2, a3, a4]
  88. check_shared(axs, share['none'], share['none'])
  89. plt.close(f)
  90. # test all option combinations
  91. ops = [False, True, 'all', 'none', 'row', 'col', 0, 1]
  92. for xo in ops:
  93. for yo in ops:
  94. f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2, sharex=xo, sharey=yo)
  95. axs = [a1, a2, a3, a4]
  96. check_shared(axs, share[xo], share[yo])
  97. check_ticklabel_visible(axs, visible['x'][xo], visible['y'][yo])
  98. plt.close(f)
  99. @pytest.mark.parametrize('remove_ticks', [True, False])
  100. @pytest.mark.parametrize('layout_engine', ['none', 'tight', 'constrained'])
  101. @pytest.mark.parametrize('with_colorbar', [True, False])
  102. def test_label_outer(remove_ticks, layout_engine, with_colorbar):
  103. fig = plt.figure(layout=layout_engine)
  104. axs = fig.subplots(2, 2, sharex=True, sharey=True)
  105. for ax in axs.flat:
  106. ax.set(xlabel="foo", ylabel="bar")
  107. if with_colorbar:
  108. fig.colorbar(mpl.cm.ScalarMappable(), ax=ax)
  109. ax.label_outer(remove_inner_ticks=remove_ticks)
  110. check_ticklabel_visible(
  111. axs.flat, [False, False, True, True], [True, False, True, False])
  112. if remove_ticks:
  113. check_tick1_visible(
  114. axs.flat, [False, False, True, True], [True, False, True, False])
  115. else:
  116. check_tick1_visible(
  117. axs.flat, [True, True, True, True], [True, True, True, True])
  118. def test_label_outer_span():
  119. fig = plt.figure()
  120. gs = fig.add_gridspec(3, 3)
  121. # +---+---+---+
  122. # | 1 | |
  123. # +---+---+---+
  124. # | | | 3 |
  125. # + 2 +---+---+
  126. # | | 4 | |
  127. # +---+---+---+
  128. a1 = fig.add_subplot(gs[0, 0:2])
  129. a2 = fig.add_subplot(gs[1:3, 0])
  130. a3 = fig.add_subplot(gs[1, 2])
  131. a4 = fig.add_subplot(gs[2, 1])
  132. for ax in fig.axes:
  133. ax.label_outer()
  134. check_ticklabel_visible(
  135. fig.axes, [False, True, False, True], [True, True, False, False])
  136. def test_label_outer_non_gridspec():
  137. ax = plt.axes((0, 0, 1, 1))
  138. ax.label_outer() # Does nothing.
  139. check_ticklabel_visible([ax], [True], [True])
  140. def test_shared_and_moved():
  141. # test if sharey is on, but then tick_left is called that labels don't
  142. # re-appear. Seaborn does this just to be sure yaxis is on left...
  143. f, (a1, a2) = plt.subplots(1, 2, sharey=True)
  144. check_ticklabel_visible([a2], [True], [False])
  145. a2.yaxis.tick_left()
  146. check_ticklabel_visible([a2], [True], [False])
  147. f, (a1, a2) = plt.subplots(2, 1, sharex=True)
  148. check_ticklabel_visible([a1], [False], [True])
  149. a2.xaxis.tick_bottom()
  150. check_ticklabel_visible([a1], [False], [True])
  151. def test_exceptions():
  152. # TODO should this test more options?
  153. with pytest.raises(ValueError):
  154. plt.subplots(2, 2, sharex='blah')
  155. with pytest.raises(ValueError):
  156. plt.subplots(2, 2, sharey='blah')
  157. @image_comparison(['subplots_offset_text.png'],
  158. tol=0 if platform.machine() == 'x86_64' else 0.028)
  159. def test_subplots_offsettext():
  160. x = np.arange(0, 1e10, 1e9)
  161. y = np.arange(0, 100, 10)+1e4
  162. fig, axs = plt.subplots(2, 2, sharex='col', sharey='all')
  163. axs[0, 0].plot(x, x)
  164. axs[1, 0].plot(x, x)
  165. axs[0, 1].plot(y, x)
  166. axs[1, 1].plot(y, x)
  167. @pytest.mark.parametrize("top", [True, False])
  168. @pytest.mark.parametrize("bottom", [True, False])
  169. @pytest.mark.parametrize("left", [True, False])
  170. @pytest.mark.parametrize("right", [True, False])
  171. def test_subplots_hide_ticklabels(top, bottom, left, right):
  172. # Ideally, we would also test offset-text visibility (and remove
  173. # test_subplots_offsettext), but currently, setting rcParams fails to move
  174. # the offset texts as well.
  175. with plt.rc_context({"xtick.labeltop": top, "xtick.labelbottom": bottom,
  176. "ytick.labelleft": left, "ytick.labelright": right}):
  177. axs = plt.figure().subplots(3, 3, sharex=True, sharey=True)
  178. for (i, j), ax in np.ndenumerate(axs):
  179. xtop = ax.xaxis._major_tick_kw["label2On"]
  180. xbottom = ax.xaxis._major_tick_kw["label1On"]
  181. yleft = ax.yaxis._major_tick_kw["label1On"]
  182. yright = ax.yaxis._major_tick_kw["label2On"]
  183. assert xtop == (top and i == 0)
  184. assert xbottom == (bottom and i == 2)
  185. assert yleft == (left and j == 0)
  186. assert yright == (right and j == 2)
  187. @pytest.mark.parametrize("xlabel_position", ["bottom", "top"])
  188. @pytest.mark.parametrize("ylabel_position", ["left", "right"])
  189. def test_subplots_hide_axislabels(xlabel_position, ylabel_position):
  190. axs = plt.figure().subplots(3, 3, sharex=True, sharey=True)
  191. for (i, j), ax in np.ndenumerate(axs):
  192. ax.set(xlabel="foo", ylabel="bar")
  193. ax.xaxis.set_label_position(xlabel_position)
  194. ax.yaxis.set_label_position(ylabel_position)
  195. ax.label_outer()
  196. assert bool(ax.get_xlabel()) == (
  197. xlabel_position == "bottom" and i == 2
  198. or xlabel_position == "top" and i == 0)
  199. assert bool(ax.get_ylabel()) == (
  200. ylabel_position == "left" and j == 0
  201. or ylabel_position == "right" and j == 2)
  202. def test_get_gridspec():
  203. # ahem, pretty trivial, but...
  204. fig, ax = plt.subplots()
  205. assert ax.get_subplotspec().get_gridspec() == ax.get_gridspec()
  206. def test_dont_mutate_kwargs():
  207. subplot_kw = {'sharex': 'all'}
  208. gridspec_kw = {'width_ratios': [1, 2]}
  209. fig, ax = plt.subplots(1, 2, subplot_kw=subplot_kw,
  210. gridspec_kw=gridspec_kw)
  211. assert subplot_kw == {'sharex': 'all'}
  212. assert gridspec_kw == {'width_ratios': [1, 2]}
  213. @pytest.mark.parametrize("width_ratios", [None, [1, 3, 2]])
  214. @pytest.mark.parametrize("height_ratios", [None, [1, 2]])
  215. @check_figures_equal(extensions=['png'])
  216. def test_width_and_height_ratios(fig_test, fig_ref,
  217. height_ratios, width_ratios):
  218. fig_test.subplots(2, 3, height_ratios=height_ratios,
  219. width_ratios=width_ratios)
  220. fig_ref.subplots(2, 3, gridspec_kw={
  221. 'height_ratios': height_ratios,
  222. 'width_ratios': width_ratios})
  223. @pytest.mark.parametrize("width_ratios", [None, [1, 3, 2]])
  224. @pytest.mark.parametrize("height_ratios", [None, [1, 2]])
  225. @check_figures_equal(extensions=['png'])
  226. def test_width_and_height_ratios_mosaic(fig_test, fig_ref,
  227. height_ratios, width_ratios):
  228. mosaic_spec = [['A', 'B', 'B'], ['A', 'C', 'D']]
  229. fig_test.subplot_mosaic(mosaic_spec, height_ratios=height_ratios,
  230. width_ratios=width_ratios)
  231. fig_ref.subplot_mosaic(mosaic_spec, gridspec_kw={
  232. 'height_ratios': height_ratios,
  233. 'width_ratios': width_ratios})
  234. @pytest.mark.parametrize('method,args', [
  235. ('subplots', (2, 3)),
  236. ('subplot_mosaic', ('abc;def', ))
  237. ]
  238. )
  239. def test_ratio_overlapping_kws(method, args):
  240. with pytest.raises(ValueError, match='height_ratios'):
  241. getattr(plt, method)(*args, height_ratios=[1, 2],
  242. gridspec_kw={'height_ratios': [1, 2]})
  243. with pytest.raises(ValueError, match='width_ratios'):
  244. getattr(plt, method)(*args, width_ratios=[1, 2, 3],
  245. gridspec_kw={'width_ratios': [1, 2, 3]})
  246. def test_old_subplot_compat():
  247. fig = plt.figure()
  248. assert isinstance(fig.add_subplot(), SubplotBase)
  249. assert not isinstance(fig.add_axes(rect=[0, 0, 1, 1]), SubplotBase)
  250. with pytest.raises(TypeError):
  251. Axes(fig, [0, 0, 1, 1], rect=[0, 0, 1, 1])