我想使用具有不同alpha值的自定义色彩映射表。但是,添加颜色条时,颜色看起来不同。我相信下面的示例非常清楚地显示了这一点:颜色栏中的颜色通过偏红色(如预期的那样),而图中的数据似乎更灰色。
我该如何解决这个问题? 我很确定我错过了一些微不足道的事情......
版本:matplotlib:1.4.3,python:2.7.3
最小(-ish)示例:
from __future__ import print_function
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import numpy as np
from pyhelpers.checker_hatch import hatch_axes
# build up some testing data
xx,_ = np.mgrid[0:10,0:10]
# set up a linear colormap which is red and only changes alpha
# (1,0,0,1) --> (1,0,0,0)
colors = [(1,0,0,i) for i in np.linspace(1,0,3)]
cmap = mcolors.LinearSegmentedColormap.from_list('mycmap', colors, N=10)
# confirm that the colormap looks like we want it to look
print("- colors --------")
map(print, colors)
for k,v in cmap._segmentdata.iteritems():
print("-", k, "---------")
map(print, v)
fig, ax = plt.subplots()
# add a hatched background rectangle to aid the visualization of transparency
r = plt.Rectangle((-0.5, -0,5), 10, 10, fc='w', ec='b', hatch='/', zorder=-10)
ax.add_patch(r)
# plot the data
im = plt.imshow(xx, cmap=cmap, origin='lower', interpolation='nearest')
# build a colorbar, hatch the background patch and remove the solids edgecolors
cb = plt.colorbar(im)
cb.patch.set_hatch('/')
cb.patch.set_ec('b')
cb.solids.set_edgecolors((0,0,0,0))
plt.savefig('test.png')
plt.show()
输出:
- colors -------- (1, 0, 0, 1.0) (1, 0, 0, 0.5) (1, 0, 0, 0.0) - blue --------- (0.0, 0, 0) (0.5, 0, 0) (1.0, 0, 0) - alpha --------- (0.0, 1.0, 1.0) (0.5, 0.5, 0.5) (1.0, 0.0, 0.0) - green --------- (0.0, 0, 0) (0.5, 0, 0) (1.0, 0, 0) - red --------- (0.0, 1, 1) (0.5, 1, 1) (1.0, 1, 1)
图:
修改
我应该先看看github上的问题:
这似乎与imshow
的alpha处理有关:
https://github.com/matplotlib/matplotlib/issues/3343