test_collections.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. from datetime import datetime
  2. import io
  3. import itertools
  4. import re
  5. from types import SimpleNamespace
  6. import numpy as np
  7. from numpy.testing import assert_array_equal, assert_array_almost_equal
  8. import pytest
  9. import matplotlib as mpl
  10. import matplotlib.pyplot as plt
  11. import matplotlib.collections as mcollections
  12. import matplotlib.colors as mcolors
  13. import matplotlib.path as mpath
  14. import matplotlib.transforms as mtransforms
  15. from matplotlib.collections import (Collection, LineCollection,
  16. EventCollection, PolyCollection)
  17. from matplotlib.testing.decorators import check_figures_equal, image_comparison
  18. @pytest.fixture(params=["pcolormesh", "pcolor"])
  19. def pcfunc(request):
  20. return request.param
  21. def generate_EventCollection_plot():
  22. """Generate the initial collection and plot it."""
  23. positions = np.array([0., 1., 2., 3., 5., 8., 13., 21.])
  24. extra_positions = np.array([34., 55., 89.])
  25. orientation = 'horizontal'
  26. lineoffset = 1
  27. linelength = .5
  28. linewidth = 2
  29. color = [1, 0, 0, 1]
  30. linestyle = 'solid'
  31. antialiased = True
  32. coll = EventCollection(positions,
  33. orientation=orientation,
  34. lineoffset=lineoffset,
  35. linelength=linelength,
  36. linewidth=linewidth,
  37. color=color,
  38. linestyle=linestyle,
  39. antialiased=antialiased
  40. )
  41. fig, ax = plt.subplots()
  42. ax.add_collection(coll)
  43. ax.set_title('EventCollection: default')
  44. props = {'positions': positions,
  45. 'extra_positions': extra_positions,
  46. 'orientation': orientation,
  47. 'lineoffset': lineoffset,
  48. 'linelength': linelength,
  49. 'linewidth': linewidth,
  50. 'color': color,
  51. 'linestyle': linestyle,
  52. 'antialiased': antialiased
  53. }
  54. ax.set_xlim(-1, 22)
  55. ax.set_ylim(0, 2)
  56. return ax, coll, props
  57. @image_comparison(['EventCollection_plot__default'])
  58. def test__EventCollection__get_props():
  59. _, coll, props = generate_EventCollection_plot()
  60. # check that the default segments have the correct coordinates
  61. check_segments(coll,
  62. props['positions'],
  63. props['linelength'],
  64. props['lineoffset'],
  65. props['orientation'])
  66. # check that the default positions match the input positions
  67. np.testing.assert_array_equal(props['positions'], coll.get_positions())
  68. # check that the default orientation matches the input orientation
  69. assert props['orientation'] == coll.get_orientation()
  70. # check that the default orientation matches the input orientation
  71. assert coll.is_horizontal()
  72. # check that the default linelength matches the input linelength
  73. assert props['linelength'] == coll.get_linelength()
  74. # check that the default lineoffset matches the input lineoffset
  75. assert props['lineoffset'] == coll.get_lineoffset()
  76. # check that the default linestyle matches the input linestyle
  77. assert coll.get_linestyle() == [(0, None)]
  78. # check that the default color matches the input color
  79. for color in [coll.get_color(), *coll.get_colors()]:
  80. np.testing.assert_array_equal(color, props['color'])
  81. @image_comparison(['EventCollection_plot__set_positions'])
  82. def test__EventCollection__set_positions():
  83. splt, coll, props = generate_EventCollection_plot()
  84. new_positions = np.hstack([props['positions'], props['extra_positions']])
  85. coll.set_positions(new_positions)
  86. np.testing.assert_array_equal(new_positions, coll.get_positions())
  87. check_segments(coll, new_positions,
  88. props['linelength'],
  89. props['lineoffset'],
  90. props['orientation'])
  91. splt.set_title('EventCollection: set_positions')
  92. splt.set_xlim(-1, 90)
  93. @image_comparison(['EventCollection_plot__add_positions'])
  94. def test__EventCollection__add_positions():
  95. splt, coll, props = generate_EventCollection_plot()
  96. new_positions = np.hstack([props['positions'],
  97. props['extra_positions'][0]])
  98. coll.switch_orientation() # Test adding in the vertical orientation, too.
  99. coll.add_positions(props['extra_positions'][0])
  100. coll.switch_orientation()
  101. np.testing.assert_array_equal(new_positions, coll.get_positions())
  102. check_segments(coll,
  103. new_positions,
  104. props['linelength'],
  105. props['lineoffset'],
  106. props['orientation'])
  107. splt.set_title('EventCollection: add_positions')
  108. splt.set_xlim(-1, 35)
  109. @image_comparison(['EventCollection_plot__append_positions'])
  110. def test__EventCollection__append_positions():
  111. splt, coll, props = generate_EventCollection_plot()
  112. new_positions = np.hstack([props['positions'],
  113. props['extra_positions'][2]])
  114. coll.append_positions(props['extra_positions'][2])
  115. np.testing.assert_array_equal(new_positions, coll.get_positions())
  116. check_segments(coll,
  117. new_positions,
  118. props['linelength'],
  119. props['lineoffset'],
  120. props['orientation'])
  121. splt.set_title('EventCollection: append_positions')
  122. splt.set_xlim(-1, 90)
  123. @image_comparison(['EventCollection_plot__extend_positions'])
  124. def test__EventCollection__extend_positions():
  125. splt, coll, props = generate_EventCollection_plot()
  126. new_positions = np.hstack([props['positions'],
  127. props['extra_positions'][1:]])
  128. coll.extend_positions(props['extra_positions'][1:])
  129. np.testing.assert_array_equal(new_positions, coll.get_positions())
  130. check_segments(coll,
  131. new_positions,
  132. props['linelength'],
  133. props['lineoffset'],
  134. props['orientation'])
  135. splt.set_title('EventCollection: extend_positions')
  136. splt.set_xlim(-1, 90)
  137. @image_comparison(['EventCollection_plot__switch_orientation'])
  138. def test__EventCollection__switch_orientation():
  139. splt, coll, props = generate_EventCollection_plot()
  140. new_orientation = 'vertical'
  141. coll.switch_orientation()
  142. assert new_orientation == coll.get_orientation()
  143. assert not coll.is_horizontal()
  144. new_positions = coll.get_positions()
  145. check_segments(coll,
  146. new_positions,
  147. props['linelength'],
  148. props['lineoffset'], new_orientation)
  149. splt.set_title('EventCollection: switch_orientation')
  150. splt.set_ylim(-1, 22)
  151. splt.set_xlim(0, 2)
  152. @image_comparison(['EventCollection_plot__switch_orientation__2x'])
  153. def test__EventCollection__switch_orientation_2x():
  154. """
  155. Check that calling switch_orientation twice sets the orientation back to
  156. the default.
  157. """
  158. splt, coll, props = generate_EventCollection_plot()
  159. coll.switch_orientation()
  160. coll.switch_orientation()
  161. new_positions = coll.get_positions()
  162. assert props['orientation'] == coll.get_orientation()
  163. assert coll.is_horizontal()
  164. np.testing.assert_array_equal(props['positions'], new_positions)
  165. check_segments(coll,
  166. new_positions,
  167. props['linelength'],
  168. props['lineoffset'],
  169. props['orientation'])
  170. splt.set_title('EventCollection: switch_orientation 2x')
  171. @image_comparison(['EventCollection_plot__set_orientation'])
  172. def test__EventCollection__set_orientation():
  173. splt, coll, props = generate_EventCollection_plot()
  174. new_orientation = 'vertical'
  175. coll.set_orientation(new_orientation)
  176. assert new_orientation == coll.get_orientation()
  177. assert not coll.is_horizontal()
  178. check_segments(coll,
  179. props['positions'],
  180. props['linelength'],
  181. props['lineoffset'],
  182. new_orientation)
  183. splt.set_title('EventCollection: set_orientation')
  184. splt.set_ylim(-1, 22)
  185. splt.set_xlim(0, 2)
  186. @image_comparison(['EventCollection_plot__set_linelength'])
  187. def test__EventCollection__set_linelength():
  188. splt, coll, props = generate_EventCollection_plot()
  189. new_linelength = 15
  190. coll.set_linelength(new_linelength)
  191. assert new_linelength == coll.get_linelength()
  192. check_segments(coll,
  193. props['positions'],
  194. new_linelength,
  195. props['lineoffset'],
  196. props['orientation'])
  197. splt.set_title('EventCollection: set_linelength')
  198. splt.set_ylim(-20, 20)
  199. @image_comparison(['EventCollection_plot__set_lineoffset'])
  200. def test__EventCollection__set_lineoffset():
  201. splt, coll, props = generate_EventCollection_plot()
  202. new_lineoffset = -5.
  203. coll.set_lineoffset(new_lineoffset)
  204. assert new_lineoffset == coll.get_lineoffset()
  205. check_segments(coll,
  206. props['positions'],
  207. props['linelength'],
  208. new_lineoffset,
  209. props['orientation'])
  210. splt.set_title('EventCollection: set_lineoffset')
  211. splt.set_ylim(-6, -4)
  212. @image_comparison([
  213. 'EventCollection_plot__set_linestyle',
  214. 'EventCollection_plot__set_linestyle',
  215. 'EventCollection_plot__set_linewidth',
  216. ])
  217. def test__EventCollection__set_prop():
  218. for prop, value, expected in [
  219. ('linestyle', 'dashed', [(0, (6.0, 6.0))]),
  220. ('linestyle', (0, (6., 6.)), [(0, (6.0, 6.0))]),
  221. ('linewidth', 5, 5),
  222. ]:
  223. splt, coll, _ = generate_EventCollection_plot()
  224. coll.set(**{prop: value})
  225. assert plt.getp(coll, prop) == expected
  226. splt.set_title(f'EventCollection: set_{prop}')
  227. @image_comparison(['EventCollection_plot__set_color'])
  228. def test__EventCollection__set_color():
  229. splt, coll, _ = generate_EventCollection_plot()
  230. new_color = np.array([0, 1, 1, 1])
  231. coll.set_color(new_color)
  232. for color in [coll.get_color(), *coll.get_colors()]:
  233. np.testing.assert_array_equal(color, new_color)
  234. splt.set_title('EventCollection: set_color')
  235. def check_segments(coll, positions, linelength, lineoffset, orientation):
  236. """
  237. Test helper checking that all values in the segment are correct, given a
  238. particular set of inputs.
  239. """
  240. segments = coll.get_segments()
  241. if (orientation.lower() == 'horizontal'
  242. or orientation.lower() == 'none' or orientation is None):
  243. # if horizontal, the position in is in the y-axis
  244. pos1 = 1
  245. pos2 = 0
  246. elif orientation.lower() == 'vertical':
  247. # if vertical, the position in is in the x-axis
  248. pos1 = 0
  249. pos2 = 1
  250. else:
  251. raise ValueError("orientation must be 'horizontal' or 'vertical'")
  252. # test to make sure each segment is correct
  253. for i, segment in enumerate(segments):
  254. assert segment[0, pos1] == lineoffset + linelength / 2
  255. assert segment[1, pos1] == lineoffset - linelength / 2
  256. assert segment[0, pos2] == positions[i]
  257. assert segment[1, pos2] == positions[i]
  258. def test_null_collection_datalim():
  259. col = mcollections.PathCollection([])
  260. col_data_lim = col.get_datalim(mtransforms.IdentityTransform())
  261. assert_array_equal(col_data_lim.get_points(),
  262. mtransforms.Bbox.null().get_points())
  263. def test_no_offsets_datalim():
  264. # A collection with no offsets and a non transData
  265. # transform should return a null bbox
  266. ax = plt.axes()
  267. coll = mcollections.PathCollection([mpath.Path([(0, 0), (1, 0)])])
  268. ax.add_collection(coll)
  269. coll_data_lim = coll.get_datalim(mtransforms.IdentityTransform())
  270. assert_array_equal(coll_data_lim.get_points(),
  271. mtransforms.Bbox.null().get_points())
  272. def test_add_collection():
  273. # Test if data limits are unchanged by adding an empty collection.
  274. # GitHub issue #1490, pull #1497.
  275. plt.figure()
  276. ax = plt.axes()
  277. ax.scatter([0, 1], [0, 1])
  278. bounds = ax.dataLim.bounds
  279. ax.scatter([], [])
  280. assert ax.dataLim.bounds == bounds
  281. @mpl.style.context('mpl20')
  282. @check_figures_equal(extensions=['png'])
  283. def test_collection_log_datalim(fig_test, fig_ref):
  284. # Data limits should respect the minimum x/y when using log scale.
  285. x_vals = [4.38462e-6, 5.54929e-6, 7.02332e-6, 8.88889e-6, 1.12500e-5,
  286. 1.42383e-5, 1.80203e-5, 2.28070e-5, 2.88651e-5, 3.65324e-5,
  287. 4.62363e-5, 5.85178e-5, 7.40616e-5, 9.37342e-5, 1.18632e-4]
  288. y_vals = [0.0, 0.1, 0.182, 0.332, 0.604, 1.1, 2.0, 3.64, 6.64, 12.1, 22.0,
  289. 39.6, 71.3]
  290. x, y = np.meshgrid(x_vals, y_vals)
  291. x = x.flatten()
  292. y = y.flatten()
  293. ax_test = fig_test.subplots()
  294. ax_test.set_xscale('log')
  295. ax_test.set_yscale('log')
  296. ax_test.margins = 0
  297. ax_test.scatter(x, y)
  298. ax_ref = fig_ref.subplots()
  299. ax_ref.set_xscale('log')
  300. ax_ref.set_yscale('log')
  301. ax_ref.plot(x, y, marker="o", ls="")
  302. def test_quiver_limits():
  303. ax = plt.axes()
  304. x, y = np.arange(8), np.arange(10)
  305. u = v = np.linspace(0, 10, 80).reshape(10, 8)
  306. q = plt.quiver(x, y, u, v)
  307. assert q.get_datalim(ax.transData).bounds == (0., 0., 7., 9.)
  308. plt.figure()
  309. ax = plt.axes()
  310. x = np.linspace(-5, 10, 20)
  311. y = np.linspace(-2, 4, 10)
  312. y, x = np.meshgrid(y, x)
  313. trans = mtransforms.Affine2D().translate(25, 32) + ax.transData
  314. plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans)
  315. assert ax.dataLim.bounds == (20.0, 30.0, 15.0, 6.0)
  316. def test_barb_limits():
  317. ax = plt.axes()
  318. x = np.linspace(-5, 10, 20)
  319. y = np.linspace(-2, 4, 10)
  320. y, x = np.meshgrid(y, x)
  321. trans = mtransforms.Affine2D().translate(25, 32) + ax.transData
  322. plt.barbs(x, y, np.sin(x), np.cos(y), transform=trans)
  323. # The calculated bounds are approximately the bounds of the original data,
  324. # this is because the entire path is taken into account when updating the
  325. # datalim.
  326. assert_array_almost_equal(ax.dataLim.bounds, (20, 30, 15, 6),
  327. decimal=1)
  328. @image_comparison(['EllipseCollection_test_image.png'], remove_text=True)
  329. def test_EllipseCollection():
  330. # Test basic functionality
  331. fig, ax = plt.subplots()
  332. x = np.arange(4)
  333. y = np.arange(3)
  334. X, Y = np.meshgrid(x, y)
  335. XY = np.vstack((X.ravel(), Y.ravel())).T
  336. ww = X / x[-1]
  337. hh = Y / y[-1]
  338. aa = np.ones_like(ww) * 20 # first axis is 20 degrees CCW from x axis
  339. ec = mcollections.EllipseCollection(
  340. ww, hh, aa, units='x', offsets=XY, offset_transform=ax.transData,
  341. facecolors='none')
  342. ax.add_collection(ec)
  343. ax.autoscale_view()
  344. @image_comparison(['polycollection_close.png'], remove_text=True, style='mpl20')
  345. def test_polycollection_close():
  346. from mpl_toolkits.mplot3d import Axes3D # type: ignore
  347. vertsQuad = [
  348. [[0., 0.], [0., 1.], [1., 1.], [1., 0.]],
  349. [[0., 1.], [2., 3.], [2., 2.], [1., 1.]],
  350. [[2., 2.], [2., 3.], [4., 1.], [3., 1.]],
  351. [[3., 0.], [3., 1.], [4., 1.], [4., 0.]]]
  352. fig = plt.figure()
  353. ax = fig.add_axes(Axes3D(fig))
  354. colors = ['r', 'g', 'b', 'y', 'k']
  355. zpos = list(range(5))
  356. poly = mcollections.PolyCollection(
  357. vertsQuad * len(zpos), linewidth=0.25)
  358. poly.set_alpha(0.7)
  359. # need to have a z-value for *each* polygon = element!
  360. zs = []
  361. cs = []
  362. for z, c in zip(zpos, colors):
  363. zs.extend([z] * len(vertsQuad))
  364. cs.extend([c] * len(vertsQuad))
  365. poly.set_color(cs)
  366. ax.add_collection3d(poly, zs=zs, zdir='y')
  367. # axis limit settings:
  368. ax.set_xlim3d(0, 4)
  369. ax.set_zlim3d(0, 3)
  370. ax.set_ylim3d(0, 4)
  371. @image_comparison(['regularpolycollection_rotate.png'], remove_text=True)
  372. def test_regularpolycollection_rotate():
  373. xx, yy = np.mgrid[:10, :10]
  374. xy_points = np.transpose([xx.flatten(), yy.flatten()])
  375. rotations = np.linspace(0, 2*np.pi, len(xy_points))
  376. fig, ax = plt.subplots()
  377. for xy, alpha in zip(xy_points, rotations):
  378. col = mcollections.RegularPolyCollection(
  379. 4, sizes=(100,), rotation=alpha,
  380. offsets=[xy], offset_transform=ax.transData)
  381. ax.add_collection(col, autolim=True)
  382. ax.autoscale_view()
  383. @image_comparison(['regularpolycollection_scale.png'], remove_text=True)
  384. def test_regularpolycollection_scale():
  385. # See issue #3860
  386. class SquareCollection(mcollections.RegularPolyCollection):
  387. def __init__(self, **kwargs):
  388. super().__init__(4, rotation=np.pi/4., **kwargs)
  389. def get_transform(self):
  390. """Return transform scaling circle areas to data space."""
  391. ax = self.axes
  392. pts2pixels = 72.0 / ax.figure.dpi
  393. scale_x = pts2pixels * ax.bbox.width / ax.viewLim.width
  394. scale_y = pts2pixels * ax.bbox.height / ax.viewLim.height
  395. return mtransforms.Affine2D().scale(scale_x, scale_y)
  396. fig, ax = plt.subplots()
  397. xy = [(0, 0)]
  398. # Unit square has a half-diagonal of `1/sqrt(2)`, so `pi * r**2` equals...
  399. circle_areas = [np.pi / 2]
  400. squares = SquareCollection(
  401. sizes=circle_areas, offsets=xy, offset_transform=ax.transData)
  402. ax.add_collection(squares, autolim=True)
  403. ax.axis([-1, 1, -1, 1])
  404. def test_picking():
  405. fig, ax = plt.subplots()
  406. col = ax.scatter([0], [0], [1000], picker=True)
  407. fig.savefig(io.BytesIO(), dpi=fig.dpi)
  408. mouse_event = SimpleNamespace(x=325, y=240)
  409. found, indices = col.contains(mouse_event)
  410. assert found
  411. assert_array_equal(indices['ind'], [0])
  412. def test_quadmesh_contains():
  413. x = np.arange(4)
  414. X = x[:, None] * x[None, :]
  415. fig, ax = plt.subplots()
  416. mesh = ax.pcolormesh(X)
  417. fig.draw_without_rendering()
  418. xdata, ydata = 0.5, 0.5
  419. x, y = mesh.get_transform().transform((xdata, ydata))
  420. mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)
  421. found, indices = mesh.contains(mouse_event)
  422. assert found
  423. assert_array_equal(indices['ind'], [0])
  424. xdata, ydata = 1.5, 1.5
  425. x, y = mesh.get_transform().transform((xdata, ydata))
  426. mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)
  427. found, indices = mesh.contains(mouse_event)
  428. assert found
  429. assert_array_equal(indices['ind'], [5])
  430. def test_quadmesh_contains_concave():
  431. # Test a concave polygon, V-like shape
  432. x = [[0, -1], [1, 0]]
  433. y = [[0, 1], [1, -1]]
  434. fig, ax = plt.subplots()
  435. mesh = ax.pcolormesh(x, y, [[0]])
  436. fig.draw_without_rendering()
  437. # xdata, ydata, expected
  438. points = [(-0.5, 0.25, True), # left wing
  439. (0, 0.25, False), # between the two wings
  440. (0.5, 0.25, True), # right wing
  441. (0, -0.25, True), # main body
  442. ]
  443. for point in points:
  444. xdata, ydata, expected = point
  445. x, y = mesh.get_transform().transform((xdata, ydata))
  446. mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)
  447. found, indices = mesh.contains(mouse_event)
  448. assert found is expected
  449. def test_quadmesh_cursor_data():
  450. x = np.arange(4)
  451. X = x[:, None] * x[None, :]
  452. fig, ax = plt.subplots()
  453. mesh = ax.pcolormesh(X)
  454. # Empty array data
  455. mesh._A = None
  456. fig.draw_without_rendering()
  457. xdata, ydata = 0.5, 0.5
  458. x, y = mesh.get_transform().transform((xdata, ydata))
  459. mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)
  460. # Empty collection should return None
  461. assert mesh.get_cursor_data(mouse_event) is None
  462. # Now test adding the array data, to make sure we do get a value
  463. mesh.set_array(np.ones(X.shape))
  464. assert_array_equal(mesh.get_cursor_data(mouse_event), [1])
  465. def test_quadmesh_cursor_data_multiple_points():
  466. x = [1, 2, 1, 2]
  467. fig, ax = plt.subplots()
  468. mesh = ax.pcolormesh(x, x, np.ones((3, 3)))
  469. fig.draw_without_rendering()
  470. xdata, ydata = 1.5, 1.5
  471. x, y = mesh.get_transform().transform((xdata, ydata))
  472. mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)
  473. # All quads are covering the same square
  474. assert_array_equal(mesh.get_cursor_data(mouse_event), np.ones(9))
  475. def test_linestyle_single_dashes():
  476. plt.scatter([0, 1, 2], [0, 1, 2], linestyle=(0., [2., 2.]))
  477. plt.draw()
  478. @image_comparison(['size_in_xy.png'], remove_text=True)
  479. def test_size_in_xy():
  480. fig, ax = plt.subplots()
  481. widths, heights, angles = (10, 10), 10, 0
  482. widths = 10, 10
  483. coords = [(10, 10), (15, 15)]
  484. e = mcollections.EllipseCollection(
  485. widths, heights, angles, units='xy',
  486. offsets=coords, offset_transform=ax.transData)
  487. ax.add_collection(e)
  488. ax.set_xlim(0, 30)
  489. ax.set_ylim(0, 30)
  490. def test_pandas_indexing(pd):
  491. # Should not fail break when faced with a
  492. # non-zero indexed series
  493. index = [11, 12, 13]
  494. ec = fc = pd.Series(['red', 'blue', 'green'], index=index)
  495. lw = pd.Series([1, 2, 3], index=index)
  496. ls = pd.Series(['solid', 'dashed', 'dashdot'], index=index)
  497. aa = pd.Series([True, False, True], index=index)
  498. Collection(edgecolors=ec)
  499. Collection(facecolors=fc)
  500. Collection(linewidths=lw)
  501. Collection(linestyles=ls)
  502. Collection(antialiaseds=aa)
  503. @mpl.style.context('default')
  504. def test_lslw_bcast():
  505. col = mcollections.PathCollection([])
  506. col.set_linestyles(['-', '-'])
  507. col.set_linewidths([1, 2, 3])
  508. assert col.get_linestyles() == [(0, None)] * 6
  509. assert col.get_linewidths() == [1, 2, 3] * 2
  510. col.set_linestyles(['-', '-', '-'])
  511. assert col.get_linestyles() == [(0, None)] * 3
  512. assert (col.get_linewidths() == [1, 2, 3]).all()
  513. def test_set_wrong_linestyle():
  514. c = Collection()
  515. with pytest.raises(ValueError, match="Do not know how to convert 'fuzzy'"):
  516. c.set_linestyle('fuzzy')
  517. @mpl.style.context('default')
  518. def test_capstyle():
  519. col = mcollections.PathCollection([])
  520. assert col.get_capstyle() is None
  521. col = mcollections.PathCollection([], capstyle='round')
  522. assert col.get_capstyle() == 'round'
  523. col.set_capstyle('butt')
  524. assert col.get_capstyle() == 'butt'
  525. @mpl.style.context('default')
  526. def test_joinstyle():
  527. col = mcollections.PathCollection([])
  528. assert col.get_joinstyle() is None
  529. col = mcollections.PathCollection([], joinstyle='round')
  530. assert col.get_joinstyle() == 'round'
  531. col.set_joinstyle('miter')
  532. assert col.get_joinstyle() == 'miter'
  533. @image_comparison(['cap_and_joinstyle.png'])
  534. def test_cap_and_joinstyle_image():
  535. fig, ax = plt.subplots()
  536. ax.set_xlim([-0.5, 1.5])
  537. ax.set_ylim([-0.5, 2.5])
  538. x = np.array([0.0, 1.0, 0.5])
  539. ys = np.array([[0.0], [0.5], [1.0]]) + np.array([[0.0, 0.0, 1.0]])
  540. segs = np.zeros((3, 3, 2))
  541. segs[:, :, 0] = x
  542. segs[:, :, 1] = ys
  543. line_segments = LineCollection(segs, linewidth=[10, 15, 20])
  544. line_segments.set_capstyle("round")
  545. line_segments.set_joinstyle("miter")
  546. ax.add_collection(line_segments)
  547. ax.set_title('Line collection with customized caps and joinstyle')
  548. @image_comparison(['scatter_post_alpha.png'],
  549. remove_text=True, style='default')
  550. def test_scatter_post_alpha():
  551. fig, ax = plt.subplots()
  552. sc = ax.scatter(range(5), range(5), c=range(5))
  553. sc.set_alpha(.1)
  554. def test_scatter_alpha_array():
  555. x = np.arange(5)
  556. alpha = x / 5
  557. # With colormapping.
  558. fig, (ax0, ax1) = plt.subplots(2)
  559. sc0 = ax0.scatter(x, x, c=x, alpha=alpha)
  560. sc1 = ax1.scatter(x, x, c=x)
  561. sc1.set_alpha(alpha)
  562. plt.draw()
  563. assert_array_equal(sc0.get_facecolors()[:, -1], alpha)
  564. assert_array_equal(sc1.get_facecolors()[:, -1], alpha)
  565. # Without colormapping.
  566. fig, (ax0, ax1) = plt.subplots(2)
  567. sc0 = ax0.scatter(x, x, color=['r', 'g', 'b', 'c', 'm'], alpha=alpha)
  568. sc1 = ax1.scatter(x, x, color='r', alpha=alpha)
  569. plt.draw()
  570. assert_array_equal(sc0.get_facecolors()[:, -1], alpha)
  571. assert_array_equal(sc1.get_facecolors()[:, -1], alpha)
  572. # Without colormapping, and set alpha afterward.
  573. fig, (ax0, ax1) = plt.subplots(2)
  574. sc0 = ax0.scatter(x, x, color=['r', 'g', 'b', 'c', 'm'])
  575. sc0.set_alpha(alpha)
  576. sc1 = ax1.scatter(x, x, color='r')
  577. sc1.set_alpha(alpha)
  578. plt.draw()
  579. assert_array_equal(sc0.get_facecolors()[:, -1], alpha)
  580. assert_array_equal(sc1.get_facecolors()[:, -1], alpha)
  581. def test_pathcollection_legend_elements():
  582. np.random.seed(19680801)
  583. x, y = np.random.rand(2, 10)
  584. y = np.random.rand(10)
  585. c = np.random.randint(0, 5, size=10)
  586. s = np.random.randint(10, 300, size=10)
  587. fig, ax = plt.subplots()
  588. sc = ax.scatter(x, y, c=c, s=s, cmap="jet", marker="o", linewidths=0)
  589. h, l = sc.legend_elements(fmt="{x:g}")
  590. assert len(h) == 5
  591. assert l == ["0", "1", "2", "3", "4"]
  592. colors = np.array([line.get_color() for line in h])
  593. colors2 = sc.cmap(np.arange(5)/4)
  594. assert_array_equal(colors, colors2)
  595. l1 = ax.legend(h, l, loc=1)
  596. h2, lab2 = sc.legend_elements(num=9)
  597. assert len(h2) == 9
  598. l2 = ax.legend(h2, lab2, loc=2)
  599. h, l = sc.legend_elements(prop="sizes", alpha=0.5, color="red")
  600. assert all(line.get_alpha() == 0.5 for line in h)
  601. assert all(line.get_markerfacecolor() == "red" for line in h)
  602. l3 = ax.legend(h, l, loc=4)
  603. h, l = sc.legend_elements(prop="sizes", num=4, fmt="{x:.2f}",
  604. func=lambda x: 2*x)
  605. actsizes = [line.get_markersize() for line in h]
  606. labeledsizes = np.sqrt(np.array(l, float) / 2)
  607. assert_array_almost_equal(actsizes, labeledsizes)
  608. l4 = ax.legend(h, l, loc=3)
  609. loc = mpl.ticker.MaxNLocator(nbins=9, min_n_ticks=9-1,
  610. steps=[1, 2, 2.5, 3, 5, 6, 8, 10])
  611. h5, lab5 = sc.legend_elements(num=loc)
  612. assert len(h2) == len(h5)
  613. levels = [-1, 0, 55.4, 260]
  614. h6, lab6 = sc.legend_elements(num=levels, prop="sizes", fmt="{x:g}")
  615. assert [float(l) for l in lab6] == levels[2:]
  616. for l in [l1, l2, l3, l4]:
  617. ax.add_artist(l)
  618. fig.canvas.draw()
  619. def test_EventCollection_nosort():
  620. # Check that EventCollection doesn't modify input in place
  621. arr = np.array([3, 2, 1, 10])
  622. coll = EventCollection(arr)
  623. np.testing.assert_array_equal(arr, np.array([3, 2, 1, 10]))
  624. def test_collection_set_verts_array():
  625. verts = np.arange(80, dtype=np.double).reshape(10, 4, 2)
  626. col_arr = PolyCollection(verts)
  627. col_list = PolyCollection(list(verts))
  628. assert len(col_arr._paths) == len(col_list._paths)
  629. for ap, lp in zip(col_arr._paths, col_list._paths):
  630. assert np.array_equal(ap._vertices, lp._vertices)
  631. assert np.array_equal(ap._codes, lp._codes)
  632. verts_tuple = np.empty(10, dtype=object)
  633. verts_tuple[:] = [tuple(tuple(y) for y in x) for x in verts]
  634. col_arr_tuple = PolyCollection(verts_tuple)
  635. assert len(col_arr._paths) == len(col_arr_tuple._paths)
  636. for ap, atp in zip(col_arr._paths, col_arr_tuple._paths):
  637. assert np.array_equal(ap._vertices, atp._vertices)
  638. assert np.array_equal(ap._codes, atp._codes)
  639. def test_collection_set_array():
  640. vals = [*range(10)]
  641. # Test set_array with list
  642. c = Collection()
  643. c.set_array(vals)
  644. # Test set_array with wrong dtype
  645. with pytest.raises(TypeError, match="^Image data of dtype"):
  646. c.set_array("wrong_input")
  647. # Test if array kwarg is copied
  648. vals[5] = 45
  649. assert np.not_equal(vals, c.get_array()).any()
  650. def test_blended_collection_autolim():
  651. a = [1, 2, 4]
  652. height = .2
  653. xy_pairs = np.column_stack([np.repeat(a, 2), np.tile([0, height], len(a))])
  654. line_segs = xy_pairs.reshape([len(a), 2, 2])
  655. f, ax = plt.subplots()
  656. trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes)
  657. ax.add_collection(LineCollection(line_segs, transform=trans))
  658. ax.autoscale_view(scalex=True, scaley=False)
  659. np.testing.assert_allclose(ax.get_xlim(), [1., 4.])
  660. def test_singleton_autolim():
  661. fig, ax = plt.subplots()
  662. ax.scatter(0, 0)
  663. np.testing.assert_allclose(ax.get_ylim(), [-0.06, 0.06])
  664. np.testing.assert_allclose(ax.get_xlim(), [-0.06, 0.06])
  665. @pytest.mark.parametrize("transform, expected", [
  666. ("transData", (-0.5, 3.5)),
  667. ("transAxes", (2.8, 3.2)),
  668. ])
  669. def test_autolim_with_zeros(transform, expected):
  670. # 1) Test that a scatter at (0, 0) data coordinates contributes to
  671. # autoscaling even though any(offsets) would be False in that situation.
  672. # 2) Test that specifying transAxes for the transform does not contribute
  673. # to the autoscaling.
  674. fig, ax = plt.subplots()
  675. ax.scatter(0, 0, transform=getattr(ax, transform))
  676. ax.scatter(3, 3)
  677. np.testing.assert_allclose(ax.get_ylim(), expected)
  678. np.testing.assert_allclose(ax.get_xlim(), expected)
  679. def test_quadmesh_set_array_validation(pcfunc):
  680. x = np.arange(11)
  681. y = np.arange(8)
  682. z = np.random.random((7, 10))
  683. fig, ax = plt.subplots()
  684. coll = getattr(ax, pcfunc)(x, y, z)
  685. with pytest.raises(ValueError, match=re.escape(
  686. "For X (11) and Y (8) with flat shading, A should have shape "
  687. "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (10, 7)")):
  688. coll.set_array(z.reshape(10, 7))
  689. z = np.arange(54).reshape((6, 9))
  690. with pytest.raises(ValueError, match=re.escape(
  691. "For X (11) and Y (8) with flat shading, A should have shape "
  692. "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (6, 9)")):
  693. coll.set_array(z)
  694. with pytest.raises(ValueError, match=re.escape(
  695. "For X (11) and Y (8) with flat shading, A should have shape "
  696. "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (54,)")):
  697. coll.set_array(z.ravel())
  698. # RGB(A) tests
  699. z = np.ones((9, 6, 3)) # RGB with wrong X/Y dims
  700. with pytest.raises(ValueError, match=re.escape(
  701. "For X (11) and Y (8) with flat shading, A should have shape "
  702. "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (9, 6, 3)")):
  703. coll.set_array(z)
  704. z = np.ones((9, 6, 4)) # RGBA with wrong X/Y dims
  705. with pytest.raises(ValueError, match=re.escape(
  706. "For X (11) and Y (8) with flat shading, A should have shape "
  707. "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (9, 6, 4)")):
  708. coll.set_array(z)
  709. z = np.ones((7, 10, 2)) # Right X/Y dims, bad 3rd dim
  710. with pytest.raises(ValueError, match=re.escape(
  711. "For X (11) and Y (8) with flat shading, A should have shape "
  712. "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (7, 10, 2)")):
  713. coll.set_array(z)
  714. x = np.arange(10)
  715. y = np.arange(7)
  716. z = np.random.random((7, 10))
  717. fig, ax = plt.subplots()
  718. coll = ax.pcolormesh(x, y, z, shading='gouraud')
  719. def test_polyquadmesh_masked_vertices_array():
  720. xx, yy = np.meshgrid([0, 1, 2], [0, 1, 2, 3])
  721. # 2 x 3 mesh data
  722. zz = (xx*yy)[:-1, :-1]
  723. quadmesh = plt.pcolormesh(xx, yy, zz)
  724. quadmesh.update_scalarmappable()
  725. quadmesh_fc = quadmesh.get_facecolor()[1:, :]
  726. # Mask the origin vertex in x
  727. xx = np.ma.masked_where((xx == 0) & (yy == 0), xx)
  728. polymesh = plt.pcolor(xx, yy, zz)
  729. polymesh.update_scalarmappable()
  730. # One cell should be left out
  731. assert len(polymesh.get_paths()) == 5
  732. # Poly version should have the same facecolors as the end of the quadmesh
  733. assert_array_equal(quadmesh_fc, polymesh.get_facecolor())
  734. # Mask the origin vertex in y
  735. yy = np.ma.masked_where((xx == 0) & (yy == 0), yy)
  736. polymesh = plt.pcolor(xx, yy, zz)
  737. polymesh.update_scalarmappable()
  738. # One cell should be left out
  739. assert len(polymesh.get_paths()) == 5
  740. # Poly version should have the same facecolors as the end of the quadmesh
  741. assert_array_equal(quadmesh_fc, polymesh.get_facecolor())
  742. # Mask the origin cell data
  743. zz = np.ma.masked_where((xx[:-1, :-1] == 0) & (yy[:-1, :-1] == 0), zz)
  744. polymesh = plt.pcolor(zz)
  745. polymesh.update_scalarmappable()
  746. # One cell should be left out
  747. assert len(polymesh.get_paths()) == 5
  748. # Poly version should have the same facecolors as the end of the quadmesh
  749. assert_array_equal(quadmesh_fc, polymesh.get_facecolor())
  750. # Setting array with 1D compressed values is deprecated
  751. with pytest.warns(mpl.MatplotlibDeprecationWarning,
  752. match="Setting a PolyQuadMesh"):
  753. polymesh.set_array(np.ones(5))
  754. # We should also be able to call set_array with a new mask and get
  755. # updated polys
  756. # Remove mask, should add all polys back
  757. zz = np.arange(6).reshape((3, 2))
  758. polymesh.set_array(zz)
  759. polymesh.update_scalarmappable()
  760. assert len(polymesh.get_paths()) == 6
  761. # Add mask should remove polys
  762. zz = np.ma.masked_less(zz, 2)
  763. polymesh.set_array(zz)
  764. polymesh.update_scalarmappable()
  765. assert len(polymesh.get_paths()) == 4
  766. def test_quadmesh_get_coordinates(pcfunc):
  767. x = [0, 1, 2]
  768. y = [2, 4, 6]
  769. z = np.ones(shape=(2, 2))
  770. xx, yy = np.meshgrid(x, y)
  771. coll = getattr(plt, pcfunc)(xx, yy, z)
  772. # shape (3, 3, 2)
  773. coords = np.stack([xx.T, yy.T]).T
  774. assert_array_equal(coll.get_coordinates(), coords)
  775. def test_quadmesh_set_array():
  776. x = np.arange(4)
  777. y = np.arange(4)
  778. z = np.arange(9).reshape((3, 3))
  779. fig, ax = plt.subplots()
  780. coll = ax.pcolormesh(x, y, np.ones(z.shape))
  781. # Test that the collection is able to update with a 2d array
  782. coll.set_array(z)
  783. fig.canvas.draw()
  784. assert np.array_equal(coll.get_array(), z)
  785. # Check that pre-flattened arrays work too
  786. coll.set_array(np.ones(9))
  787. fig.canvas.draw()
  788. assert np.array_equal(coll.get_array(), np.ones(9))
  789. z = np.arange(16).reshape((4, 4))
  790. fig, ax = plt.subplots()
  791. coll = ax.pcolormesh(x, y, np.ones(z.shape), shading='gouraud')
  792. # Test that the collection is able to update with a 2d array
  793. coll.set_array(z)
  794. fig.canvas.draw()
  795. assert np.array_equal(coll.get_array(), z)
  796. # Check that pre-flattened arrays work too
  797. coll.set_array(np.ones(16))
  798. fig.canvas.draw()
  799. assert np.array_equal(coll.get_array(), np.ones(16))
  800. def test_quadmesh_vmin_vmax(pcfunc):
  801. # test when vmin/vmax on the norm changes, the quadmesh gets updated
  802. fig, ax = plt.subplots()
  803. cmap = mpl.colormaps['plasma']
  804. norm = mpl.colors.Normalize(vmin=0, vmax=1)
  805. coll = getattr(ax, pcfunc)([[1]], cmap=cmap, norm=norm)
  806. fig.canvas.draw()
  807. assert np.array_equal(coll.get_facecolors()[0, :], cmap(norm(1)))
  808. # Change the vmin/vmax of the norm so that the color is from
  809. # the bottom of the colormap now
  810. norm.vmin, norm.vmax = 1, 2
  811. fig.canvas.draw()
  812. assert np.array_equal(coll.get_facecolors()[0, :], cmap(norm(1)))
  813. def test_quadmesh_alpha_array(pcfunc):
  814. x = np.arange(4)
  815. y = np.arange(4)
  816. z = np.arange(9).reshape((3, 3))
  817. alpha = z / z.max()
  818. alpha_flat = alpha.ravel()
  819. # Provide 2-D alpha:
  820. fig, (ax0, ax1) = plt.subplots(2)
  821. coll1 = getattr(ax0, pcfunc)(x, y, z, alpha=alpha)
  822. coll2 = getattr(ax0, pcfunc)(x, y, z)
  823. coll2.set_alpha(alpha)
  824. plt.draw()
  825. assert_array_equal(coll1.get_facecolors()[:, -1], alpha_flat)
  826. assert_array_equal(coll2.get_facecolors()[:, -1], alpha_flat)
  827. # Or provide 1-D alpha:
  828. fig, (ax0, ax1) = plt.subplots(2)
  829. coll1 = getattr(ax0, pcfunc)(x, y, z, alpha=alpha)
  830. coll2 = getattr(ax1, pcfunc)(x, y, z)
  831. coll2.set_alpha(alpha)
  832. plt.draw()
  833. assert_array_equal(coll1.get_facecolors()[:, -1], alpha_flat)
  834. assert_array_equal(coll2.get_facecolors()[:, -1], alpha_flat)
  835. def test_alpha_validation(pcfunc):
  836. # Most of the relevant testing is in test_artist and test_colors.
  837. fig, ax = plt.subplots()
  838. pc = getattr(ax, pcfunc)(np.arange(12).reshape((3, 4)))
  839. with pytest.raises(ValueError, match="^Data array shape"):
  840. pc.set_alpha([0.5, 0.6])
  841. pc.update_scalarmappable()
  842. def test_legend_inverse_size_label_relationship():
  843. """
  844. Ensure legend markers scale appropriately when label and size are
  845. inversely related.
  846. Here label = 5 / size
  847. """
  848. np.random.seed(19680801)
  849. X = np.random.random(50)
  850. Y = np.random.random(50)
  851. C = 1 - np.random.random(50)
  852. S = 5 / C
  853. legend_sizes = [0.2, 0.4, 0.6, 0.8]
  854. fig, ax = plt.subplots()
  855. sc = ax.scatter(X, Y, s=S)
  856. handles, labels = sc.legend_elements(
  857. prop='sizes', num=legend_sizes, func=lambda s: 5 / s
  858. )
  859. # Convert markersize scale to 's' scale
  860. handle_sizes = [x.get_markersize() for x in handles]
  861. handle_sizes = [5 / x**2 for x in handle_sizes]
  862. assert_array_almost_equal(handle_sizes, legend_sizes, decimal=1)
  863. @mpl.style.context('default')
  864. def test_color_logic(pcfunc):
  865. pcfunc = getattr(plt, pcfunc)
  866. z = np.arange(12).reshape(3, 4)
  867. # Explicitly set an edgecolor.
  868. pc = pcfunc(z, edgecolors='red', facecolors='none')
  869. pc.update_scalarmappable() # This is called in draw().
  870. # Define 2 reference "colors" here for multiple use.
  871. face_default = mcolors.to_rgba_array(pc._get_default_facecolor())
  872. mapped = pc.get_cmap()(pc.norm(z.ravel()))
  873. # GitHub issue #1302:
  874. assert mcolors.same_color(pc.get_edgecolor(), 'red')
  875. # Check setting attributes after initialization:
  876. pc = pcfunc(z)
  877. pc.set_facecolor('none')
  878. pc.set_edgecolor('red')
  879. pc.update_scalarmappable()
  880. assert mcolors.same_color(pc.get_facecolor(), 'none')
  881. assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
  882. pc.set_alpha(0.5)
  883. pc.update_scalarmappable()
  884. assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 0.5]])
  885. pc.set_alpha(None) # restore default alpha
  886. pc.update_scalarmappable()
  887. assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
  888. # Reset edgecolor to default.
  889. pc.set_edgecolor(None)
  890. pc.update_scalarmappable()
  891. assert np.array_equal(pc.get_edgecolor(), mapped)
  892. pc.set_facecolor(None) # restore default for facecolor
  893. pc.update_scalarmappable()
  894. assert np.array_equal(pc.get_facecolor(), mapped)
  895. assert mcolors.same_color(pc.get_edgecolor(), 'none')
  896. # Turn off colormapping entirely:
  897. pc.set_array(None)
  898. pc.update_scalarmappable()
  899. assert mcolors.same_color(pc.get_edgecolor(), 'none')
  900. assert mcolors.same_color(pc.get_facecolor(), face_default) # not mapped
  901. # Turn it back on by restoring the array (must be 1D!):
  902. pc.set_array(z)
  903. pc.update_scalarmappable()
  904. assert np.array_equal(pc.get_facecolor(), mapped)
  905. assert mcolors.same_color(pc.get_edgecolor(), 'none')
  906. # Give color via tuple rather than string.
  907. pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=(0, 1, 0))
  908. pc.update_scalarmappable()
  909. assert np.array_equal(pc.get_facecolor(), mapped)
  910. assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
  911. # Provide an RGB array; mapping overrides it.
  912. pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 3)))
  913. pc.update_scalarmappable()
  914. assert np.array_equal(pc.get_facecolor(), mapped)
  915. assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
  916. # Turn off the mapping.
  917. pc.set_array(None)
  918. pc.update_scalarmappable()
  919. assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 3)))
  920. assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
  921. # And an RGBA array.
  922. pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 4)))
  923. pc.update_scalarmappable()
  924. assert np.array_equal(pc.get_facecolor(), mapped)
  925. assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
  926. # Turn off the mapping.
  927. pc.set_array(None)
  928. pc.update_scalarmappable()
  929. assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 4)))
  930. assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
  931. def test_LineCollection_args():
  932. lc = LineCollection(None, linewidth=2.2, edgecolor='r',
  933. zorder=3, facecolors=[0, 1, 0, 1])
  934. assert lc.get_linewidth()[0] == 2.2
  935. assert mcolors.same_color(lc.get_edgecolor(), 'r')
  936. assert lc.get_zorder() == 3
  937. assert mcolors.same_color(lc.get_facecolor(), [[0, 1, 0, 1]])
  938. # To avoid breaking mplot3d, LineCollection internally sets the facecolor
  939. # kwarg if it has not been specified. Hence we need the following test
  940. # for LineCollection._set_default().
  941. lc = LineCollection(None, facecolor=None)
  942. assert mcolors.same_color(lc.get_facecolor(), 'none')
  943. def test_array_dimensions(pcfunc):
  944. # Make sure we can set the 1D, 2D, and 3D array shapes
  945. z = np.arange(12).reshape(3, 4)
  946. pc = getattr(plt, pcfunc)(z)
  947. # 1D
  948. pc.set_array(z.ravel())
  949. pc.update_scalarmappable()
  950. # 2D
  951. pc.set_array(z)
  952. pc.update_scalarmappable()
  953. # 3D RGB is OK as well
  954. z = np.arange(36, dtype=np.uint8).reshape(3, 4, 3)
  955. pc.set_array(z)
  956. pc.update_scalarmappable()
  957. def test_get_segments():
  958. segments = np.tile(np.linspace(0, 1, 256), (2, 1)).T
  959. lc = LineCollection([segments])
  960. readback, = lc.get_segments()
  961. # these should comeback un-changed!
  962. assert np.all(segments == readback)
  963. def test_set_offsets_late():
  964. identity = mtransforms.IdentityTransform()
  965. sizes = [2]
  966. null = mcollections.CircleCollection(sizes=sizes)
  967. init = mcollections.CircleCollection(sizes=sizes, offsets=(10, 10))
  968. late = mcollections.CircleCollection(sizes=sizes)
  969. late.set_offsets((10, 10))
  970. # Bbox.__eq__ doesn't compare bounds
  971. null_bounds = null.get_datalim(identity).bounds
  972. init_bounds = init.get_datalim(identity).bounds
  973. late_bounds = late.get_datalim(identity).bounds
  974. # offsets and transform are applied when set after initialization
  975. assert null_bounds != init_bounds
  976. assert init_bounds == late_bounds
  977. def test_set_offset_transform():
  978. skew = mtransforms.Affine2D().skew(2, 2)
  979. init = mcollections.Collection(offset_transform=skew)
  980. late = mcollections.Collection()
  981. late.set_offset_transform(skew)
  982. assert skew == init.get_offset_transform() == late.get_offset_transform()
  983. def test_set_offset_units():
  984. # passing the offsets in initially (i.e. via scatter)
  985. # should yield the same results as `set_offsets`
  986. x = np.linspace(0, 10, 5)
  987. y = np.sin(x)
  988. d = x * np.timedelta64(24, 'h') + np.datetime64('2021-11-29')
  989. sc = plt.scatter(d, y)
  990. off0 = sc.get_offsets()
  991. sc.set_offsets(list(zip(d, y)))
  992. np.testing.assert_allclose(off0, sc.get_offsets())
  993. # try the other way around
  994. fig, ax = plt.subplots()
  995. sc = ax.scatter(y, d)
  996. off0 = sc.get_offsets()
  997. sc.set_offsets(list(zip(y, d)))
  998. np.testing.assert_allclose(off0, sc.get_offsets())
  999. @image_comparison(baseline_images=["test_check_masked_offsets"],
  1000. extensions=["png"], remove_text=True, style="mpl20")
  1001. def test_check_masked_offsets():
  1002. # Check if masked data is respected by scatter
  1003. # Ref: Issue #24545
  1004. unmasked_x = [
  1005. datetime(2022, 12, 15, 4, 49, 52),
  1006. datetime(2022, 12, 15, 4, 49, 53),
  1007. datetime(2022, 12, 15, 4, 49, 54),
  1008. datetime(2022, 12, 15, 4, 49, 55),
  1009. datetime(2022, 12, 15, 4, 49, 56),
  1010. ]
  1011. masked_y = np.ma.array([1, 2, 3, 4, 5], mask=[0, 1, 1, 0, 0])
  1012. fig, ax = plt.subplots()
  1013. ax.scatter(unmasked_x, masked_y)
  1014. @check_figures_equal(extensions=["png"])
  1015. def test_masked_set_offsets(fig_ref, fig_test):
  1016. x = np.ma.array([1, 2, 3, 4, 5], mask=[0, 0, 1, 1, 0])
  1017. y = np.arange(1, 6)
  1018. ax_test = fig_test.add_subplot()
  1019. scat = ax_test.scatter(x, y)
  1020. scat.set_offsets(np.ma.column_stack([x, y]))
  1021. ax_test.set_xticks([])
  1022. ax_test.set_yticks([])
  1023. ax_ref = fig_ref.add_subplot()
  1024. ax_ref.scatter([1, 2, 5], [1, 2, 5])
  1025. ax_ref.set_xticks([])
  1026. ax_ref.set_yticks([])
  1027. def test_check_offsets_dtype():
  1028. # Check that setting offsets doesn't change dtype
  1029. x = np.ma.array([1, 2, 3, 4, 5], mask=[0, 0, 1, 1, 0])
  1030. y = np.arange(1, 6)
  1031. fig, ax = plt.subplots()
  1032. scat = ax.scatter(x, y)
  1033. masked_offsets = np.ma.column_stack([x, y])
  1034. scat.set_offsets(masked_offsets)
  1035. assert isinstance(scat.get_offsets(), type(masked_offsets))
  1036. unmasked_offsets = np.column_stack([x, y])
  1037. scat.set_offsets(unmasked_offsets)
  1038. assert isinstance(scat.get_offsets(), type(unmasked_offsets))
  1039. @pytest.mark.parametrize('gapcolor', ['orange', ['r', 'k']])
  1040. @check_figures_equal(extensions=['png'])
  1041. @mpl.rc_context({'lines.linewidth': 20})
  1042. def test_striped_lines(fig_test, fig_ref, gapcolor):
  1043. ax_test = fig_test.add_subplot(111)
  1044. ax_ref = fig_ref.add_subplot(111)
  1045. for ax in [ax_test, ax_ref]:
  1046. ax.set_xlim(0, 6)
  1047. ax.set_ylim(0, 1)
  1048. x = range(1, 6)
  1049. linestyles = [':', '-', '--']
  1050. ax_test.vlines(x, 0, 1, linestyle=linestyles, gapcolor=gapcolor, alpha=0.5)
  1051. if isinstance(gapcolor, str):
  1052. gapcolor = [gapcolor]
  1053. for x, gcol, ls in zip(x, itertools.cycle(gapcolor),
  1054. itertools.cycle(linestyles)):
  1055. ax_ref.axvline(x, 0, 1, linestyle=ls, gapcolor=gcol, alpha=0.5)