Skip to content
Advertisement

How to have a image as the plot face (the outer border) in matplotlib?

I know I can change the color using fig.patch.set_facecolor("#ccdece") but how do I have an image instead of a solid color? Like using img = plt.imread() and ax.imshow(img) but for the outer border.

Any help is welcome.

Advertisement

Answer

You can create a dummy ax for the full size of the surrounding figure and add an image to that ax. Giving the ax a low enough zorder makes sure it appears behind the actual plots.

For an additional effect, the facecolor of the actual plots can be made semi-transparent.

Here is an example starting from a stock image.

import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import numpy as np

imageFile = cbook.get_sample_data('ada.png')
image = plt.imread(imageFile)

fig, ax = plt.subplots(figsize=(6, 8))

bg_ax = fig.add_axes([0, 0, 1, 1], zorder=-1)
bg_ax.axis('off')
bg_ax.imshow(image)
t = np.linspace(0, 4 * np.pi, 200)
x = 2 * np.cos(t / 2)
y = np.sin(t)
ax.plot(x, y)
ax.set_facecolor('#FFFFFFEE')
plt.show()

example figure background image

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement