how to color area under curve green when its positive and red when its negative in python

You can use numpy to create your data to plot your curve and then use fill_between() function of pyplot from matplotlib to color the area between curve and x-axis. The area color can be green if it's positive and red if it's negative. Here is an example:

main.py
import numpy as np
import matplotlib.pyplot as plt

# create data
x = np.linspace(-5, 5, 1000)
y = x**3 - 4*x

# plot curve
fig, ax = plt.subplots()
ax.plot(x, y, color='black')

# fill area
mask = np.sign(y) == 1  # mask for positive area
ax.fill_between(x, y, where=mask, interpolate=True, color='green', alpha=0.4)
ax.fill_between(x, y, where=~mask, interpolate=True, color='red', alpha=0.4)

# show plot
plt.show()
419 chars
19 lines

This code will plot the curve and color the area under curve green when it's positive and red when it's negative. You can adjust the alpha parameter to control the transparency of the color.

related categories

gistlibby LogSnag