pandas fill between in python

To fill between two curves in pandas, you can use the .fill_between() method provided by matplotlib. First, you need to plot the two curves using pandas, then get the current axis and pass it to fill_between() method. Here's an example:

main.py
import pandas as pd
import matplotlib.pyplot as plt

# create some dummy data
x = [0, 1, 2, 3, 4]
y1 = [1, 2, 3, 2, 1]
y2 = [0, 1, 2, 1, 0]

# create dataframe
df = pd.DataFrame({'x': x, 'y1': y1, 'y2': y2})

# plot the curves
ax = df.plot(x='x', y='y1')
df.plot(x='x', y='y2', ax=ax)

# fill between the curves
ax.fill_between(x, y1, y2, where=y1 >= y2, interpolate=True, alpha=0.25, color='green')
ax.fill_between(x, y1, y2, where=y1 < y2, interpolate=True, alpha=0.25, color='red')

# show the plot
plt.show()
513 chars
22 lines

This will create a plot with two curves and fill between them where y1 >= y2 with green color and where y1 < y2 with red color. You can adjust the interpolate parameter to change the style of filling between the curves.

related categories

gistlibby LogSnag