Matplotlib: change the background color of the color bar (when using transparent colors)

Context: Matplotlib markup graphs. When using transparency ( alpha<1) in scatter plots and the background color of the axis other than white, the colors in the corresponding color panel look different. This is clearly seen in the figure below: The color bar on the right looks “too bright”. However, setting the background color for the axis of the color bar does not change this.

So the question is . How to change the background color of a color panel with transparent colors?

I am 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

+4
source share
1 answer

Put this line after the call plt.clim,

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

All Articles