3

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):

I have two background images, I'd like to use; cat.jpg and dog.jpg

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()
smci
  • 32,567
  • 20
  • 113
  • 146
jjjayn
  • 555
  • 5
  • 10
  • 19

1 Answers1

8

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()

enter image description here

ali_m
  • 71,714
  • 23
  • 223
  • 298