Skip to content

[ENH]: Handle categorical/string data as x/y in pcolormesh #32678

Backlog

Description

@SamWolski

Problem

Categorical data is currently not accepted by pcolormesh, as X and Y arrays must be 2D to explicitly specify coordinate points.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

## Generate data
rng = np.random.default_rng()
x_values = pd.Series(np.linspace(0.0, 1.0, 251), name="x").to_frame()
cat_values = pd.Series(["abc", "pqr", "xyz"], name="cat", dtype="category").to_frame()
## Long-form coordinate grid with cross-merge
data = x_values.merge(cat_values, how="cross")
data["z"] = rng.random(size=len(data))

## Long-to-wide pivot for coordinate grid
## Result is 2D numpy arrays, as intended by pcolormesh
pivot_df = data.pivot(index="cat", columns="x", values="z")
x_data, y_data = np.meshgrid(
	pivot_df.columns.values,
	pivot_df.index.values,
)
## z values as a 2D grid
z_data = pivot_df.values

fig, axes = plt.subplots(1,1)
axes.pcolormesh(x_data, y_data, z_data)
plt.show()

The above code fails with TypeError: unhashable type: 'numpy.ndarray' when attempting to create a UnitData object to set up the axis converter.

Expected result is the same behaviour as categorical data on eg. a lineplot: correct axis labeling (using object strings), and mouseover coordinates also showing the object string rather than its numerical equivalent.

Proposed solution

I was able to get it to work with the following steps:

  1. Requires the corresponding converter (StrCategoryConverter in the above example) to handle >1d arrays on creation, for example by adding a ravel or flatten to values in
    unit.update(values)

    Note that the problem isn't actually with StrCategoryConverter, but instead with the UnitData.update method; the fix can in principle go in either.
    (Would this be a massive breaking change? Other simple plots seemed to work fine with this modification, but perhaps there are edge cases I'm not familiar with)
  2. Explicitly setting the units, converter, locator, and formatter on the axes.xaxis/axes.yaxis as applicable. I haven't looked into the details of where exactly this should be done in the matplotlib code, but I'm hoping it follows a similar structure to when constructing eg. a Line2D.

In my own code, I am currently subclassing StrCategoryConverter with a reimplementation of the convert static method, and using it along with the other relevant classes as-is for explicitly setting the required properties in (2.).

I would like to implement this, but I wanted to check if there is anything here I may have missed or if I'm unaware of something that runs counter to some design philosophy of some of these backend objects.

Activity

  1. rcomer commented on Nov 27, 2026

    @rcomer
    Member

    Sorry if I've misunderstood, but this works for me with Matplotlib 3.10.9

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = ['a', 'b', 'c']
    y = ['foo', 'bar']
    d = np.random.random((2, 3))
    
    plt.pcolormesh(x, y, d)
    plt.show()
    image
  2. SamWolski commented on Nov 27, 2026

    @SamWolski
    Author

    Sure, but this is still inconsistent behaviour processing 2D arrays, as numeric ones will work. If cat_values is instead

    cat_values = pd.Series([0,1,2], name="cat").to_frame()
    

    everything works as expected.

    If for some reason it isn't feasible to change it, I think at the very least the documentation (I can't find anything about it on the pcolormesh page, or anywhere else for that matter) and the (in this context) cryptic error message should be improved.

    (To be clear, I understand that the workaround in this specific case is to take the x and y arrays from the pivot df columns and indices, but the error still hits you out of nowhere if you don't know exactly what to look for)

  3. rcomer commented on Nov 28, 2026

    @rcomer
    Member

    Sorry, I'm unfamiliar with pandas, so I am not quite following. Are you saying that pandas naturally gives you 2D string arrays, so it's more convenient to pass those?

    I think this would need some thought about what happens if the y-values vary in the x direction and vice versa. In your example they don't, so everything lines up nicely. For pcolormesh more generally, the quadrilaterals do not have to be rectangular, so numerical x and y could vary in both directions.

    That said, I am not the expert in either pcolormesh or categorical data, so probably best to wait for someone else to comment!

  4. jklymak commented on Nov 28, 2026

    @jklymak
    Member

    Agree with @rcomer that it doesn't make much sense to have 2-D X and Y for categoricals. What were you trying to achieve with this?

    I'd be against any special handling for this, but a better error message in the converter seems reasonable. Or if someone wanted to reduce x and y in the converter that would be ok too, but I'm skeptical you'd have a reasonable inference for all potential (mis) use cases.

    As @rcomer indicates, the reason numerical arrays work is that pcolromesh supports distorted vertices. But those don't make any sense for categorical x and y.

  5. SamWolski commented on Nov 30, 2026

    @SamWolski
    Author

    it doesn't make much sense to have 2-D X and Y for categoricals. What were you trying to achieve with this?

    I have code that handles drawing semantically irrespectively of the datatype: a middleware pipeline marshalling database-style rows into whatever works best for the plotting functions, here it's into 2D using np.meshgrid, but the generality breaks here with categorical data.

    the reason numerical arrays work is that pcolromesh supports distorted vertices.

    Well, I haven't investigated the numeric code path more but I imagine either the axis units aren't reset or the (default?) numerical converter handles higher-dimensional arrays, and the StrCategoryConverter doesn't. I don't see anything that is specific to pcolormesh as far as I'm aware, just the fact that it accepts 2D arguments where most other functions (plot, scatter, etc.) don't.

    Of course there are workarounds for the determined as with any software ever, but that's not an excuse to have an inconsistent interface. pcolormesh having "partial" support for categorical data depending on the input array shape seems bizarre, as the underlying machinery is clearly there.

  6. story645 commented on Nov 30, 2026

    @story645
    Member

    either the axis units aren't reset

    I don't think they are but what do you mean by this?

    numerical converter handles higher-dimensional arrays, and the StrCategoryConverter doesn't

    in theory it's supposed to work w/ arbitrary dims but it could very much be broken/under tested/the unitData.update should match the convert.

    https://github.com/matplotlib/matplotlib/blob/main/lib%2Fmatplotlib%2Fcategory.py#L58-L59

    I dunno how this aligns w/ your plan, but I've been thinking for a while that the categorical code should use numpy string arrays as the "ArrayLike"/input expectation.

  7. SamWolski commented on Nov 30, 2026

    @SamWolski
    Author

    either the axis units aren't reset

    For my workaround I followed the codepath for the string/object array in the pcolormesh call and mimicked for example the axis.set_units call, but I wasn't 100% sure what the corresponding actions for the numeric array are and I didn't want to be confidently incorrect ;)

    in theory it's supposed to work w/ arbitrary dims but it could very much be broken/under tested/the unitData.update should match the convert.

    In the hacky solution where I modified the matplotlib internals, I noticed that if the unit.update(values) call is successful, everything else follows. In particular, the next lines (https://github.com/matplotlib/matplotlib/blob/main/lib%2Fmatplotlib%2Fcategory.py#L58-L59) work fine with the numeric type because they are already using the mapped values from unit._mapping (ie "abc" -> 0, "pqr" -> 1, etc.), and the same applies for all further code.

    That's what I mean when I say the underlying machinery is already there: all the other code accepts the string/object array or the converted numeric array as applicable, it seems to literally just be this one unit update call in the converter that's causing the problem. (Well, that and the fact that the appropriate tick locator and formatter are not set, but this already works fine for other plot types so should be implementable in principle)

  8. jklymak commented on Nov 30, 2026

    @jklymak
    Member

    here it's into 2D using np.meshgrid, but the generality breaks here with categorical data.

    You don't need to use meshgrid at all for any data types if all you are doing are pulling a couple of 1-D rows x and y from a pandas table -- Matplotlib handles those fine. The only reason to pass X and Y as 2-D arrays is if X varies from column to column, and Y varies from row to row.

    We could do a song and dance to deal with 2D categorical X and Y, but I don't think there is a reasonable use case for this.

  9. SamWolski commented on Nov 30, 2026

    @SamWolski
    Author

    Sure, that's fair. It's a little annoying for at least one person (me) who inferred from the documentation and examples that the meshgrid/2D inputs allow for general access to the superset of all pcolormesh functionality, but I understand we want to be cautious about messing with existing internals.

    I guess it then becomes a question of clarifying things for anyone who follows my reasoning in the future:

    1. Updating the pcolormesh documentation to explicitly state that categorical/string/object values are not supported for 2D X and Y inputs.
    2. Issuing a meaningful error message for when someone does use the 2D inputs for categorical data. I suspect the best way to do it would be an explicit check in pcolormesh or more generally _pcolorargs or perhaps even _process_unit_info.
  10. jklymak commented on Nov 30, 2026

    @jklymak
    Member

    I think the converter error message should definitely be better.

  11. story645 commented on Nov 30, 2026

    @story645
    Member

    it seems to literally just be this one unit update call in the converter that's causing the problem

    Is this a small fix? To me it doesn't sound like you'd have to do a whole song and dance; rather this reads like a flaw in how unit data.update was implemented b/c it should work on any data convert works on.

  12. rcomer commented on Nov 30, 2026

    @rcomer
    Member

    The docstring is very focused on the 2D case for x and y, with just one line at the end mentioning that 1D arrays are automatically expanded. It’s plausible that a lot of users are calling meshgrid without realising they don’t need to.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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