mwaskom / seaborn

Statistical data visualization in Python
https://seaborn.pydata.org
BSD 3-Clause "New" or "Revised" License
12.6k stars 1.93k forks source link

Adding bar_label to a barplot - changed behaviour with 0.13 when using palette without hue #3775

Closed AlexTWeb closed 4 weeks ago

AlexTWeb commented 4 weeks ago

Hello and thanks for this awesome visualisation library!

While migrating from 0.12 to 0.13, I've spotted the new behaviour of palette on a barplot, that now automatically uses hue.

This changes the returned containers, as in the past all bars where part of containers[0], while with the hue parameter 1 BarContainer is returned per bar.

Example Code:

import seaborn as sns

penguins = sns.load_dataset("penguins")

palette = sns.color_palette("hls", 3)

ax = sns.barplot(penguins, x="body_mass_g", y="island",
                 palette=palette,
                # hue="island", legend=False # << This will be added by v0.13 implicitly if not provided 
                 )

print(f"Type of ax.containers[0] = {type(ax.containers[0])} / Length: {(len(ax.containers[0]))}")

ax.bar_label(ax.containers[0], fontsize=10)

When running this with v0.12 is resulted in all 3 bars having bar_labels (as ax.containers[0] contains all of them): image

Now with v0.13 each bar is it's own BarContainer, so ax.containers[0] is just the first bar: image

I assume this is the supposed behaviour, as it behaves the same, when using the hue parameter in v0.12 (that likely not many people used).

So the old behaviour can be restored, by iterating all BarContainers like this:

for c in ax.containers:
    ax.bar_label(c, fontsize=10)

Do you confirm, that this is the expected behaviour or did I miss something?

mwaskom commented 4 weeks ago

While migrating from 0.12 to 0.13, I've spotted the new behaviour of palette on a barplot, that now automatically uses hue.

This is just to make the deprecation smoother; you should be seeing a warning that you need to update your code, and eventually it will be required to pass hue explicitly. This change was documented in the release notes.

Note that the precise way that artists end up on the matplotlib Axes is considered an implementation detail and subject to change at any time (this is true for pyplot as well).