{"record":{"id":"5c8132b6f47631b5","repo":"matplotlib/matplotlib","slug":"input-could-not-be-cast-to-an-at-least-1d-numpy-ar","errorCode":null,"errorMessage":"Input could not be cast to an at-least-1D NumPy array","messagePattern":"Input could not be cast to an at-least-1D NumPy array","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"lib/matplotlib/cbook.py","lineNumber":1772,"sourceCode":"    y : float or array-like\n\n    Returns\n    -------\n    x, y : ndarray\n       The x and y values to plot.\n    \"\"\"\n    try:\n        return y.index.to_numpy(), y.to_numpy()\n    except AttributeError:\n        pass\n    try:\n        y = _check_1d(y)\n    except (VisibleDeprecationWarning, ValueError):\n        # NumPy 1.19 will warn on ragged input, and we can't actually use it.\n        pass\n    else:\n        return np.arange(y.shape[0], dtype=float), y\n    raise ValueError('Input could not be cast to an at-least-1D NumPy array')\n\n\ndef safe_first_element(obj):\n    \"\"\"\n    Return the first element in *obj*.\n\n    This is a type-independent way of obtaining the first element,\n    supporting both index access and the iterator protocol.\n    \"\"\"\n    if isinstance(obj, collections.abc.Iterator):\n        # needed to accept `array.flat` as input.\n        # np.flatiter reports as an instance of collections.Iterator but can still be\n        # indexed via []. This has the side effect of re-setting the iterator, but\n        # that is acceptable.\n        try:\n            return obj[0]\n        except TypeError:\n            pass","sourceCodeStart":1754,"sourceCodeEnd":1790,"githubUrl":"https://github.com/matplotlib/matplotlib/blob/b379c1b69e012b142c0f496a52bcb30513802d72/lib/matplotlib/cbook.py#L1754-L1790","documentation":"Raised by cbook.index_of, which matplotlib uses to synthesize x-coordinates when only y-data is given (e.g. ax.plot(y)). It first tries the pandas path (y.index/y.values), then _check_1d to coerce y to a 1D NumPy array; if that conversion raises (ragged nested input, object NumPy cannot coerce), the ValueError is raised as the final answer. It means the y argument is not representable as a single flat numeric array.","triggerScenarios":"ax.plot(y) / APIs that call cbook.index_of with y = [[1, 2], [3, 4, 5]] (ragged nested list), a sequence of unequal-length sequences, an object with no .index and no ndarray coercion, or heterogeneous data that NumPy >= 1.24 refuses to convert (ragged creation changed from deprecation warning to hard ValueError).","commonSituations":"Plotting variable-length windows/batches in one call; upgrading NumPy past 1.24 so old ragged-input deprecation warnings become this error; passing dict views or custom container objects where a flat list/ndarray was expected.","solutions":["Plot each variable-length series in its own ax.plot call","Flatten uniform nested data with np.ravel(y) before plotting","Coerce and validate explicitly first: y = np.asarray(y, dtype=float)","For pandas-like objects pass x explicitly (ax.plot(df.index, df[col])) so index_of is bypassed"],"exampleFix":"# before\nax.plot([[1, 2], [3, 4, 5]])  # ragged: cannot cast to 1D\n\n# after\nfor series in [[1, 2], [3, 4, 5]]:\n    ax.plot(series)","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef plot_ready_1d(y):\n    try:\n        arr = np.asarray(y)\n    except (ValueError, TypeError) as e:\n        return False, f'not convertible to ndarray: {e}'\n    if arr.ndim < 1:\n        return False, 'input is 0-dimensional'\n    if arr.dtype == object:\n        return False, 'object dtype (ragged?) input'\n    return True, 'ok'\n\nok, why = plot_ready_1d(data)\nif ok:\n    ax.plot(data)\nelse:\n    for series in data:  # ragged: plot series by series\n        ax.plot(series)","typeGuard":"import numpy as np\n\ndef is_plottable_1d(y) -> bool:\n    try:\n        a = np.asarray(y)\n    except Exception:\n        return False\n    return a.ndim >= 1 and a.dtype != object","tryCatchPattern":"try:\n    ax.plot(data)\nexcept ValueError as e:\n    if 'could not be cast' in str(e):\n        for series in data:\n            ax.plot(series)  # fall back to per-series plotting\n    else:\n        raise","preventionTips":["Never plot ragged nested lists in one call; issue one plot per series","Normalize data with np.asarray(..., dtype=float) and assert ndim == 1 upstream","Be aware NumPy >= 1.24 turns ragged conversion warnings into hard errors"],"tags":["matplotlib","numpy","ragged-array","data-shape","valueerror"],"backgroundTag":"invalid-input-shape","analyzedSha":"b379c1b69e012b142c0f496a52bcb30513802d72","analyzedAt":"2026-08-21T23:31:55.468Z","schemaVersion":2},"datasetVersion":"2026-08-22T04:17:13.399Z"}