Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add legend support for boxplots #27840

Merged
merged 5 commits into from
Mar 21, 2024
Merged

Conversation

saranti
Copy link
Contributor

@saranti saranti commented Mar 1, 2024

PR summary

Closes #27792. Boxplots now get legend entries.
This was previously attempted on #27711 and then reverted #27780 because it used the same parameter for tick labels and didn't generalize well. These 2 issues have been addressed in this PR.

A new label parameter has been added to Axes.boxplot and Axes.bxp. If called via ax.boxplot(), label is passed to the bxp function, otherwise bxp can be directly called with the label parameter.

The label is passed to the boxes object if showbox=True, otherwise it will be passed to the medians object is showbox=False. Attaching the label to the boxes makes sure that the legend handles will get a patch which will be displayed on the legend.
If the box is turned off, the legend handles will get a Line2D object from the median line which will be displayed as a line in the legend. This has 2 advantages:

  • It suits the aesthetics of a boxless plot
  • Unlike the box, caps, flyers and means, the medians cannot be turned off so they're a good vehicle for the legend label and will ensure that the labels always get set.
Click to old test cases

new_test

PR checklist

@saranti
Copy link
Contributor Author

saranti commented Mar 2, 2024

Other things that need to be done at some stage:

@saranti saranti marked this pull request as draft March 3, 2024 04:30
@saranti saranti marked this pull request as ready for review March 3, 2024 12:09
Copy link
Member

@rcomer rcomer left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your work on this @saranti. It looks like you've done some good work pulling a variety of strands together.

One thing I'm a bit confused about is how the legend label is passed from boxplot to bxp. It is passed both as part of the boxprops dictionary and by itself. Why not just pass with the label parameter?

@@ -0,0 +1,5 @@
``boxplot`` legend labels
~~~~~~~~~~~~~~~~~~~~~~~~~
The tick labels on `~.Axes.boxplot` were previously set with the `labels` parameter.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
The tick labels on `~.Axes.boxplot` were previously set with the `labels` parameter.
The tick labels on `~.Axes.boxplot` were previously set with the *labels* parameter.

When you use backticks, Sphinx tries to turn the word into a link. We have a convention to use emphasis for parameters.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, the boxprops label is redundant. When i first implemented this, I used it as the only check to see if labels has been set but then I realized that it should've been set at the bxp function. Everything in the 'if boxprops' condition is no longer needed.

Legend support for Boxplot
~~~~~~~~~~~~~~~~~~~~~~~~~~
Boxplots now generate legend entries and can be labelled with the
new `label` parameter. If a patch is passed to the box with `show_patch=True`,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
new `label` parameter. If a patch is passed to the box with `show_patch=True`,
new *label* parameter. If a patch is passed to the box with ``show_patch=True``,

Double backtick gets you code formatting.

@@ -3884,10 +3885,12 @@ def boxplot(self, x, notch=None, sym=None, vert=None, whis=None,
If `False` produces boxes with the Line2D artist. Otherwise,
boxes are drawn with Patch artists.

labels : sequence, optional
tick_labels : sequence, optional
Labels for each dataset (one per dataset). These are used for
x-tick labels; *not* for legend entries.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the parameter now has a more specific name, I think we no longer need the note about them not being for the legend.

label : sequence, optional
Legend labels for each boxplot.

.. versionadded:: 3.9
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIRC the data parameter is special and should always come last.

box_or_whis = boxes if showbox else whiskers
for index, element in enumerate(box_or_whis):
try:
if isinstance(boxprops['label'], list):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think is_scalar_or_string may be useful here.

with pytest.warns(mpl.MatplotlibDeprecationWarning,
match='has been renamed \'tick_labels\''):
first = axs[0, 0].boxplot(data,
labels=labels, # `tick_labels`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe use tick_labels here rather than the deprecated name?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I don't use the deprecated name then this pytest will fail.


# This plot will not generate a legend.
with pytest.warns(UserWarning, match='No artists with labels found'):
warnings.warn('No artists with labels found.', UserWarning)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this might be a stray debugging line?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it is. I'm having trouble trying to get pytest to catch the UserWarning when legend is called without the labels being set. The list of emitted warnings is always null even though the warning is clearly raised in

elif len(args) == 0: # 0 args: automatically detect labels and handles.
handles, labels = _get_legend_handles_labels(axs, handlers)
if not handles:
_api.warn_external(
"No artists with labels found to put in legend. Note that "
"artists whose label start with an underscore are ignored "
"when legend() is called with no argument.")

showmeans=True,
patch_artist=True)
axs[0, 1].set_title('Tick labels, no legend')
axs[0, 1].legend()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be good for this test to get hold of the legend handles and labels and assert that these lists are empty.

lib/matplotlib/tests/test_legend.py Outdated Show resolved Hide resolved
@@ -3956,6 +3959,10 @@ def boxplot(self, x, notch=None, sym=None, vert=None, whis=None,
The style of the mean.
data : indexable object, optional
DATA_PARAMETER_PLACEHOLDER
label : sequence, optional
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this could be a single string or a sequence?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might actually need to be str or list of str

@rcomer
Copy link
Member

rcomer commented Mar 4, 2024

The tests failed because of a problem with a new version of pytest which has now been yanked. I’m going to close and re-open to restart the CI.

@rcomer rcomer closed this Mar 4, 2024
@rcomer rcomer reopened this Mar 4, 2024
@timhoffm
Copy link
Member

timhoffm commented Mar 4, 2024

AFAICT, this needs a rebase to pick up the pytest pinning.

@github-actions github-actions bot added the Documentation: examples files in galleries/examples label Mar 5, 2024
@saranti saranti marked this pull request as draft March 5, 2024 13:17
@saranti
Copy link
Contributor Author

saranti commented Mar 6, 2024

@melissawm Thanks for the help yesterday, the rebase seems to have gone fine. The only problem I see now is that all the code having to do with the violin plot shouldn't be there and belongs to #27815

@rcomer
Copy link
Member

rcomer commented Mar 8, 2024

@saranti your branch is still 60 commits behind main. I think you just need

git fetch upstream
git rebase upstream/main

to get it up to date. That should also get rid of the violinplot changes.

@github-actions github-actions bot removed the Documentation: examples files in galleries/examples label Mar 8, 2024
@saranti saranti marked this pull request as ready for review March 8, 2024 08:47
Copy link
Member

@timhoffm timhoffm left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel uncomfortable with the scope of the PR - which has prevented me from looking more closely. It mixes the two independent topics legend support and parameter rename. I would I encourage separate PRs or at least separate commits to make it clear which feature is responsible for which code changes, and to ease review.

doc/api/next_api_changes/deprecations/27840-TS.rst Outdated Show resolved Hide resolved
doc/api/next_api_changes/deprecations/27840-TS.rst Outdated Show resolved Hide resolved
@saranti saranti marked this pull request as draft March 9, 2024 03:42
@saranti
Copy link
Contributor Author

saranti commented Mar 15, 2024

The old tick label test was still there after doing git pull upstream. I removed it as part of the conflict resolution but it's showing up in the diff 🤔

@rcomer
Copy link
Member

rcomer commented Mar 15, 2024

I’ve never used git pull upstream so not really sure what that does. To get up to date with changes that have been merged to main, it is recommended to use rebase.
https://matplotlib.org/devdocs/devel/development_workflow.html#rebase-onto-upstream-main

@saranti saranti force-pushed the box_legend_support branch 2 times, most recently from 1902592 to 9fcf0c0 Compare March 15, 2024 08:38
Copy link
Member

@timhoffm timhoffm left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To fix the doc build.

lib/matplotlib/axes/_axes.py Outdated Show resolved Hide resolved
lib/matplotlib/axes/_axes.py Outdated Show resolved Hide resolved
@timhoffm timhoffm added this to the v3.9.0 milestone Mar 19, 2024
@timhoffm
Copy link
Member

timhoffm commented Mar 19, 2024

Milestoning as 3.9 because it would be nice to get this in and IMO it’s ready. Just needs a second review.

lib/matplotlib/axes/_axes.py Outdated Show resolved Hide resolved
lib/matplotlib/axes/_axes.py Outdated Show resolved Hide resolved
Comment on lines 4424 to 4425
raise ValueError("There must be an equal number of legend"
" labels and boxplots.")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check should probably be in the "input validation" section, and reuse datashape_message.

lib/matplotlib/axes/_axes.pyi Outdated Show resolved Hide resolved
lib/matplotlib/axes/_axes.pyi Outdated Show resolved Hide resolved
@QuLogic QuLogic merged commit 102d0a6 into matplotlib:main Mar 21, 2024
41 of 43 checks passed
@saranti saranti deleted the box_legend_support branch March 23, 2024 05:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[ENH]: Legend entries for boxplot
4 participants