2011-05-17 223 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