{"record":{"id":"0b1390ba316d2a59","repo":"matplotlib/matplotlib","slug":"collections-can-only-map-rank-1-arrays","errorCode":null,"errorMessage":"Collections can only map rank 1 arrays","messagePattern":"Collections can only map rank 1 arrays","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"lib/matplotlib/collections.py","lineNumber":1025,"sourceCode":"        changed = (edge0 is None or face0 is None\n                   or self._edge_is_mapped != edge0\n                   or self._face_is_mapped != face0)\n        return mapped or changed\n\n    def update_scalarmappable(self):\n        \"\"\"\n        Update colors from the scalar mappable array, if any.\n\n        Assign colors to edges and faces based on the array and/or\n        colors that were directly set, as appropriate.\n        \"\"\"\n        if not self._set_mappable_flags():\n            return\n        # Allow possibility to call 'self.set_array(None)'.\n        if self._A is not None:\n            # QuadMesh can map 2d arrays (but pcolormesh supplies 1d array)\n            if self._A.ndim > 1 and not isinstance(self, _MeshData):\n                raise ValueError('Collections can only map rank 1 arrays')\n            if np.iterable(self._alpha):\n                if self._alpha.size != self._A.size:\n                    raise ValueError(\n                        f'Data array shape, {self._A.shape} '\n                        'is incompatible with alpha array shape, '\n                        f'{self._alpha.shape}. '\n                        'This can occur with the deprecated '\n                        'behavior of the \"flat\" shading option, '\n                        'in which a row and/or column of the data '\n                        'array is dropped.')\n                # pcolormesh, scatter, maybe others flatten their _A\n                self._alpha = self._alpha.reshape(self._A.shape)\n            self._mapped_colors = self.to_rgba(self._A, self._alpha)\n\n        if self._face_is_mapped:\n            self._facecolors = self._mapped_colors\n        else:\n            self._set_facecolor(self._original_facecolor)","sourceCodeStart":1007,"sourceCodeEnd":1043,"githubUrl":"https://github.com/matplotlib/matplotlib/blob/b379c1b69e012b142c0f496a52bcb30513802d72/lib/matplotlib/collections.py#L1007-L1043","documentation":"Collection.update_scalarmappable maps the mappable array (_A) through the colormap at draw time. Regular collections (LineCollection, PolyCollection, PathCollection) accept only rank-1 arrays — one value per element; if _A.ndim > 1 and the class is not a _MeshData subclass (QuadMesh, supplied 1D by pcolormesh), it raises ValueError.","triggerScenarios":"coll = LineCollection(...); coll.set_array(np.zeros((10, 10))); then any draw, colorbar, or autoscale triggers update_scalarmappable. Also passing a (N,1) column array instead of (N,) to a collection's set_array.","commonSituations":"Porting pcolormesh/imshow-style 2D gridded data onto a generic collection; custom Collection subclasses expected to behave like a mesh; forgetting that scatter flattens c for you while direct set_array does not.","solutions":["Flatten the array: coll.set_array(arr.ravel())","Keep genuinely 2D fields on QuadMesh/pcolormesh or imshow, which are built for them","Check the flattened length matches the number of elements: len(coll.get_paths()) or coll.get_offsets()"],"exampleFix":"# before\ncoll.set_array(np.zeros((10, 10)))\n\n# after\ncoll.set_array(np.zeros((10, 10)).ravel())","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef set_array_1d(coll, arr):\n    a = np.asarray(arr)\n    if a.ndim != 1:\n        a = a.ravel()\n    coll.set_array(a)\n\nset_array_1d(coll, np.zeros((10, 10)))","typeGuard":"import numpy as np\n\ndef is_rank1(a) -> bool:\n    return getattr(a, 'ndim', 1) == 1","tryCatchPattern":"try:\n    coll.set_array(arr); fig.canvas.draw()\nexcept ValueError as e:\n    if 'rank 1' in str(e):\n        coll.set_array(np.asarray(arr).ravel())\n    else:\n        raise","preventionTips":["ravel() arrays before set_array on collections","Use pcolormesh/imshow for 2D fields instead of generic collections","Match the flattened length to the number of paths/offsets in the collection"],"tags":["matplotlib","collections","set-array","array-shape","valueerror"],"backgroundTag":"array-dimensionality-mismatch","analyzedSha":"b379c1b69e012b142c0f496a52bcb30513802d72","analyzedAt":"2026-08-21T23:31:55.468Z","schemaVersion":2},"datasetVersion":"2026-08-22T04:17:13.399Z"}