Repository navigation
Description
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:
- Requires the corresponding converter (
StrCategoryConverterin the above example) to handle >1d arrays on creation, for example by adding aravelorflattentovaluesinmatplotlib/lib/matplotlib/category.py
Line 57 in 37ef9f5
unit.update(values)
Note that the problem isn't actually withStrCategoryConverter, but instead with theUnitData.updatemethod; 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) - Explicitly setting the units, converter, locator, and formatter on the
axes.xaxis/axes.yaxisas 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. aLine2D.
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
rcomer commentedon Nov 27, 2026
Sorry if I've misunderstood, but this works for me with Matplotlib 3.10.9
SamWolski commentedon Nov 27, 2026
Sure, but this is still inconsistent behaviour processing 2D arrays, as numeric ones will work. If cat_values is instead
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
pcolormeshpage, 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)
rcomer commentedon Nov 28, 2026
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
pcolormeshmore 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
pcolormeshor categorical data, so probably best to wait for someone else to comment!jklymak commentedon Nov 28, 2026
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.
SamWolski commentedon Nov 30, 2026
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.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
StrCategoryConverterdoesn't. I don't see anything that is specific topcolormeshas 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.
pcolormeshhaving "partial" support for categorical data depending on the input array shape seems bizarre, as the underlying machinery is clearly there.story645 commentedon Nov 30, 2026
I don't think they are but what do you mean by this?
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.
SamWolski commentedon Nov 30, 2026
For my workaround I followed the codepath for the string/object array in the
pcolormeshcall and mimicked for example theaxis.set_unitscall, 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 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 fromunit._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)
jklymak commentedon Nov 30, 2026
You don't need to use
meshgridat 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.
SamWolski commentedon Nov 30, 2026
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 allpcolormeshfunctionality, 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:
pcolormeshdocumentation to explicitly state that categorical/string/object values are not supported for 2DXandYinputs.pcolormeshor more generally_pcolorargsor perhaps even_process_unit_info.jklymak commentedon Nov 30, 2026
I think the converter error message should definitely be better.
story645 commentedon Nov 30, 2026
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.
rcomer commentedon Nov 30, 2026
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
meshgridwithout realising they don’t need to.