Reputation: 893
I'm trying to color the space between the graph line and the x-axis. The color should be based on the value of the corresponding point on the line. Kinda like the first graph:
(https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/fill_between_demo.html)
If it's higher than 100 it should be red, if it's lower than 100 it should be green. The graph I'm looking for should be red-green alternating.
This is what I have at the moment:
import matplotlib.pyplot as plt
lenght = 120
y = [107, 108, 105, 109, 107, 106, 107, 109, 106, 106, 94, 93, 94, 93, 93, 94, 95, 106, 108, 109, 107, 107, 106, 108, 105, 108, 107, 106, 107, 97, 93, 96, 94, 96, 95, 94, 104, 107, 106, 108, 107, 107, 106, 107, 105, 107, 108, 105, 107, 100, 93, 94, 93, 95, 104, 107, 107, 108, 108, 107, 107, 107, 107, 104, 94, 96, 95, 96, 94, 95, 94, 100, 107, 107, 105, 107, 107, 109, 107, 108, 107, 105, 108, 108, 106, 97, 94, 94, 94, 94, 95, 94, 94, 94, 96, 108, 108, 107, 106, 107, 107, 108, 107, 106, 95, 95, 95, 94, 94, 96, 105, 108, 107, 106, 106, 108, 107, 108, 106, 107]
x = [x for x in range(lenght)]
lvl = lenght * [100]
fig, ax = plt.subplots()
ax.plot(x, y, color="black")
ax.fill_between(x, 0, y, where=y>lvl, facecolor='red', interpolate=True)
ax.fill_between(x, 0, y, where=y<=lvl, facecolor='green', interpolate=True)
plt.show()
This results in the following graph:
The area's where the value is less than 100 should be green. But the space between the line and the x-axis is always the color based on the first value in the array (in this example, red). How can I fix this?
Upvotes: 3
Views: 4121
Reputation: 339220
Use numpy
, A > B
. Else, if not wanting to use numpy it would need to be [a > b for a,b in zip(A,B)]
.
import numpy as np
import matplotlib.pyplot as plt
y = [107, 108, 105, 109, 107, 106, 107, 109, 106, 106, 94, 93, 94, 93, 93, 94, 95, 106, 108,
109, 107, 107, 106, 108, 105, 108, 107, 106, 107, 97, 93, 96, 94, 96, 95, 94, 104, 107,
106, 108, 107, 107, 106, 107, 105, 107, 108, 105, 107, 100, 93, 94, 93, 95, 104, 107, 107,
108, 108, 107, 107, 107, 107, 104, 94, 96, 95, 96, 94, 95, 94, 100, 107, 107, 105, 107, 107,
109, 107, 108, 107, 105, 108, 108, 106, 97, 94, 94, 94, 94, 95, 94, 94, 94, 96, 108, 108, 107,
106, 107, 107, 108, 107, 106, 95, 95, 95, 94, 94, 96, 105, 108, 107, 106, 106, 108, 107,
108, 106, 107]
y = np.array(y)
x = np.arange(len(y))
lvl = 100
fig, ax = plt.subplots()
ax.plot(x, y, color="black")
ax.fill_between(x, 0, y, where=y>lvl, facecolor='red', interpolate=True)
ax.fill_between(x, 0, y, where=y<=lvl, facecolor='green', interpolate=True)
plt.show()
Upvotes: 5