如何在运行时使用colormap使用标量值在matplotlib中设置线条的颜色(例如jet)?我在这里尝试了几种不同的方法,但我觉得很困惑。values[]是一个存储的标量数组。曲线是一组一维数组,标签是文本字符串数组。每个数组的长度相同。
jet
values[]
fig = plt.figure() ax = fig.add_subplot(111) jet = colors.Colormap('jet') cNorm = colors.Normalize(vmin=0, vmax=values[-1]) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) lines = [] for idx in range(len(curves)): line = curves[idx] colorVal = scalarMap.to_rgba(values[idx]) retLine, = ax.plot(line, color=colorVal) #retLine.set_color() lines.append(retLine) ax.legend(lines, labels, loc='upper right') ax.grid() plt.show()
您收到的错误是由于您的定义jet。您正在创建Colormap名称为’jet’的基类,但这与获取’jet’颜色图的默认定义非常不同。永远不要直接创建此基类,而应仅实例化子类。
Colormap
在示例中发现的是Matplotlib中的错误行为。运行此代码时,应该会产生一条更清晰的错误消息。
这是您的示例的更新版本:
import matplotlib.pyplot as plt import matplotlib.colors as colors import matplotlib.cm as cmx import numpy as np # define some random data that emulates your indeded code: NCURVES = 10 np.random.seed(101) curves = [np.random.random(20) for i in range(NCURVES)] values = range(NCURVES) fig = plt.figure() ax = fig.add_subplot(111) # replace the next line #jet = colors.Colormap('jet') # with jet = cm = plt.get_cmap('jet') cNorm = colors.Normalize(vmin=0, vmax=values[-1]) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) print scalarMap.get_clim() lines = [] for idx in range(len(curves)): line = curves[idx] colorVal = scalarMap.to_rgba(values[idx]) colorText = ( 'color: (%4.2f,%4.2f,%4.2f)'%(colorVal[0],colorVal[1],colorVal[2]) ) retLine, = ax.plot(line, color=colorVal, label=colorText) lines.append(retLine) #added this to get the legend to work handles,labels = ax.get_legend_handles_labels() ax.legend(handles, labels, loc='upper right') ax.grid() plt.show()
导致: