Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions doc/users/next_whats_new/stackplot_legend.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
Order of legend entries in stackplots
-------------------------------------

The order of entries in a legend of a `~matplotlib.axes.Axes.stackplot` can be inverted with the option ``top_to_bottom``. In the below example, a viewer would see the area for ``y3`` above ``y2``, and ``y2`` above ``y1``. Here the legend will be generated in the same way such that ``y3`` appears above ``y2`` and ``y2`` above ``y1``.

.. code-block:: python

@tacaswell tacaswell Nov 23, 2022 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
.. code-block:: python
.. plot::


from matplotlib import pyplot as plt
plt.x = [1, 2, 3, 4, 5]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
plt.x = [1, 2, 3, 4, 5]
x = [1, 2, 3, 4, 5]

y1 = [1, 1, 2, 3, 5]
y2 = [0, 4, 2, 6, 8]
y3 = [1, 3, 5, 7, 9]

y4 = [23, 23, 23, 24, 25]

y = np.vstack([y1, y2, y3])

labels = ["Fibonacci ", "Evens", "Odds"]

fig, ax = plt.subplots()
ax.plot(x, y4, label="staying above")
ax.stackplot(x, y1, y2, y3, labels=labels, top_to_bottom=True)
ax.legend(loc='upper left')
plt.show()
39 changes: 39 additions & 0 deletions examples/lines_bars_and_markers/stackplot_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,42 @@ def add_random_gaussian(a):
fig, ax = plt.subplots()
ax.stackplot(x, ys, baseline='wiggle')
plt.show()

##############################################################################
# stackplot top_to_bottom option
# ------------------------------
#
# When cycling through the color palette more than once, it can become
# difficult to match legend entries to the correct plot area.
# In this example a color palette with 8 different colors is chosen for
# a stackplot with 16 components.
# "entry 1" and "entry 9" will use the same color, yet a viewer of the
# plot may wonder which of the two is the large band, and which the smaller.
# With the ``top_to_bottom`` option, entries in the legend are stacked in the
# same way as in the plotting area - i.e. "entry 9" appears higher up in the
# legend than and higher up in the stack than "entry 1".

x = np.linspace(0, 10, 11)
many_ys = {"entry 1": np.random.normal(3., 1., 11),
"entry 2": np.random.normal(3., .1, 11),
"entry 3": np.random.normal(1., .1, 11),
"entry 4": np.random.normal(1., .1, 11),
"entry 5": np.random.normal(1., .1, 11),
"entry 6": np.random.normal(3., .3, 11),
"entry 7": np.random.normal(10., 0., 11),
"entry 8": np.random.normal(8., 0., 11),

"entry 9": np.random.normal(30., 1., 11),
"entry 10": np.random.normal(30., 5., 11),
"entry 11": np.random.normal(1., .1, 11),
"entry 12": np.random.normal(1., .1, 11),
"entry 13": np.random.normal(5., .1, 11),
"entry 14": np.random.normal(5., 1., 11),
"entry 15": np.random.normal(5., .5, 11),
"entry 16": np.random.normal(5., .2, 11)}

fig, ax = plt.subplots()
ax.set_prop_cycle(color=plt.cm.Dark2.colors)
ax.stackplot(x, many_ys.values(), labels=many_ys.keys(), top_to_bottom=True)
ax.legend(loc='upper left')
plt.show()
7 changes: 4 additions & 3 deletions lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2840,10 +2840,11 @@ def spy(
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.stackplot)
def stackplot(
x, *args, labels=(), colors=None, baseline='zero', data=None,
**kwargs):
x, *args, labels=(), top_to_bottom=False, colors=None,
baseline='zero', data=None, **kwargs):
return gca().stackplot(
x, *args, labels=labels, colors=colors, baseline=baseline,
x, *args, labels=labels, top_to_bottom=top_to_bottom,
colors=colors, baseline=baseline,
**({"data": data} if data is not None else {}), **kwargs)


Expand Down
59 changes: 40 additions & 19 deletions lib/matplotlib/stackplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@


def stackplot(axes, x, *args,
labels=(), colors=None, baseline='zero',
labels=(), top_to_bottom=False, colors=None, baseline='zero',
**kwargs):
"""
Draw a stacked area plot.
Expand All @@ -30,7 +30,7 @@ def stackplot(axes, x, *args,
calls is legal::

stackplot(x, y) # where y has shape (M, N)
stackplot(x, y1, y2, y3) # where y1, y2, y3, y4 have length N
stackplot(x, y1, y2, y3) # where y1, y2, y3 have length N

baseline : {'zero', 'sym', 'wiggle', 'weighted_wiggle'}
Method used to calculate the baseline:
Expand All @@ -47,6 +47,14 @@ def stackplot(axes, x, *args,
A sequence of labels to assign to each data series. If unspecified,
then no labels will be applied to artists.

top_to_bottom : bool, optional
When true, the top most component of the stackplot will be plotted
first. This has the effect that the top most plot component will appear
above the other plot components in the legend. That is, for
``stackplot(x, y1, y2, y3)``, the legend will contain y3 above y2 and
y2 above y1.
The default behaviour is plotting the bottom area first.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
The default behaviour is plotting the bottom area first.
The default behaviour is plotting the bottom area first.
.. versionadded:: 3.7


colors : list of color, optional
A sequence of colors to be cycled through and used to color the stacked
areas. The sequence need not be exactly the same length as the number
Expand All @@ -70,11 +78,12 @@ def stackplot(axes, x, *args,

y = np.row_stack(args)

labels = iter(labels)
iter_method = reversed if top_to_bottom else iter
labels = iter_method(labels)
if colors is not None:
colors = itertools.cycle(colors)
colors = itertools.cycle(iter_method(colors))
else:
colors = (axes._get_lines.get_next_color() for _ in y)
colors = iter_method(list(axes._get_lines.get_next_color() for _ in y))

# Assume data passed has not been 'stacked', so stack it here.
# We'll need a float buffer for the upcoming calculations.
Expand Down Expand Up @@ -111,17 +120,29 @@ def stackplot(axes, x, *args,
first_line = center - 0.5 * total
stack += first_line

# Color between x = 0 and the first array.
coll = axes.fill_between(x, first_line, stack[0, :],
facecolor=next(colors), label=next(labels, None),
**kwargs)
coll.sticky_edges.y[:] = [0]
r = [coll]

# Color between array i-1 and array i
for i in range(len(y) - 1):
r.append(axes.fill_between(x, stack[i, :], stack[i + 1, :],
facecolor=next(colors),
label=next(labels, None),
**kwargs))
return r
r = []

def bottom_area():
# Color between x = 0 and the first array.
coll = axes.fill_between(x, first_line, stack[0, :],
facecolor=next(colors),
label=next(labels, None),
**kwargs)
coll.sticky_edges.y[:] = [0]
r.append(coll)

def not_bottom_areas():
# Color between array i-1 and array i
for i in iter_method(range(len(y) - 1)):
r.append(axes.fill_between(x, stack[i, :], stack[i + 1, :],
facecolor=next(colors),
label=next(labels, None),
**kwargs))
if top_to_bottom:
not_bottom_areas()
bottom_area()
else:
bottom_area()
not_bottom_areas()

return list(iter_method(r))
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
15 changes: 15 additions & 0 deletions lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,21 @@ def test_legend_stackplot():
ax.legend(loc='best')


@image_comparison(['legend_stackplot_sorted.png'])
def test_legend_stackplot_updown_sort():
"""Test up-down sorted legend for PolyCollection using stackplot."""
# related to #1341, #1943, and PR #3303
fig, ax = plt.subplots()
x = np.linspace(0, 10, 10)
y1 = 1.0 * x
y2 = 2.0 * x + 1
y3 = 3.0 * x + 2
ax.stackplot(x, y1, y2, y3, labels=['y1', 'y2', 'y3'], top_to_bottom=True)
ax.set_xlim((0, 10))
ax.set_ylim((0, 70))
ax.legend(loc='best')


def test_cross_figure_patch_legend():
fig, ax = plt.subplots()
fig2, ax2 = plt.subplots()
Expand Down