I'm trying to plot a simple line plot and insert a background image to a plot.
An example pic (with cat.jpg and dog.jpd):

At the moment I have a code that plots the line (from a pandas dataframe) and places the images into figure. However the images and the line plot do not 'interact' at all.
fig, ax = plt.subplots(figsize=(15,10))
cat = np.array(Image.open('cat.jpg'))
dog = np.array(Image.open('dog.jpg'))
ax.imshow(cat, extent=[0, 10, 0, 18], aspect='auto', cmap='gray',alpha=0.75)
ax.imshow(dog, extent=[10, 20, 0, 18], aspect='auto', cmap='gray',alpha=0.75)
ax.plot(df['Series'],color='#3cb8fb',alpha=0.95,linewidth=3.0)
plt.show()
You can use plt.fill_between to create a polygon that covers the area between the origin and the line, then use the .set_clip_path method of each image object to display only the part of the image that falls within the polygon.
For example:
from matplotlib import pyplot as plt
from scipy.misc import lena
fig, ax = plt.subplots(1, 1)
x = np.linspace(0, 1, 10)
y = np.random.rand(10)
image = ax.imshow(lena(), cmap=plt.cm.gray, extent=[0, 1, 0, 1])
line = ax.plot(x, y, '-r', lw=2)
# invisible clipping polygon
poly = ax.fill_between(x, 0, y, visible=False)
clip = poly.get_paths()[0]
# you will need to do this separately for each of the images in your plot
image.set_clip_path(clip, transform=ax.transData)
plt.show()

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With