Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Bug]: plt.pcolormesh crashes when called with Int64 nullable dtype #23991

Copy link
Copy link
Open
@mojones

Description

@mojones
Issue body actions

Bug summary

When calling plt.pcolormesh with a dataframe containing either of the pandas nullable dtypes (Int64 or Float64) it crashes.

Code for reproduction

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({
    'foo' : [1,2],
    'bar' : [3,np.nan]
    })

# works as expected
plt.pcolormesh(df)

# crashes
plt.pcolormesh(df.astype('Int64'))

Actual outcome

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [28], in <cell line: 13>()
     10 plt.pcolormesh(df)
     12 # crashes
---> 13 plt.pcolormesh(df.astype('Int64'))

File ~/.virtualenvs/teaching/lib/python3.10/site-packages/matplotlib/pyplot.py:2728, in pcolormesh(alpha, norm, cmap, vmin, vmax, shading, antialiased, data, *args, **kwargs)
   2723 @_copy_docstring_and_deprecators(Axes.pcolormesh)
   2724 def pcolormesh(
   2725         *args, alpha=None, norm=None, cmap=None, vmin=None,
   2726         vmax=None, shading=None, antialiased=False, data=None,
   2727         **kwargs):
-> 2728     __ret = gca().pcolormesh(
   2729         *args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
   2730         vmax=vmax, shading=shading, antialiased=antialiased,
   2731         **({"data": data} if data is not None else {}), **kwargs)
   2732     sci(__ret)
   2733     return __ret

File ~/.virtualenvs/teaching/lib/python3.10/site-packages/matplotlib/__init__.py:1414, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs)
   1411 @functools.wraps(func)
   1412 def inner(ax, *args, data=None, **kwargs):
   1413     if data is None:
-> 1414         return func(ax, *map(sanitize_sequence, args), **kwargs)
   1416     bound = new_sig.bind(ax, *args, **kwargs)
   1417     auto_label = (bound.arguments.get(label_namer)
   1418                   or bound.kwargs.get(label_namer))

File ~/.virtualenvs/teaching/lib/python3.10/site-packages/matplotlib/axes/_axes.py:6072, in Axes.pcolormesh(self, alpha, norm, cmap, vmin, vmax, shading, antialiased, *args, **kwargs)
   6068 C = C.ravel()
   6070 kwargs.setdefault('snap', rcParams['pcolormesh.snap'])
-> 6072 collection = mcoll.QuadMesh(
   6073     coords, antialiased=antialiased, shading=shading,
   6074     array=C, cmap=cmap, norm=norm, alpha=alpha, **kwargs)
   6075 collection._scale_norm(norm, vmin, vmax)
   6076 self._pcolor_grid_deprecation_helper()

File ~/.virtualenvs/teaching/lib/python3.10/site-packages/matplotlib/collections.py:2015, in QuadMesh.__init__(self, *args, **kwargs)
   2012 self._bbox.update_from_data_xy(self._coordinates.reshape(-1, 2))
   2013 # super init delayed after own init because array kwarg requires
   2014 # self._coordinates and self._shading
-> 2015 super().__init__(**kwargs)
   2016 self.mouseover = False

File ~/.virtualenvs/teaching/lib/python3.10/site-packages/matplotlib/collections.py:217, in Collection.__init__(self, edgecolors, facecolors, linewidths, linestyles, capstyle, joinstyle, antialiaseds, offsets, transOffset, norm, cmap, pickradius, hatch, urls, zorder, **kwargs)
    214 self._transOffset = transOffset
    216 self._path_effects = None
--> 217 self.update(kwargs)
    218 self._paths = None

File ~/.virtualenvs/teaching/lib/python3.10/site-packages/matplotlib/artist.py:1069, in Artist.update(self, props)
   1066             if not callable(func):
   1067                 raise AttributeError(f"{type(self).__name__!r} object "
   1068                                      f"has no property {k!r}")
-> 1069             ret.append(func(v))
   1070 if ret:
   1071     self.pchanged()

File ~/.virtualenvs/teaching/lib/python3.10/site-packages/matplotlib/collections.py:2077, in QuadMesh.set_array(self, A)
   2072     if faulty_data:
   2073         raise TypeError(
   2074             f"Dimensions of A {A.shape} are incompatible with "
   2075             f"X ({width}) and/or Y ({height})")
-> 2077 return super().set_array(A)

File ~/.virtualenvs/teaching/lib/python3.10/site-packages/matplotlib/cm.py:477, in ScalarMappable.set_array(self, A)
    475 A = cbook.safe_masked_invalid(A, copy=True)
    476 if not np.can_cast(A.dtype, float, "same_kind"):
--> 477     raise TypeError(f"Image data of dtype {A.dtype} cannot be "
    478                     "converted to float")
    480 self._A = A

TypeError: Image data of dtype object cannot be converted to float

Expected outcome

image

Additional information

Noticed via seaborn mwaskom/seaborn#3042.

Operating system

lubuntu

Matplotlib Version

3.5.3

Matplotlib Backend

module://matplotlib_inline.backend_inline

Python version

3.10.4

Jupyter version

6.4.12

Installation

pip

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.