Repository: matplotlib/matplotlib

Issue:
[Bug]: Incorrect pcolormesh when shading='nearest' and only the mesh data C is provided.
### Bug summary

The coloring of meshgrid of `plt.pcolormesh(C, shading='nearest')` is inconsistent with other types of shading, e.g., 'auto', 'flat', 'gouraud'.

### Code for reproduction

```Python
import numpy as np
import matplotlib.pyplot as plt
x, y = np.mgrid[0:11, 0:11]
C = x + y
plt.figure(figsize=(20, 5))
plt.subplot(151)
plt.pcolormesh(C, shading='nearest') # Incorrect Plot
plt.title('shading=nearest, without x, y')
plt.subplot(152)
plt.pcolormesh(x, y, C, shading='nearest') # Expected Plot
plt.title('shading=nearest, with x, y')
plt.subplot(153)
plt.pcolormesh(C, shading='auto')
plt.title('shading=auto, without x, y')
plt.subplot(154)
plt.pcolormesh(C, shading='flat')
plt.title('shading=flat, without x, y')
plt.subplot(155)
plt.pcolormesh(C, shading='gouraud')
plt.title('shading=gouraud, without x, y')
plt.show()
```


### Actual outcome

![test_pcolormesh_shading](https://github.com/user-attachments/assets/e284b003-66d9-412c-a1ba-c7eb3f8248fe)


### Expected outcome

![test_pcolormesh_shading_expected](https://github.com/user-attachments/assets/757a8d00-5469-41c0-8aa1-b029ee46a128)


### Additional information

This bug happens when only the mesh data C is provided, and using `shading = 'nearest'`.

### Operating system

_No response_

### Matplotlib Version

3.9.2

### Matplotlib Backend

_No response_

### Python version

_No response_

### Jupyter version

_No response_

### Installation

None


Discussion:
Thanks for the clear report @smith2936.  I have reproduced this with our `main` development branch.  I also note that if you do

```
plt.pcolor(C, shading='nearest')
```
you get an error.

If `X` and `Y` are provided the ['nearest' option gets translated to 'flat'](https://github.com/matplotlib/matplotlib/blob/b1d2ecd09bfee53cf2eddd95920d679c508be5b8/lib/matplotlib/axes/_axes.py#L5976-L6009), so I suspect the easiest fix will be to also replace 'nearest' with 'flat' in the [loop that checks whether X/Y was set](https://github.com/matplotlib/matplotlib/blob/b1d2ecd09bfee53cf2eddd95920d679c508be5b8/lib/matplotlib/axes/_axes.py#L5918-L5927).

I think this is a Good First Issue because the scope is limited.
### Good first issue - notes for new contributors

This issue is suited to new contributors because it does not require understanding of the
Matplotlib internals. To get started, please see our [contributing
guide](https://matplotlib.org/stable/devel/index).

**We do not assign issues**. Check the *Development* section in the sidebar for linked pull
requests (PRs). If there are none, feel free to start working on it. If there is an open PR, please
collaborate on the work by reviewing it rather than duplicating it in a competing PR.

If something is unclear, please reach out on any of our [communication
channels](https://matplotlib.org/stable/devel/contributing.html#get-connected).
@rcomer 
i guess this chnage can fix the issue
``` python
 if len(args) == 1:
            C = np.asanyarray(args[0])
            nrows, ncols = C.shape[:2]
            if shading in ['gouraud', 'nearest']:
                if shading == 'nearest':
                    X = np.arange(C.shape[1])  # Create x array based on the number of columns
                    Y = np.arange(C.shape[0])  # Create y array based on the number of rows
                else:
                     X, Y = np.meshgrid(np.arange(ncols), np.arange(nrows))

            else:
                X, Y = np.meshgrid(np.arange(ncols + 1), np.arange(nrows + 1))
                shading = 'flat'
            C = cbook.safe_masked_invalid(C, copy=True)
            return X, Y, C, shading
 ```
Hi user @saikarna913, thank you for your contribution. We are also a team of new contributors and are more than happy to test your code. We will get back to you as soon as possible. If this solution does not work, we can also work on this and see if there is opportunity for collaboration. Thank you.
This took me a while to parse what is going on, but the proposed fixes so far are not correct.  The OP made this complicated by flipping x and y; `np.mgrid` unfortunately uses the transposed matrix order from what `np.meshgrid` uses.  For problems like this, it is very helpful to make x and y different lengths so it is clear what data is being plotted.  

```python
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(4)
y = np.arange(7)
X, Y = np.meshgrid(x, y)
C = X + Y
plt.figure(figsize=(7, 5))
plt.subplot(131)
print('shading=nearest, without x, y')

plt.pcolormesh(C, shading='nearest') # Incorrect Plot
plt.title('shading=nearest, without x, y')
plt.subplot(132)

print('shading=nearest, with x, y')
plt.pcolormesh(x, y, C, shading='nearest') # Expected Plot
plt.title('shading=nearest, with x, y')

plt.subplot(133)
print('shading=flat, with x, y')
plt.pcolormesh(C, shading='flat') # Expected Plot
plt.title('shading=flat, without x, y')
plt.show()
```

I think the correct fix is 

```diff
diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py
index f6a4ebfdc7..cc4322e58e 100644
--- a/lib/matplotlib/axes/_axes.py
+++ b/lib/matplotlib/axes/_axes.py
@@ -5923,10 +5923,8 @@ class Axes(_AxesBase):
             else:
                 X, Y = np.meshgrid(np.arange(ncols + 1), np.arange(nrows + 1))
                 shading = 'flat'
-            C = cbook.safe_masked_invalid(C, copy=True)
-            return X, Y, C, shading
 
-        if len(args) == 3:
+        elif len(args) == 3:
             # Check x and y for bad data...
             C = np.asanyarray(args[2])
             # unit conversion allows e.g. datetime objects as axis values
```




Patch:
diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py
index c55f77811859..7ca3a7da3878 100644
--- a/lib/matplotlib/axes/_axes.py
+++ b/lib/matplotlib/axes/_axes.py
@@ -5923,10 +5923,7 @@ def _pcolorargs(self, funcname, *args, shading='auto', **kwargs):
             else:
                 X, Y = np.meshgrid(np.arange(ncols + 1), np.arange(nrows + 1))
                 shading = 'flat'
-            C = cbook.safe_masked_invalid(C, copy=True)
-            return X, Y, C, shading
-
-        if len(args) == 3:
+        elif len(args) == 3:
             # Check x and y for bad data...
             C = np.asanyarray(args[2])
             # unit conversion allows e.g. datetime objects as axis values


Test patch:
diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py
index 62eb491aa4bb..f952eaa90af1 100644
--- a/lib/matplotlib/tests/test_axes.py
+++ b/lib/matplotlib/tests/test_axes.py
@@ -1499,6 +1499,20 @@ def test_pcolormesh_rgba(fig_test, fig_ref, dims, alpha):
     ax.pcolormesh(c[..., 0], cmap="gray", vmin=0, vmax=1, alpha=alpha)
 
 
+@check_figures_equal(extensions=["png"])
+def test_pcolormesh_nearest_noargs(fig_test, fig_ref):
+    x = np.arange(4)
+    y = np.arange(7)
+    X, Y = np.meshgrid(x, y)
+    C = X + Y
+
+    ax = fig_test.subplots()
+    ax.pcolormesh(C, shading="nearest")
+
+    ax = fig_ref.subplots()
+    ax.pcolormesh(x, y, C, shading="nearest")
+
+
 @image_comparison(['pcolormesh_datetime_axis.png'], style='mpl20')
 def test_pcolormesh_datetime_axis():
     # Remove this line when this test image is regenerated.