在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()
1 个回答
40
使用 p.set_clim([5, 50])
可以设置你例子中的颜色范围的最小值和最大值。在matplotlib中,任何有颜色映射的东西都有 get_clim
和 set_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)
fig.colorbar(p)
fig.show()
现在,如果我们在调用 fig.show(...)
之前的某个地方添加 p.set_clim([5, 50])
(这里的 p
是补丁集合),我们就会得到这个效果:
