2011-05-17 160 views
7

我在matplotlib中绘制了一个PatchCollection,并且从文件读入了坐标和补丁颜色值。设置matplotlib patchcollection中的颜色范围

问题是,matplotlib似乎自动将颜色范围缩放到数据值的最小/最大值。我如何手动设置颜色范围?例如。如果我的数据范围是10-30,但我想将其缩放到5-50的颜色范围(例如,与另一个图相比较),我该怎么做?

我的绘图命令看起来大致相同的API示例代码:patch_collection.py

colors = 100 * pylab.rand(len(patches)) 
p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4) 
p.set_array(pylab.array(colors)) 
ax.add_collection(p) 
pylab.colorbar(p) 

pylab.show() 

回答

20

使用p.set_clim([5, 50])设置颜色比例最小值和最大值在你的榜样的情况下。 matplotlib中有色图的任何东西都有get_climset_clim方法。

作为一个完整的例子:

import matplotlib 
import matplotlib.pyplot as plt 
from matplotlib.collections import PatchCollection 
from matplotlib.patches import Circle 
import numpy as np 

# (modified from one of the matplotlib gallery examples) 
resolution = 50 # the number of vertices 
N = 100 
x  = np.random.random(N) 
y  = np.random.random(N) 
radii = 0.1*np.random.random(N) 
patches = [] 
for x1,y1,r in zip(x, y, radii): 
    circle = Circle((x1,y1), r) 
    patches.append(circle) 

fig = plt.figure() 
ax = fig.add_subplot(111) 

colors = 100*np.random.random(N) 
p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4) 
p.set_array(colors) 
ax.add_collection(p) 
plt.colorbar(p) 

plt.show() 

enter image description here

现在,如果我们只是添加p.set_clim([5, 50])(其中p是补丁集),我们称之为plt.show(...)以前在什么地方,我们得到这样的: enter image description here