Nico Schlömer
Nico Schlömer

Reputation: 58791

stackplot with different x data

Stacked plotting in matplotlib with equal x data is as easy as

from matplotlib import pyplot as plt

x0 = [0.0, 0.5, 2.0]
y0 = [1.0, 1.5, 1.0]

# x1 = [0.0, 1.5, 2.0]
y1 = [1.0, 1.5, 1.0]

plt.stackplot(x0, (y0, y1))
plt.show()

Is it possible to stack two plots with different x data too?

Upvotes: 3

Views: 1131

Answers (1)

J. P. Petersen
J. P. Petersen

Reputation: 5031

It does not seem to be possible. If you look at the code for Matplotlib's stackplot, then this is the part that draws the stacked plot itself:

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

So it will always use the same x for all stacks.

You could on the other hand create a new x array for the stacked plot, and include all values from all the different x arrays you have, and then calculate the missing y stack values using linear interpolation.

A possible solution using interpolation could look like this:

from matplotlib import pyplot as plt

def interp_nans(x, y):
    is_nan = np.isnan(y)
    res = y * 1.0
    res[is_nan] = np.interp(x[is_nan], x[-is_nan], y[-is_nan])
    return res

x = np.array([0.0, 0.5, 1.5, 2.0])

y0 = np.array([1.0, 1.5, np.nan, 1.0])
y1 = np.array([1.0, np.nan, 1.5, 1.0])

plt.stackplot(x, (interp_nans(x, y0), interp_nans(x, y1)))
plt.show()

But if interpolation can not be used in this case, then it would not work.

Upvotes: 4

Related Questions