Search code examples
pythonmatplotlibgradient

Pyplot background with color gradient, filling the whole figure


I want to add a background to my Pyplot figure, so that it looks approximately like shown below:

enter image description here

As far as I can tell, adding a color gradient to the figure is a bit tricky, so the idea was to stretch the Axes to fill the entire figure and then add a background image, or something similar to the Axes.

However, I have neither been able to get the axes to fill the entire figure, as shown in the code example below, nor do I know how to set a color gradient background, or set an image behind the graph.

This is what I generate at the moment:

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

x, y, z = np.random.rand(30).reshape((3, 10))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z)
fig.set_facecolor('green')
ax.set_facecolor('gray')
ax.set_position([0, 0, 1, 1])
plt.show()

enter image description here

Using this

ax.imshow([[0,0],[1,1]], cmap=plt.cm.Greens, interpolation='bicubic', extent=(-1, 1, -1, 1))

I can plot an image over the entire axes, below the data, but not below the axis labels, grid, etc. Is there a smart way to do this?


Solution

  • You could create an extra subplot for the background. And put a gradient via imshow(). If the background subplot is created first, it will be behind the main subplot. Then make the background of the main subplot transparent.

    import numpy as np
    import matplotlib.pyplot as plt
    
    x, y, z = np.random.rand(30).reshape((3, 10))
    
    fig = plt.figure()
    
    ax_bg = fig.add_axes([0, 0, 1, 1])
    ax_bg.imshow([[.8, .8], [.2, .2]], cmap='Greens', vmin=0, vmax=1, aspect='auto', interpolation='bicubic')
    
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(x, y, z)
    ax.set_facecolor('none') # make transparent
    
    plt.show()
    

    matplotlib 3d plot with gradient background