Search code examples
pythonmatplotlibcolorbar

Change background color of colorbar when using transparent colors


Context: Matplotlib scatter plots. When using transparency (alpha<1) in scatter plots and an axis background color other than white, the colors in the corresponding colorbar look different. This is clearly visible in the figure below: The colorbar on the right looks "too bright". However, setting the background color of the axis of the colorbar does not change this.

So the question: How can I change the background color of colorbar with transparent colors?

I'm using Python 2.7.3 and Matplotlib 1.3.1 (on Ubuntu 12.04)

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(10) #for reproducability

n = 10
ticks = range(n)
data = np.hstack((np.random.rand(50,2),np.random.randint(0,n,(50,1))))
colors = plt.cm.get_cmap('jet',n)(ticks)
lcmap = plt.matplotlib.colors.ListedColormap(colors)

plt.figure(figsize=(8,4))
ax = plt.subplot(121)
plt.scatter(data[:,0],data[:,1], c=data[:,2], s=40, alpha=0.3, 
        edgecolor='none', cmap=lcmap)
plt.colorbar(ticks=ticks)
plt.clim(-0.5,9.5)

ax = plt.subplot(122)
plt.scatter(data[:,0],data[:,1], c=data[:,2], s=40, alpha=0.3, 
        edgecolor='none', cmap=lcmap)
cb = plt.colorbar(ticks=ticks)
ax.set_axis_bgcolor((0.2,0.2,0.2))
cb.ax.set_axis_bgcolor((0.2,0.2,0.2))
plt.clim(-0.5,9.5)

plt.show()

enter image description here


Solution

  • Put this line after your plt.clim call,

    cb.patch.set_facecolor((0.2, 0.2, 0.2, 1.0))