test_contour.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. import datetime
  2. import platform
  3. import re
  4. from unittest import mock
  5. import contourpy
  6. import numpy as np
  7. from numpy.testing import assert_array_almost_equal, assert_array_almost_equal_nulp
  8. import matplotlib as mpl
  9. from matplotlib import pyplot as plt, rc_context, ticker
  10. from matplotlib.colors import LogNorm, same_color
  11. import matplotlib.patches as mpatches
  12. from matplotlib.testing.decorators import check_figures_equal, image_comparison
  13. import pytest
  14. def test_contour_shape_1d_valid():
  15. x = np.arange(10)
  16. y = np.arange(9)
  17. z = np.random.random((9, 10))
  18. fig, ax = plt.subplots()
  19. ax.contour(x, y, z)
  20. def test_contour_shape_2d_valid():
  21. x = np.arange(10)
  22. y = np.arange(9)
  23. xg, yg = np.meshgrid(x, y)
  24. z = np.random.random((9, 10))
  25. fig, ax = plt.subplots()
  26. ax.contour(xg, yg, z)
  27. @pytest.mark.parametrize("args, message", [
  28. ((np.arange(9), np.arange(9), np.empty((9, 10))),
  29. 'Length of x (9) must match number of columns in z (10)'),
  30. ((np.arange(10), np.arange(10), np.empty((9, 10))),
  31. 'Length of y (10) must match number of rows in z (9)'),
  32. ((np.empty((10, 10)), np.arange(10), np.empty((9, 10))),
  33. 'Number of dimensions of x (2) and y (1) do not match'),
  34. ((np.arange(10), np.empty((10, 10)), np.empty((9, 10))),
  35. 'Number of dimensions of x (1) and y (2) do not match'),
  36. ((np.empty((9, 9)), np.empty((9, 10)), np.empty((9, 10))),
  37. 'Shapes of x (9, 9) and z (9, 10) do not match'),
  38. ((np.empty((9, 10)), np.empty((9, 9)), np.empty((9, 10))),
  39. 'Shapes of y (9, 9) and z (9, 10) do not match'),
  40. ((np.empty((3, 3, 3)), np.empty((3, 3, 3)), np.empty((9, 10))),
  41. 'Inputs x and y must be 1D or 2D, not 3D'),
  42. ((np.empty((3, 3, 3)), np.empty((3, 3, 3)), np.empty((3, 3, 3))),
  43. 'Input z must be 2D, not 3D'),
  44. (([[0]],), # github issue 8197
  45. 'Input z must be at least a (2, 2) shaped array, but has shape (1, 1)'),
  46. (([0], [0], [[0]]),
  47. 'Input z must be at least a (2, 2) shaped array, but has shape (1, 1)'),
  48. ])
  49. def test_contour_shape_error(args, message):
  50. fig, ax = plt.subplots()
  51. with pytest.raises(TypeError, match=re.escape(message)):
  52. ax.contour(*args)
  53. def test_contour_no_valid_levels():
  54. fig, ax = plt.subplots()
  55. # no warning for empty levels.
  56. ax.contour(np.random.rand(9, 9), levels=[])
  57. # no warning if levels is given and is not within the range of z.
  58. cs = ax.contour(np.arange(81).reshape((9, 9)), levels=[100])
  59. # ... and if fmt is given.
  60. ax.clabel(cs, fmt={100: '%1.2f'})
  61. # no warning if z is uniform.
  62. ax.contour(np.ones((9, 9)))
  63. def test_contour_Nlevels():
  64. # A scalar levels arg or kwarg should trigger auto level generation.
  65. # https://github.com/matplotlib/matplotlib/issues/11913
  66. z = np.arange(12).reshape((3, 4))
  67. fig, ax = plt.subplots()
  68. cs1 = ax.contour(z, 5)
  69. assert len(cs1.levels) > 1
  70. cs2 = ax.contour(z, levels=5)
  71. assert (cs1.levels == cs2.levels).all()
  72. @check_figures_equal(extensions=['png'])
  73. def test_contour_set_paths(fig_test, fig_ref):
  74. cs_test = fig_test.subplots().contour([[0, 1], [1, 2]])
  75. cs_ref = fig_ref.subplots().contour([[1, 0], [2, 1]])
  76. cs_test.set_paths(cs_ref.get_paths())
  77. @image_comparison(['contour_manual_labels'], remove_text=True, style='mpl20', tol=0.26)
  78. def test_contour_manual_labels():
  79. x, y = np.meshgrid(np.arange(0, 10), np.arange(0, 10))
  80. z = np.max(np.dstack([abs(x), abs(y)]), 2)
  81. plt.figure(figsize=(6, 2), dpi=200)
  82. cs = plt.contour(x, y, z)
  83. pts = np.array([(1.0, 3.0), (1.0, 4.4), (1.0, 6.0)])
  84. plt.clabel(cs, manual=pts)
  85. pts = np.array([(2.0, 3.0), (2.0, 4.4), (2.0, 6.0)])
  86. plt.clabel(cs, manual=pts, fontsize='small', colors=('r', 'g'))
  87. def test_contour_manual_moveto():
  88. x = np.linspace(-10, 10)
  89. y = np.linspace(-10, 10)
  90. X, Y = np.meshgrid(x, y)
  91. Z = X**2 * 1 / Y**2 - 1
  92. contours = plt.contour(X, Y, Z, levels=[0, 100])
  93. # This point lies on the `MOVETO` line for the 100 contour
  94. # but is actually closest to the 0 contour
  95. point = (1.3, 1)
  96. clabels = plt.clabel(contours, manual=[point])
  97. # Ensure that the 0 contour was chosen, not the 100 contour
  98. assert clabels[0].get_text() == "0"
  99. @image_comparison(['contour_disconnected_segments'],
  100. remove_text=True, style='mpl20', extensions=['png'])
  101. def test_contour_label_with_disconnected_segments():
  102. x, y = np.mgrid[-1:1:21j, -1:1:21j]
  103. z = 1 / np.sqrt(0.01 + (x + 0.3) ** 2 + y ** 2)
  104. z += 1 / np.sqrt(0.01 + (x - 0.3) ** 2 + y ** 2)
  105. plt.figure()
  106. cs = plt.contour(x, y, z, levels=[7])
  107. cs.clabel(manual=[(0.2, 0.1)])
  108. @image_comparison(['contour_manual_colors_and_levels.png'], remove_text=True,
  109. tol=0 if platform.machine() == 'x86_64' else 0.018)
  110. def test_given_colors_levels_and_extends():
  111. # Remove this line when this test image is regenerated.
  112. plt.rcParams['pcolormesh.snap'] = False
  113. _, axs = plt.subplots(2, 4)
  114. data = np.arange(12).reshape(3, 4)
  115. colors = ['red', 'yellow', 'pink', 'blue', 'black']
  116. levels = [2, 4, 8, 10]
  117. for i, ax in enumerate(axs.flat):
  118. filled = i % 2 == 0.
  119. extend = ['neither', 'min', 'max', 'both'][i // 2]
  120. if filled:
  121. # If filled, we have 3 colors with no extension,
  122. # 4 colors with one extension, and 5 colors with both extensions
  123. first_color = 1 if extend in ['max', 'neither'] else None
  124. last_color = -1 if extend in ['min', 'neither'] else None
  125. c = ax.contourf(data, colors=colors[first_color:last_color],
  126. levels=levels, extend=extend)
  127. else:
  128. # If not filled, we have 4 levels and 4 colors
  129. c = ax.contour(data, colors=colors[:-1],
  130. levels=levels, extend=extend)
  131. plt.colorbar(c, ax=ax)
  132. @image_comparison(['contourf_hatch_colors'],
  133. remove_text=True, style='mpl20', extensions=['png'])
  134. def test_hatch_colors():
  135. fig, ax = plt.subplots()
  136. cf = ax.contourf([[0, 1], [1, 2]], hatches=['-', '/', '\\', '//'], cmap='gray')
  137. cf.set_edgecolors(["blue", "grey", "yellow", "red"])
  138. @pytest.mark.parametrize('color, extend', [('darkred', 'neither'),
  139. ('darkred', 'both'),
  140. (('r', 0.5), 'neither'),
  141. ((0.1, 0.2, 0.5, 0.3), 'neither')])
  142. def test_single_color_and_extend(color, extend):
  143. z = [[0, 1], [1, 2]]
  144. _, ax = plt.subplots()
  145. levels = [0.5, 0.75, 1, 1.25, 1.5]
  146. cs = ax.contour(z, levels=levels, colors=color, extend=extend)
  147. for c in cs.get_edgecolors():
  148. assert same_color(c, color)
  149. @image_comparison(['contour_log_locator.svg'], style='mpl20', remove_text=False)
  150. def test_log_locator_levels():
  151. fig, ax = plt.subplots()
  152. N = 100
  153. x = np.linspace(-3.0, 3.0, N)
  154. y = np.linspace(-2.0, 2.0, N)
  155. X, Y = np.meshgrid(x, y)
  156. Z1 = np.exp(-X**2 - Y**2)
  157. Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
  158. data = Z1 + 50 * Z2
  159. c = ax.contourf(data, locator=ticker.LogLocator())
  160. assert_array_almost_equal(c.levels, np.power(10.0, np.arange(-6, 3)))
  161. cb = fig.colorbar(c, ax=ax)
  162. assert_array_almost_equal(cb.ax.get_yticks(), c.levels)
  163. @image_comparison(['contour_datetime_axis.png'], style='mpl20')
  164. def test_contour_datetime_axis():
  165. fig = plt.figure()
  166. fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
  167. base = datetime.datetime(2013, 1, 1)
  168. x = np.array([base + datetime.timedelta(days=d) for d in range(20)])
  169. y = np.arange(20)
  170. z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
  171. z = z1 * z2
  172. plt.subplot(221)
  173. plt.contour(x, y, z)
  174. plt.subplot(222)
  175. plt.contourf(x, y, z)
  176. x = np.repeat(x[np.newaxis], 20, axis=0)
  177. y = np.repeat(y[:, np.newaxis], 20, axis=1)
  178. plt.subplot(223)
  179. plt.contour(x, y, z)
  180. plt.subplot(224)
  181. plt.contourf(x, y, z)
  182. for ax in fig.get_axes():
  183. for label in ax.get_xticklabels():
  184. label.set_ha('right')
  185. label.set_rotation(30)
  186. @image_comparison(['contour_test_label_transforms.png'],
  187. remove_text=True, style='mpl20', tol=1.1)
  188. def test_labels():
  189. # Adapted from pylab_examples example code: contour_demo.py
  190. # see issues #2475, #2843, and #2818 for explanation
  191. delta = 0.025
  192. x = np.arange(-3.0, 3.0, delta)
  193. y = np.arange(-2.0, 2.0, delta)
  194. X, Y = np.meshgrid(x, y)
  195. Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi)
  196. Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) /
  197. (2 * np.pi * 0.5 * 1.5))
  198. # difference of Gaussians
  199. Z = 10.0 * (Z2 - Z1)
  200. fig, ax = plt.subplots(1, 1)
  201. CS = ax.contour(X, Y, Z)
  202. disp_units = [(216, 177), (359, 290), (521, 406)]
  203. data_units = [(-2, .5), (0, -1.5), (2.8, 1)]
  204. CS.clabel()
  205. for x, y in data_units:
  206. CS.add_label_near(x, y, inline=True, transform=None)
  207. for x, y in disp_units:
  208. CS.add_label_near(x, y, inline=True, transform=False)
  209. def test_label_contour_start():
  210. # Set up data and figure/axes that result in automatic labelling adding the
  211. # label to the start of a contour
  212. _, ax = plt.subplots(dpi=100)
  213. lats = lons = np.linspace(-np.pi / 2, np.pi / 2, 50)
  214. lons, lats = np.meshgrid(lons, lats)
  215. wave = 0.75 * (np.sin(2 * lats) ** 8) * np.cos(4 * lons)
  216. mean = 0.5 * np.cos(2 * lats) * ((np.sin(2 * lats)) ** 2 + 2)
  217. data = wave + mean
  218. cs = ax.contour(lons, lats, data)
  219. with mock.patch.object(
  220. cs, '_split_path_and_get_label_rotation',
  221. wraps=cs._split_path_and_get_label_rotation) as mocked_splitter:
  222. # Smoke test that we can add the labels
  223. cs.clabel(fontsize=9)
  224. # Verify at least one label was added to the start of a contour. I.e. the
  225. # splitting method was called with idx=0 at least once.
  226. idxs = [cargs[0][1] for cargs in mocked_splitter.call_args_list]
  227. assert 0 in idxs
  228. @image_comparison(['contour_corner_mask_False.png', 'contour_corner_mask_True.png'],
  229. remove_text=True, tol=1.88)
  230. def test_corner_mask():
  231. n = 60
  232. mask_level = 0.95
  233. noise_amp = 1.0
  234. np.random.seed([1])
  235. x, y = np.meshgrid(np.linspace(0, 2.0, n), np.linspace(0, 2.0, n))
  236. z = np.cos(7*x)*np.sin(8*y) + noise_amp*np.random.rand(n, n)
  237. mask = np.random.rand(n, n) >= mask_level
  238. z = np.ma.array(z, mask=mask)
  239. for corner_mask in [False, True]:
  240. plt.figure()
  241. plt.contourf(z, corner_mask=corner_mask)
  242. def test_contourf_decreasing_levels():
  243. # github issue 5477.
  244. z = [[0.1, 0.3], [0.5, 0.7]]
  245. plt.figure()
  246. with pytest.raises(ValueError):
  247. plt.contourf(z, [1.0, 0.0])
  248. def test_contourf_symmetric_locator():
  249. # github issue 7271
  250. z = np.arange(12).reshape((3, 4))
  251. locator = plt.MaxNLocator(nbins=4, symmetric=True)
  252. cs = plt.contourf(z, locator=locator)
  253. assert_array_almost_equal(cs.levels, np.linspace(-12, 12, 5))
  254. def test_circular_contour_warning():
  255. # Check that almost circular contours don't throw a warning
  256. x, y = np.meshgrid(np.linspace(-2, 2, 4), np.linspace(-2, 2, 4))
  257. r = np.hypot(x, y)
  258. plt.figure()
  259. cs = plt.contour(x, y, r)
  260. plt.clabel(cs)
  261. @pytest.mark.parametrize("use_clabeltext, contour_zorder, clabel_zorder",
  262. [(True, 123, 1234), (False, 123, 1234),
  263. (True, 123, None), (False, 123, None)])
  264. def test_clabel_zorder(use_clabeltext, contour_zorder, clabel_zorder):
  265. x, y = np.meshgrid(np.arange(0, 10), np.arange(0, 10))
  266. z = np.max(np.dstack([abs(x), abs(y)]), 2)
  267. fig, (ax1, ax2) = plt.subplots(ncols=2)
  268. cs = ax1.contour(x, y, z, zorder=contour_zorder)
  269. cs_filled = ax2.contourf(x, y, z, zorder=contour_zorder)
  270. clabels1 = cs.clabel(zorder=clabel_zorder, use_clabeltext=use_clabeltext)
  271. clabels2 = cs_filled.clabel(zorder=clabel_zorder,
  272. use_clabeltext=use_clabeltext)
  273. if clabel_zorder is None:
  274. expected_clabel_zorder = 2+contour_zorder
  275. else:
  276. expected_clabel_zorder = clabel_zorder
  277. for clabel in clabels1:
  278. assert clabel.get_zorder() == expected_clabel_zorder
  279. for clabel in clabels2:
  280. assert clabel.get_zorder() == expected_clabel_zorder
  281. def test_clabel_with_large_spacing():
  282. # When the inline spacing is large relative to the contour, it may cause the
  283. # entire contour to be removed. In current implementation, one line segment is
  284. # retained between the identified points.
  285. # This behavior may be worth reconsidering, but check to be sure we do not produce
  286. # an invalid path, which results in an error at clabel call time.
  287. # see gh-27045 for more information
  288. x = y = np.arange(-3.0, 3.01, 0.05)
  289. X, Y = np.meshgrid(x, y)
  290. Z = np.exp(-X**2 - Y**2)
  291. fig, ax = plt.subplots()
  292. contourset = ax.contour(X, Y, Z, levels=[0.01, 0.2, .5, .8])
  293. ax.clabel(contourset, inline_spacing=100)
  294. # tol because ticks happen to fall on pixel boundaries so small
  295. # floating point changes in tick location flip which pixel gets
  296. # the tick.
  297. @image_comparison(['contour_log_extension.png'],
  298. remove_text=True, style='mpl20',
  299. tol=1.444)
  300. def test_contourf_log_extension():
  301. # Remove this line when this test image is regenerated.
  302. plt.rcParams['pcolormesh.snap'] = False
  303. # Test that contourf with lognorm is extended correctly
  304. fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10, 5))
  305. fig.subplots_adjust(left=0.05, right=0.95)
  306. # make data set with large range e.g. between 1e-8 and 1e10
  307. data_exp = np.linspace(-7.5, 9.5, 1200)
  308. data = np.power(10, data_exp).reshape(30, 40)
  309. # make manual levels e.g. between 1e-4 and 1e-6
  310. levels_exp = np.arange(-4., 7.)
  311. levels = np.power(10., levels_exp)
  312. # original data
  313. c1 = ax1.contourf(data,
  314. norm=LogNorm(vmin=data.min(), vmax=data.max()))
  315. # just show data in levels
  316. c2 = ax2.contourf(data, levels=levels,
  317. norm=LogNorm(vmin=levels.min(), vmax=levels.max()),
  318. extend='neither')
  319. # extend data from levels
  320. c3 = ax3.contourf(data, levels=levels,
  321. norm=LogNorm(vmin=levels.min(), vmax=levels.max()),
  322. extend='both')
  323. cb = plt.colorbar(c1, ax=ax1)
  324. assert cb.ax.get_ylim() == (1e-8, 1e10)
  325. cb = plt.colorbar(c2, ax=ax2)
  326. assert_array_almost_equal_nulp(cb.ax.get_ylim(), np.array((1e-4, 1e6)))
  327. cb = plt.colorbar(c3, ax=ax3)
  328. @image_comparison(['contour_addlines.png'], remove_text=True, style='mpl20',
  329. tol=0.03 if platform.machine() == 'x86_64' else 0.15)
  330. # tolerance is because image changed minutely when tick finding on
  331. # colorbars was cleaned up...
  332. def test_contour_addlines():
  333. # Remove this line when this test image is regenerated.
  334. plt.rcParams['pcolormesh.snap'] = False
  335. fig, ax = plt.subplots()
  336. np.random.seed(19680812)
  337. X = np.random.rand(10, 10)*10000
  338. pcm = ax.pcolormesh(X)
  339. # add 1000 to make colors visible...
  340. cont = ax.contour(X+1000)
  341. cb = fig.colorbar(pcm)
  342. cb.add_lines(cont)
  343. assert_array_almost_equal(cb.ax.get_ylim(), [114.3091, 9972.30735], 3)
  344. @image_comparison(baseline_images=['contour_uneven'],
  345. extensions=['png'], remove_text=True, style='mpl20')
  346. def test_contour_uneven():
  347. # Remove this line when this test image is regenerated.
  348. plt.rcParams['pcolormesh.snap'] = False
  349. z = np.arange(24).reshape(4, 6)
  350. fig, axs = plt.subplots(1, 2)
  351. ax = axs[0]
  352. cs = ax.contourf(z, levels=[2, 4, 6, 10, 20])
  353. fig.colorbar(cs, ax=ax, spacing='proportional')
  354. ax = axs[1]
  355. cs = ax.contourf(z, levels=[2, 4, 6, 10, 20])
  356. fig.colorbar(cs, ax=ax, spacing='uniform')
  357. @pytest.mark.parametrize(
  358. "rc_lines_linewidth, rc_contour_linewidth, call_linewidths, expected", [
  359. (1.23, None, None, 1.23),
  360. (1.23, 4.24, None, 4.24),
  361. (1.23, 4.24, 5.02, 5.02)
  362. ])
  363. def test_contour_linewidth(
  364. rc_lines_linewidth, rc_contour_linewidth, call_linewidths, expected):
  365. with rc_context(rc={"lines.linewidth": rc_lines_linewidth,
  366. "contour.linewidth": rc_contour_linewidth}):
  367. fig, ax = plt.subplots()
  368. X = np.arange(4*3).reshape(4, 3)
  369. cs = ax.contour(X, linewidths=call_linewidths)
  370. assert cs.get_linewidths()[0] == expected
  371. @pytest.mark.backend("pdf")
  372. def test_label_nonagg():
  373. # This should not crash even if the canvas doesn't have a get_renderer().
  374. plt.clabel(plt.contour([[1, 2], [3, 4]]))
  375. @image_comparison(baseline_images=['contour_closed_line_loop'],
  376. extensions=['png'], remove_text=True)
  377. def test_contour_closed_line_loop():
  378. # github issue 19568.
  379. z = [[0, 0, 0], [0, 2, 0], [0, 0, 0], [2, 1, 2]]
  380. fig, ax = plt.subplots(figsize=(2, 2))
  381. ax.contour(z, [0.5], linewidths=[20], alpha=0.7)
  382. ax.set_xlim(-0.1, 2.1)
  383. ax.set_ylim(-0.1, 3.1)
  384. def test_quadcontourset_reuse():
  385. # If QuadContourSet returned from one contour(f) call is passed as first
  386. # argument to another the underlying C++ contour generator will be reused.
  387. x, y = np.meshgrid([0.0, 1.0], [0.0, 1.0])
  388. z = x + y
  389. fig, ax = plt.subplots()
  390. qcs1 = ax.contourf(x, y, z)
  391. qcs2 = ax.contour(x, y, z)
  392. assert qcs2._contour_generator != qcs1._contour_generator
  393. qcs3 = ax.contour(qcs1, z)
  394. assert qcs3._contour_generator == qcs1._contour_generator
  395. @image_comparison(baseline_images=['contour_manual'],
  396. extensions=['png'], remove_text=True, tol=0.89)
  397. def test_contour_manual():
  398. # Manually specifying contour lines/polygons to plot.
  399. from matplotlib.contour import ContourSet
  400. fig, ax = plt.subplots(figsize=(4, 4))
  401. cmap = 'viridis'
  402. # Segments only (no 'kind' codes).
  403. lines0 = [[[2, 0], [1, 2], [1, 3]]] # Single line.
  404. lines1 = [[[3, 0], [3, 2]], [[3, 3], [3, 4]]] # Two lines.
  405. filled01 = [[[0, 0], [0, 4], [1, 3], [1, 2], [2, 0]]]
  406. filled12 = [[[2, 0], [3, 0], [3, 2], [1, 3], [1, 2]], # Two polygons.
  407. [[1, 4], [3, 4], [3, 3]]]
  408. ContourSet(ax, [0, 1, 2], [filled01, filled12], filled=True, cmap=cmap)
  409. ContourSet(ax, [1, 2], [lines0, lines1], linewidths=3, colors=['r', 'k'])
  410. # Segments and kind codes (1 = MOVETO, 2 = LINETO, 79 = CLOSEPOLY).
  411. segs = [[[4, 0], [7, 0], [7, 3], [4, 3], [4, 0],
  412. [5, 1], [5, 2], [6, 2], [6, 1], [5, 1]]]
  413. kinds = [[1, 2, 2, 2, 79, 1, 2, 2, 2, 79]] # Polygon containing hole.
  414. ContourSet(ax, [2, 3], [segs], [kinds], filled=True, cmap=cmap)
  415. ContourSet(ax, [2], [segs], [kinds], colors='k', linewidths=3)
  416. @image_comparison(baseline_images=['contour_line_start_on_corner_edge'],
  417. extensions=['png'], remove_text=True)
  418. def test_contour_line_start_on_corner_edge():
  419. fig, ax = plt.subplots(figsize=(6, 5))
  420. x, y = np.meshgrid([0, 1, 2, 3, 4], [0, 1, 2])
  421. z = 1.2 - (x - 2)**2 + (y - 1)**2
  422. mask = np.zeros_like(z, dtype=bool)
  423. mask[1, 1] = mask[1, 3] = True
  424. z = np.ma.array(z, mask=mask)
  425. filled = ax.contourf(x, y, z, corner_mask=True)
  426. cbar = fig.colorbar(filled)
  427. lines = ax.contour(x, y, z, corner_mask=True, colors='k')
  428. cbar.add_lines(lines)
  429. def test_find_nearest_contour():
  430. xy = np.indices((15, 15))
  431. img = np.exp(-np.pi * (np.sum((xy - 5)**2, 0)/5.**2))
  432. cs = plt.contour(img, 10)
  433. nearest_contour = cs.find_nearest_contour(1, 1, pixel=False)
  434. expected_nearest = (1, 0, 33, 1.965966, 1.965966, 1.866183)
  435. assert_array_almost_equal(nearest_contour, expected_nearest)
  436. nearest_contour = cs.find_nearest_contour(8, 1, pixel=False)
  437. expected_nearest = (1, 0, 5, 7.550173, 1.587542, 0.547550)
  438. assert_array_almost_equal(nearest_contour, expected_nearest)
  439. nearest_contour = cs.find_nearest_contour(2, 5, pixel=False)
  440. expected_nearest = (3, 0, 21, 1.884384, 5.023335, 0.013911)
  441. assert_array_almost_equal(nearest_contour, expected_nearest)
  442. nearest_contour = cs.find_nearest_contour(2, 5, indices=(5, 7), pixel=False)
  443. expected_nearest = (5, 0, 16, 2.628202, 5.0, 0.394638)
  444. assert_array_almost_equal(nearest_contour, expected_nearest)
  445. def test_find_nearest_contour_no_filled():
  446. xy = np.indices((15, 15))
  447. img = np.exp(-np.pi * (np.sum((xy - 5)**2, 0)/5.**2))
  448. cs = plt.contourf(img, 10)
  449. with pytest.raises(ValueError, match="Method does not support filled contours"):
  450. cs.find_nearest_contour(1, 1, pixel=False)
  451. with pytest.raises(ValueError, match="Method does not support filled contours"):
  452. cs.find_nearest_contour(1, 10, indices=(5, 7), pixel=False)
  453. with pytest.raises(ValueError, match="Method does not support filled contours"):
  454. cs.find_nearest_contour(2, 5, indices=(2, 7), pixel=True)
  455. @mpl.style.context("default")
  456. def test_contour_autolabel_beyond_powerlimits():
  457. ax = plt.figure().add_subplot()
  458. cs = plt.contour(np.geomspace(1e-6, 1e-4, 100).reshape(10, 10),
  459. levels=[.25e-5, 1e-5, 4e-5])
  460. ax.clabel(cs)
  461. # Currently, the exponent is missing, but that may be fixed in the future.
  462. assert {text.get_text() for text in ax.texts} == {"0.25", "1.00", "4.00"}
  463. def test_contourf_legend_elements():
  464. from matplotlib.patches import Rectangle
  465. x = np.arange(1, 10)
  466. y = x.reshape(-1, 1)
  467. h = x * y
  468. cs = plt.contourf(h, levels=[10, 30, 50],
  469. colors=['#FFFF00', '#FF00FF', '#00FFFF'],
  470. extend='both')
  471. cs.cmap.set_over('red')
  472. cs.cmap.set_under('blue')
  473. cs.changed()
  474. artists, labels = cs.legend_elements()
  475. assert labels == ['$x \\leq -1e+250s$',
  476. '$10.0 < x \\leq 30.0$',
  477. '$30.0 < x \\leq 50.0$',
  478. '$x > 1e+250s$']
  479. expected_colors = ('blue', '#FFFF00', '#FF00FF', 'red')
  480. assert all(isinstance(a, Rectangle) for a in artists)
  481. assert all(same_color(a.get_facecolor(), c)
  482. for a, c in zip(artists, expected_colors))
  483. def test_contour_legend_elements():
  484. x = np.arange(1, 10)
  485. y = x.reshape(-1, 1)
  486. h = x * y
  487. colors = ['blue', '#00FF00', 'red']
  488. cs = plt.contour(h, levels=[10, 30, 50],
  489. colors=colors,
  490. extend='both')
  491. artists, labels = cs.legend_elements()
  492. assert labels == ['$x = 10.0$', '$x = 30.0$', '$x = 50.0$']
  493. assert all(isinstance(a, mpl.lines.Line2D) for a in artists)
  494. assert all(same_color(a.get_color(), c)
  495. for a, c in zip(artists, colors))
  496. @pytest.mark.parametrize(
  497. "algorithm, klass",
  498. [('mpl2005', contourpy.Mpl2005ContourGenerator),
  499. ('mpl2014', contourpy.Mpl2014ContourGenerator),
  500. ('serial', contourpy.SerialContourGenerator),
  501. ('threaded', contourpy.ThreadedContourGenerator),
  502. ('invalid', None)])
  503. def test_algorithm_name(algorithm, klass):
  504. z = np.array([[1.0, 2.0], [3.0, 4.0]])
  505. if klass is not None:
  506. cs = plt.contourf(z, algorithm=algorithm)
  507. assert isinstance(cs._contour_generator, klass)
  508. else:
  509. with pytest.raises(ValueError):
  510. plt.contourf(z, algorithm=algorithm)
  511. @pytest.mark.parametrize(
  512. "algorithm", ['mpl2005', 'mpl2014', 'serial', 'threaded'])
  513. def test_algorithm_supports_corner_mask(algorithm):
  514. z = np.array([[1.0, 2.0], [3.0, 4.0]])
  515. # All algorithms support corner_mask=False
  516. plt.contourf(z, algorithm=algorithm, corner_mask=False)
  517. # Only some algorithms support corner_mask=True
  518. if algorithm != 'mpl2005':
  519. plt.contourf(z, algorithm=algorithm, corner_mask=True)
  520. else:
  521. with pytest.raises(ValueError):
  522. plt.contourf(z, algorithm=algorithm, corner_mask=True)
  523. @image_comparison(baseline_images=['contour_all_algorithms'],
  524. extensions=['png'], remove_text=True, tol=0.06)
  525. def test_all_algorithms():
  526. algorithms = ['mpl2005', 'mpl2014', 'serial', 'threaded']
  527. rng = np.random.default_rng(2981)
  528. x, y = np.meshgrid(np.linspace(0.0, 1.0, 10), np.linspace(0.0, 1.0, 6))
  529. z = np.sin(15*x)*np.cos(10*y) + rng.normal(scale=0.5, size=(6, 10))
  530. mask = np.zeros_like(z, dtype=bool)
  531. mask[3, 7] = True
  532. z = np.ma.array(z, mask=mask)
  533. _, axs = plt.subplots(2, 2)
  534. for ax, algorithm in zip(axs.ravel(), algorithms):
  535. ax.contourf(x, y, z, algorithm=algorithm)
  536. ax.contour(x, y, z, algorithm=algorithm, colors='k')
  537. ax.set_title(algorithm)
  538. def test_subfigure_clabel():
  539. # Smoke test for gh#23173
  540. delta = 0.025
  541. x = np.arange(-3.0, 3.0, delta)
  542. y = np.arange(-2.0, 2.0, delta)
  543. X, Y = np.meshgrid(x, y)
  544. Z1 = np.exp(-(X**2) - Y**2)
  545. Z2 = np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)
  546. Z = (Z1 - Z2) * 2
  547. fig = plt.figure()
  548. figs = fig.subfigures(nrows=1, ncols=2)
  549. for f in figs:
  550. ax = f.subplots()
  551. CS = ax.contour(X, Y, Z)
  552. ax.clabel(CS, inline=True, fontsize=10)
  553. ax.set_title("Simplest default with labels")
  554. @pytest.mark.parametrize(
  555. "style", ['solid', 'dashed', 'dashdot', 'dotted'])
  556. def test_linestyles(style):
  557. delta = 0.025
  558. x = np.arange(-3.0, 3.0, delta)
  559. y = np.arange(-2.0, 2.0, delta)
  560. X, Y = np.meshgrid(x, y)
  561. Z1 = np.exp(-X**2 - Y**2)
  562. Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
  563. Z = (Z1 - Z2) * 2
  564. # Positive contour defaults to solid
  565. fig1, ax1 = plt.subplots()
  566. CS1 = ax1.contour(X, Y, Z, 6, colors='k')
  567. ax1.clabel(CS1, fontsize=9, inline=True)
  568. ax1.set_title('Single color - positive contours solid (default)')
  569. assert CS1.linestyles is None # default
  570. # Change linestyles using linestyles kwarg
  571. fig2, ax2 = plt.subplots()
  572. CS2 = ax2.contour(X, Y, Z, 6, colors='k', linestyles=style)
  573. ax2.clabel(CS2, fontsize=9, inline=True)
  574. ax2.set_title(f'Single color - positive contours {style}')
  575. assert CS2.linestyles == style
  576. # Ensure linestyles do not change when negative_linestyles is defined
  577. fig3, ax3 = plt.subplots()
  578. CS3 = ax3.contour(X, Y, Z, 6, colors='k', linestyles=style,
  579. negative_linestyles='dashdot')
  580. ax3.clabel(CS3, fontsize=9, inline=True)
  581. ax3.set_title(f'Single color - positive contours {style}')
  582. assert CS3.linestyles == style
  583. @pytest.mark.parametrize(
  584. "style", ['solid', 'dashed', 'dashdot', 'dotted'])
  585. def test_negative_linestyles(style):
  586. delta = 0.025
  587. x = np.arange(-3.0, 3.0, delta)
  588. y = np.arange(-2.0, 2.0, delta)
  589. X, Y = np.meshgrid(x, y)
  590. Z1 = np.exp(-X**2 - Y**2)
  591. Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
  592. Z = (Z1 - Z2) * 2
  593. # Negative contour defaults to dashed
  594. fig1, ax1 = plt.subplots()
  595. CS1 = ax1.contour(X, Y, Z, 6, colors='k')
  596. ax1.clabel(CS1, fontsize=9, inline=True)
  597. ax1.set_title('Single color - negative contours dashed (default)')
  598. assert CS1.negative_linestyles == 'dashed' # default
  599. # Change negative_linestyles using rcParams
  600. plt.rcParams['contour.negative_linestyle'] = style
  601. fig2, ax2 = plt.subplots()
  602. CS2 = ax2.contour(X, Y, Z, 6, colors='k')
  603. ax2.clabel(CS2, fontsize=9, inline=True)
  604. ax2.set_title(f'Single color - negative contours {style}'
  605. '(using rcParams)')
  606. assert CS2.negative_linestyles == style
  607. # Change negative_linestyles using negative_linestyles kwarg
  608. fig3, ax3 = plt.subplots()
  609. CS3 = ax3.contour(X, Y, Z, 6, colors='k', negative_linestyles=style)
  610. ax3.clabel(CS3, fontsize=9, inline=True)
  611. ax3.set_title(f'Single color - negative contours {style}')
  612. assert CS3.negative_linestyles == style
  613. # Ensure negative_linestyles do not change when linestyles is defined
  614. fig4, ax4 = plt.subplots()
  615. CS4 = ax4.contour(X, Y, Z, 6, colors='k', linestyles='dashdot',
  616. negative_linestyles=style)
  617. ax4.clabel(CS4, fontsize=9, inline=True)
  618. ax4.set_title(f'Single color - negative contours {style}')
  619. assert CS4.negative_linestyles == style
  620. def test_contour_remove():
  621. ax = plt.figure().add_subplot()
  622. orig_children = ax.get_children()
  623. cs = ax.contour(np.arange(16).reshape((4, 4)))
  624. cs.clabel()
  625. assert ax.get_children() != orig_children
  626. cs.remove()
  627. assert ax.get_children() == orig_children
  628. def test_contour_no_args():
  629. fig, ax = plt.subplots()
  630. data = [[0, 1], [1, 0]]
  631. with pytest.raises(TypeError, match=r"contour\(\) takes from 1 to 4"):
  632. ax.contour(Z=data)
  633. def test_contour_clip_path():
  634. fig, ax = plt.subplots()
  635. data = [[0, 1], [1, 0]]
  636. circle = mpatches.Circle([0.5, 0.5], 0.5, transform=ax.transAxes)
  637. cs = ax.contour(data, clip_path=circle)
  638. assert cs.get_clip_path() is not None
  639. def test_bool_autolevel():
  640. x, y = np.random.rand(2, 9)
  641. z = (np.arange(9) % 2).reshape((3, 3)).astype(bool)
  642. m = [[False, False, False], [False, True, False], [False, False, False]]
  643. assert plt.contour(z.tolist()).levels.tolist() == [.5]
  644. assert plt.contour(z).levels.tolist() == [.5]
  645. assert plt.contour(np.ma.array(z, mask=m)).levels.tolist() == [.5]
  646. assert plt.contourf(z.tolist()).levels.tolist() == [0, .5, 1]
  647. assert plt.contourf(z).levels.tolist() == [0, .5, 1]
  648. assert plt.contourf(np.ma.array(z, mask=m)).levels.tolist() == [0, .5, 1]
  649. z = z.ravel()
  650. assert plt.tricontour(x, y, z.tolist()).levels.tolist() == [.5]
  651. assert plt.tricontour(x, y, z).levels.tolist() == [.5]
  652. assert plt.tricontourf(x, y, z.tolist()).levels.tolist() == [0, .5, 1]
  653. assert plt.tricontourf(x, y, z).levels.tolist() == [0, .5, 1]
  654. def test_all_nan():
  655. x = np.array([[np.nan, np.nan], [np.nan, np.nan]])
  656. assert_array_almost_equal(plt.contour(x).levels,
  657. [-1e-13, -7.5e-14, -5e-14, -2.4e-14, 0.0,
  658. 2.4e-14, 5e-14, 7.5e-14, 1e-13])
  659. def test_allsegs_allkinds():
  660. x, y = np.meshgrid(np.arange(0, 10, 2), np.arange(0, 10, 2))
  661. z = np.sin(x) * np.cos(y)
  662. cs = plt.contour(x, y, z, levels=[0, 0.5])
  663. # Expect two levels, the first with 5 segments and the second with 4.
  664. for result in [cs.allsegs, cs.allkinds]:
  665. assert len(result) == 2
  666. assert len(result[0]) == 5
  667. assert len(result[1]) == 4