Skip to content

[Bug]: stackplot creates artifacts when height of input is zero #22393

@tlkaufmann

Description

@tlkaufmann

Bug summary

In some cases, when a given input for stackplot has zero value entries, thin lines are drawn.

Code for reproduction

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(42)
x = np.arange(10)
y0 = np.linspace(0, 1, 10)
y1 = np.linspace(0, 1, 10)
y2 = [0, 0, 0.25, 0, 0, 0, 0.25, 0, 0, 0]
y3 = np.linspace(0, 1, 10)


colors=['grey', 'blue', 'red', 'blue']

y = np.stack([y0, y1, y2, y3])
im = plt.stackplot(x, y, colors=colors, lw=0)

Actual outcome

image

One can see thin grey lines where the red object hast zero height.

Expected outcome

image

The thin lines are gone

Additional information

This only happens when the color above and below the empty data has the same color, but there are some use-cases where this is needed (see e.g. fish plots for evolutionary relationships).

Fix

The individual calls to fill_between need to have the following parameters:
where=(stack[i, :] != stack[i+1, :]), interpolate=True and edgecolor=color.

These are the changes made to matplotlib/lib/matplotlib/stackplot.py

    # Color between x = 0 and the first array.
    color = ax._get_lines.get_next_color()
    coll = ax.fill_between(x, 0, stack[0, :],
                                      where=(stack[0, :] != 0), interpolate=True, edgecolor=color,
                                     facecolor=color, 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):
        color = ax._get_lines.get_next_color()
        r.append(ax.fill_between(x, stack[i, :], stack[i+1, :],  
                                               where=(stack[i, :] != stack[i+1, :]), interpolate=True, edgecolor=color,
                                               facecolor=color, label=next(labels, None), **kwargs))

These changes get rid of the lines but as far as I tested it do not have side effects for other plots. Probably one should check whether edgecolor is set in **kwargs as well.

Operating system

No response

Matplotlib Version

3.4.3

Matplotlib Backend

No response

Python version

No response

Jupyter version

No response

Installation

conda

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: inactiveMarked by the “Stale” Github Action

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions