2

How can I extract the x/y data from the resulting PolyCollection from a fill_between plot?

polyCollection = ax.fill_between(x,ylo,yhi)

Now how do I get the data back from polyCollection?

For other Collection objects, I use x, y = artist.get_offsets().T, but here that returns just zeros for some reason.

For "Line" type objects, I use x, y = artist.get_xdata(), artist.get_ydata().

(I use this information in a callback to locally auto-zoom the y-axis to fit the data within a certain x-range.)

supergra
  • 1,578
  • 13
  • 19

1 Answers1

7

polyCollection.get_paths() gives a list of paths. In this case a list with one element. From there you can get the vertices as an Nx2 numpy array, and there the x and y:

from matplotlib import pyplot as plt
import numpy as np

N = 20
polyCollection = plt.fill_between(np.arange(0, N),
                                  5 + np.random.normal(size=N).cumsum(),
                                  10 + np.random.normal(size=N).cumsum(), color='lightblue', alpha=0.3)
points = polyCollection.get_paths()[0].vertices
xs = points[:, 0]
ys = points[:, 1]
plt.scatter(xs, ys, marker='o', color='crimson')

example of resulting plot

JohanC
  • 71,591
  • 8
  • 33
  • 66