我有二维字段可以使用 matplotlib 底图在 python 中绘制。 字段的值从 0 到 1000 以上不等。是否可以创建具有固定渐变和颜色的手动颜色图?它应该看起来像:
对于值 - 设置颜色
我是Python新手。所以,欢迎任何建议。
这正是您想要的。
您输入的方式有点令人困惑,所以this可能会更有帮助。
要获得大于 1000 位,您需要屏蔽 1000 以上的值,并让其余的范围从 0-1000 变化。
from matplotlib.colors import LinearSegmentedColormap
cMap = []
for value, colour in zip([0,1,5,10,25,50,100,500,1000],["White", "DarkGreen", "LightGreen", "Yellow", "Brown", "Orange", "IndianRed", "DarkRed", "Purple"]):
cMap.append((value/1000.0, colour))
customColourMap = LinearSegmentedColormap.from_list("custom", cMap)
这就是创建自定义颜色图所需的全部内容。要使用它,只需将其作为命名参数传递到绘图函数(无论您使用哪个)即可
cmap
这就是它的样子。
这样的东西应该有效:
from matplotlib import pyplot
from matplotlib.colors import LinearSegmentedColormap
def create_cmap(data, colours, stops=None):
min_x = min(data)
max_x = max(data)
if stops is not None:
min_x = min(min_x, min(stops))
max_x = max(max_x, max(stops))
if stops is None:
d_x = (max_x - min_x)/(len(colours)-1)
stops = [min_x + i*d_x for i in range(len(colours))]
if min_x < min(stops):
stops = [min_x] + stops
colours = [colours[0]] + colours
if max_x > max(stops):
stops = stops + [max_x]
colours = colours + [colours[-1]]
stops = [(s-min_x)/(max_x-min_x) for s in stops]
cmap_data = list(zip(stops, colours))
cmap = LinearSegmentedColormap.from_list('continuous_map', cmap_data)
def cmap_wrapper(x):
x = max(min_x, min(x, max_x))
x_n = (x-min_x)/(max_x-min_x)
return cmap(x_n)
return cmap_wrapper
colours = ['xkcd:white', 'xkcd:darkgreen', 'xkcd:lightgreen', 'xkcd:yellow', 'xkcd:brown', 'xkcd:orange', 'xkcd:coral', 'xkcd:crimson', 'xkcd:purple']
stops = [0, 1, 5, 10, 25, 50, 100, 500, 1000]
cmap = create_cmap(stops, colours, stops=stops)
fig = pyplot.figure(figsize=(10,10))
ax = fig.add_subplot(1,1,1)
for y in range(1000):
ax.plot([0,1],[y,y],c=cmap(y))
pyplot.show()