问题描述
我正在绘制 PatchCollection
在matplotlib中,具有从文件中读取的坐标和色块颜色值.
I am plotting a PatchCollection
in matplotlib with coords and patch color values read in from a file.
问题是matplotlib似乎会自动将颜色范围缩放到数据值的最小值/最大值.如何手动设置颜色范围?例如.如果我的数据范围是 10-30,但我想将其缩放到 5-50 的颜色范围(例如与另一个图进行比较),我该怎么做?
The problem is that matplotlib seems to automatically scale the color range to the min/max of the data values. How can I manually set the color range? E.g. if my data range is 10-30, but I want to scale this to a color range of 5-50 (e.g. to compare to another plot), how can I do this?
我的绘图命令与api示例代码中的命令几乎相同: patch_collection.py
My plotting commands look much the same as in the api example code: 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()
推荐答案
在您的示例中,使用 p.set_clim([5,50])
设置颜色缩放的最小值和最大值.matplotlib中具有颜色图的所有内容均具有 get_clim
和 set_clim
方法.
Use p.set_clim([5, 50])
to set the color scaling minimums and maximums in the case of your example. Anything in matplotlib that has a colormap has the get_clim
and set_clim
methods.
作为一个完整的例子:
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()
现在,如果我们在调用 plt.show(...)
,我们得到这个:
Now, if we just add p.set_clim([5, 50])
(where p
is the patch collection) somewhere before we call plt.show(...)
, we get this:
这篇关于在 matplotlib patchcollect 中设置颜色范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!