3

I am trying to shade the area between two curves that I have plotted. This is what I plotted. enter image description here

Using the following code.

plt.scatter(z1,y1, s = 0.5, color = 'blue')
plt.scatter(z2,y2, s = 0.5, color = 'orange')

I tried using plt.fill_between() but for this to work I need to have the same data on the x_axis (would need to do something like plt.fill_between(x,y1,y2)). Is there any other function that might help with this or am I just using fill_between wrong.

Aksen P
  • 4,245
  • 3
  • 12
  • 26
Susan-l3p
  • 97
  • 1
  • 9

2 Answers2

7

You can try with:

plt.fill(np.append(z1, z2[::-1]), np.append(y1, y2[::-1]), 'lightgrey')

For example:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.array([1,2,3])
y1 = np.array([2,3,4])
x2 = np.array([2,3,4,5,6])
y2 = np.array([1,2,3,4,5])
# plt.plot(x1, y1, 'o')
# plt.plot(x2, y2, 'x')

plt.scatter(x1, y1, s = 0.5, color = 'blue')
plt.scatter(x2, y2, s = 0.5, color = 'orange')
plt.fill(np.append(x1, x2[::-1]), np.append(y1, y2[::-1]), 'lightgrey')
plt.show()

enter image description here

Joe
  • 11,147
  • 5
  • 36
  • 50
  • When using this I get the following error. ValueError: x and y must have same first dimension, but have shapes (107156,) and (168560,) – Susan-l3p Sep 17 '19 at 07:37
  • There was an error in the first draft of the code I posted, try it now :) – Joe Sep 17 '19 at 07:39
  • 1
    This worked beautifully. Thank you! Now just one last thing. So the shaded area now sort of covers my initial plot. Is there a way for me to "send it to the back"? Not too sure if you know what I mean – Susan-l3p Sep 17 '19 at 07:59
  • You are welcome. Maybe you can set the transparency? add this argument: `alpha=0.4` – Joe Sep 17 '19 at 08:02
-1

Try this code:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0.0, 2, 0.01)
y1 = np.sin(2 * np.pi * x)
y2 = 1.2 * np.sin(4 * np.pi * x)


fig, (ax1) = plt.subplots(1, sharex=True)
ax1.fill_between(x, 0, y1)
ax1.set_ylabel('between y1 and 0')
lch
  • 1,892
  • 2
  • 23
  • 41