0

I know the function fill_between from matplotlib allows to color space between curves. Now, I would like to know if I can retrieve this information, ie get the coordinates of the pixels that are now colored on my plotting window.

Here is a working example:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,10,100)
y = np.linspace(0,20,100)
plt.plot(x,y)
im = plt.fill_between(x,y)

Here I see a blue triangle, how can I get the coordinates of the points within this triangle? I have been searching through the PolyCollection options, but nothing seems to fit what I want.

Here is an example of what fill_between looks like:
enter image description here

Thanks for your help!

Mr. T
  • 11,960
  • 10
  • 32
  • 54
BP_astro
  • 11
  • 1
  • What do you mean by "the coordinates of the points"? There is an infinite number of points in this filled area. Maybe you want to calculate the area? – Mr. T Apr 18 '22 at 10:03
  • You're right, I guess what would help me is a method to test if a point is inside this area, or a way to get the area's boundaries. – BP_astro Apr 18 '22 at 10:12
  • What do you want to test? PolyCollection has the method `contains(mouseevent)` to test whether a mouse event occurs within this PolyCollection. Otherwise, I would consider using shapely. The paths can be extracted as shown [here](https://stackoverflow.com/q/63078126/8881141). – Mr. T Apr 18 '22 at 10:28

1 Answers1

0

If you have functions f(x) = y and g(x) = y that describe the boundary lines, and you want to test whether a given point (x, y) lies between the graphs of these functions (i.e. within the area colored by fill_between), you can write a function like this:

def is_between(x, y, f, g=lambda x: 0):
    y_min = f(x)
    y_max = g(x)
    if y_min > y_max:
        y_min, y_max = y_max, y_min
    return y_min <= y <= y_max

For example, is the point (2, 4.1) within the blue area in your example? In this case, we can omit specifying g, because we set it to be the x-axis (g(x) = 0) by default.

is_between(2, 4.1, lambda x: 2 * x)

This returns False, as expected.

Arne
  • 9,990
  • 2
  • 18
  • 28
  • 1
    Good thinking but it lacks flexibility to be applicable to cases like [`fill_betweenx(y, x1, x2)`](https://matplotlib.org/stable/gallery/lines_bars_and_markers/fill_betweenx_demo.html) – Mr. T Apr 18 '22 at 12:44