8

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,564
  • 3
  • 14
  • 27
Susan-l3p
  • 157
  • 1
  • 13

2 Answers2

8

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
  • 12,057
  • 5
  • 39
  • 55
  • 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
0

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
  • 2,028
  • 2
  • 25
  • 46
  • Are you creating your own data here? How would I apply this to the data that I have? – Susan-l3p Sep 17 '19 at 07:38
  • 1
    Welcome to StackOverflow. Kindly format and indent your answer correctly, and if possible, please elucidate it further too. Happy coding! – Arka Mukherjee Sep 17 '19 at 07:40
  • The reason why this answer doesn't address the OP's question is the `x` value is not the same for both curves. This answer assumes `x` is the same. Otherwise, if you `x` is the same then this will do the trick – Gene Burinsky Sep 28 '22 at 20:20