Repository: matplotlib/matplotlib
Pull request: warning when scatter plot color settings discarded
## PR Summary
first pr, happy to add/make any necessary changes
closes #23487

The changed test in `test_colorbar.py` was related removing a colorbar from a scatter plot. I don't think the `cmap` there was necessary to test this. And running the tests on my own revealed the `cmap` wasn't changing the color of the scatter plot anyways
## PR Checklist

<!-- Please mark any checkboxes that do not apply to this PR as [N/A]. -->
**Tests and Styling**
- [x] Has pytest style unit tests (and `pytest` passes).
- [x] Is [Flake 8](https://flake8.pycqa.org/en/latest/) compliant (install `flake8-docstrings` and run `flake8 --docstring-convention=all`).

**Documentation**
- [N/A] New features are documented, with examples if plot related.
- [N/A] New features have an entry in `doc/users/next_whats_new/` (follow instructions in README.rst there).
- [x] API changes documented in `doc/api/next_api_changes/` (follow instructions in README.rst there).
- [N/A] Documentation is sphinx and numpydoc compliant (the docs should [build](https://matplotlib.org/devel/documenting_mpl.html#building-the-docs) without error).

<!--
Thank you so much for your PR!  To help us review your contribution, please
consider the following points:

- A development guide is available at https://matplotlib.org/devdocs/devel/index.html.

- Help with git and github is available at
  https://matplotlib.org/devel/gitwash/development_workflow.html.

- Do not create the PR out of main, but out of a separate branch.

- The PR title should summarize the changes, for example "Raise ValueError on
  non-numeric input to set_xlim".  Avoid non-descriptive titles such as
  "Addresses issue #8576".

- The summary should provide at least 1-2 sentences describing the pull request
  in detail (Why is this change required?  What problem does it solve?) and
  link to any relevant issues.

- If you are contributing fixes to docstrings, please pay attention to
  http://matplotlib.org/devel/documenting_mpl.html#formatting.  In particular,
  note the difference between using single backquotes, double backquotes, and
  asterisks in the markup.

We understand that PRs can sometimes be overwhelming, especially as the
reviews start coming in.  Please let us know if the reviews are unclear or
the recommended next step seems overly demanding, if you would like help in
addressing a reviewer's comments, or if you have been waiting too long to hear
back on your PR.
-->


Problem statement:
[Bug]: scatter plot color settings discarded unless c given
### Bug summary

When making an animation of a scatter plot, if you don't set `c` (the color value parameter) when initializing the artist, the color settings are ignored.

### Code for reproduction

```python
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
pts = ax.scatter([], [], cmap="gray")
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

def update(i):
    pts.set_offsets(np.random.rand(100, 2))
    pts.set_array(np.random.rand(100))

ani = animation.FuncAnimation(fig, func=update, frames=range(10))
plt.show()
```


### Actual outcome

Even though `cmap="gray"` is passed to `scatter`, the points use the default "viridis" color map.

### Expected outcome

I would expect the points to use the "gray" color map.

### Additional information

If you modify the above code to use:
```python
pts = ax.scatter([], [], c=[], cmap="gray")
```
it works as expected. It seems like all color-related settings, including cmap, vmin, vmax, etc. are discarded unless `c` is given during the first call to `scatter`. 

This workaround (passing an empty `c`) isn't problematic, but I found the default behavior quite unintuitive and it took me the better part of a day to figure out what was happening, so I figured it would be worth reporting.

Possible solutions:

* Raise an error/warning if `cmap`/`vmin`/`vmax` are given but `c` is not
* Store parameters like `cmap`/`vmin`/`vmax` even if they aren't immediately used

These changes should probably happen in `_parse_scatter_color_args` in `lib/matplotlib/axes/_axes.py`. According to `git blame`, @timhoffm @anntzer wrote most of this logic.

### Operating system

macOS 12.4

### Matplotlib Version

3.5.2

### Matplotlib Backend

MacOSX

### Python version

3.9.13

### Jupyter version

N/A

### Installation

from source (.tar.gz)

Hints from issue discussion:
Thank you for diagnosing and reporting this @adamjstewart 

> Raise an error/warning if cmap/vmin/vmax are given but c is not

I think this is the better option of the two.   It will capture some unintentional usage and I think will be less surprising in the long run.

https://github.com/matplotlib/matplotlib/blob/1e4bc521dd14535711ac2dd0142adb147a1ba251/lib/matplotlib/axes/_axes.py#L4557-L4561 is probably the right place to put the check and warning (which we should make an error in the future).


I think this is a good first issue because it does involve a little bit of API design, I do not think it will be controversial (warn the user we are dropping their input on the floor).

Steps:

 - add a check to the  code linked above to warn if any of `c`, `cmap`, `norm`, `vmin`, `vmax` are passed by the user and `colors` is not None
 - add a test
 - add an behavior change API change note.
Could this just error out at `set_array` if the array has never been used?  
If it is still open, can I take up the issue?

@anandhakrishnanaji As you can see above there is an open pull request. So this is aleady been worked on. 

You are welcome to pick up another issue. A good place to start looking is [the list of good first issues](https://github.com/matplotlib/matplotlib/labels/Good%20first%20issue).

Commit message: Fixed tests to look for proper warning message

Patch to review:
diff --git a/doc/api/next_api_changes/behavior/23516-MS.rst b/doc/api/next_api_changes/behavior/23516-MS.rst
new file mode 100644
index 000000000000..32bdb8a7df87
--- /dev/null
+++ b/doc/api/next_api_changes/behavior/23516-MS.rst
@@ -0,0 +1,6 @@
+Warning when scatter plot color settings discarded
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+When making an animation of a scatter plot, if you don't set *c* (the color
+value parameter) when initializing the artist, the color settings are ignored.
+`.Axes.scatter` now raises a warning if color-related settings's are changed
+without setting *c*
diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py
index e9b3e078b2a0..4b35d1c7d4fc 100644
--- a/lib/matplotlib/axes/_axes.py
+++ b/lib/matplotlib/axes/_axes.py
@@ -4559,6 +4559,16 @@ def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None,
             collection.set_cmap(cmap)
             collection.set_norm(norm)
             collection._scale_norm(norm, vmin, vmax)
+        else:
+            extra_kwargs = {
+                    'cmap': cmap, 'norm': norm, 'vmin': vmin, 'vmax': vmax
+                    }
+            extra_keys = [k for k, v in extra_kwargs.items() if v is not None]
+            if any(extra_keys):
+                keys_str = ", ".join(f"'{k}'" for k in extra_keys)
+                _api.warn_external(
+                    "No data for colormapping provided via 'c'. "
+                    f"Parameters {keys_str} will be ignored")
         collection._internal_update(kwargs)
 
         # Classic mode only:
diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py
index 721e35768265..346bc07bed88 100644
--- a/lib/matplotlib/tests/test_axes.py
+++ b/lib/matplotlib/tests/test_axes.py
@@ -2383,6 +2383,25 @@ def test_scatter_color(self):
         with pytest.raises(ValueError):
             plt.scatter([1, 2, 3], [1, 2, 3], color=[1, 2, 3])
 
+    @pytest.mark.parametrize('kwargs',
+                                [
+                                    {'cmap': 'gray'},
+                                    {'norm': mcolors.Normalize()},
+                                    {'vmin': 0},
+                                    {'vmax': 0}
+                                ])
+    def test_scatter_color_warning(self, kwargs):
+        warn_match = "No data for colormapping provided "
+        # Warn for cases where 'cmap', 'norm', 'vmin', 'vmax'
+        # kwargs are being overridden
+        with pytest.warns(Warning, match=warn_match):
+            plt.scatter([], [], **kwargs)
+        with pytest.warns(Warning, match=warn_match):
+            plt.scatter([1, 2], [3, 4], c=[], **kwargs)
+        # Do not warn for cases where 'c' matches 'x' and 'y'
+        plt.scatter([], [], c=[], **kwargs)
+        plt.scatter([1, 2], [3, 4], c=[4, 5], **kwargs)
+
     def test_scatter_unfilled(self):
         coll = plt.scatter([0, 1, 2], [1, 3, 2], c=['0.1', '0.3', '0.5'],
                            marker=mmarkers.MarkerStyle('o', fillstyle='none'),
diff --git a/lib/matplotlib/tests/test_colorbar.py b/lib/matplotlib/tests/test_colorbar.py
index 83b6be1b707f..50f3498d12dc 100644
--- a/lib/matplotlib/tests/test_colorbar.py
+++ b/lib/matplotlib/tests/test_colorbar.py
@@ -280,7 +280,7 @@ def test_remove_from_figure(use_gridspec):
     Test `remove` with the specified ``use_gridspec`` setting
     """
     fig, ax = plt.subplots()
-    sc = ax.scatter([1, 2], [3, 4], cmap="spring")
+    sc = ax.scatter([1, 2], [3, 4])
     sc.set_array(np.array([5, 6]))
     pre_position = ax.get_position()
     cb = fig.colorbar(sc, use_gridspec=use_gridspec)
@@ -296,7 +296,7 @@ def test_remove_from_figure_cl():
     Test `remove` with constrained_layout
     """
     fig, ax = plt.subplots(constrained_layout=True)
-    sc = ax.scatter([1, 2], [3, 4], cmap="spring")
+    sc = ax.scatter([1, 2], [3, 4])
     sc.set_array(np.array([5, 6]))
     fig.draw_without_rendering()
     pre_position = ax.get_position()


Code review comments:
diff_hunk: @@ -0,0 +1,6 @@
+Warning when scatter plot color settings discarded
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+When making an animation of a scatter plot, if you don't set *c* (the color
+value parameter) when initializing the artist, the color settings are ignored.
+`.Axes.scatter` now raises a warning if color-related settings's are changed
+without setting *c*
path: doc/api/next_api_changes/behavior/23516-MS.rst
text: @user1:
```suggestion
`.Axes.scatter` now raises a warning if color-related settings are changed
without setting *c*.
```