使用颜色图在 matplotlib 中设置线条颜色 [英] Using Colormaps to set color of line in matplotlib

查看:72
本文介绍了使用颜色图在 matplotlib 中设置线条颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用颜色图(例如 jet)使用运行时提供的标量值设置 matplotlib 中线条的颜色?我在这里尝试了几种不同的方法,我想我很难过.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)行 = []对于范围内的 idx(len(曲线)):线 = 曲线 [idx]colorVal = scalarMap.to_rgba(values[idx])retLine, = ax.plot(line, color=colorVal)#retLine.set_color()行.追加(retLine)ax.legend(线条,标签,loc='右上角')ax.grid()plt.show()

解决方案

您收到的错误是由于您如何定义 jet.您正在创建名为jet"的基类 Colormap,但这与获取jet"颜色图的默认定义非常不同.永远不应直接创建此基类,而应仅实例化子类.

您在示例中发现的是 Matplotlib 中的错误行为.运行此代码时,应该会生成更清晰的错误消息.

这是您示例的更新版本:

将 matplotlib.pyplot 导入为 plt导入 matplotlib.colors 作为颜色将 matplotlib.cm 导入为 cmx将 numpy 导入为 np# 定义一些模拟你输入的代码的随机数据:NCURVES = 10np.random.seed(101)曲线 = [np.random.random(20) for i in range(NCURVES)]值 = 范围(NCURVES)fig = plt.figure()ax = fig.add_subplot(111)# 替换下一行#jet = colors.Colormap('jet')# 和jet = cm = plt.get_cmap('jet')cNorm = colors.Normalize(vmin=0, vmax=values[-1])scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)打印 scalarMap.get_clim()行 = []对于范围内的 idx(len(曲线)):线 = 曲线 [idx]colorVal = scalarMap.to_rgba(values[idx])颜色文本 = ('颜色:(%4.2f,%4.2f,%4.2f)'%(colorVal[0],colorVal[1],colorVal[2]))retLine, = ax.plot(line,颜色=颜色值,标签=颜色文本)行.追加(retLine)#添加这个以使图例起作用句柄,标签 = ax.get_legend_handles_labels()ax.legend(手柄,标签,loc='右上角')ax.grid()plt.show()

导致:

使用 ScalarMappable 是对我的相关答案中提出的方法的改进:使用 matplotlib 创建 20 多种独特的图例颜色>

How does one set the color of a line in matplotlib with scalar values provided at run time using a colormap (say jet)? I tried a couple of different approaches here and I think I'm stumped. values[] is a storted array of scalars. curves are a set of 1-d arrays, and labels are an array of text strings. Each of the arrays have the same length.

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()

解决方案

The error you are receiving is due to how you define jet. You are creating the base class Colormap with the name 'jet', but this is very different from getting the default definition of the 'jet' colormap. This base class should never be created directly, and only the subclasses should be instantiated.

What you've found with your example is a buggy behavior in Matplotlib. There should be a clearer error message generated when this code is run.

This is an updated version of your example:

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()

Resulting in:

Using a ScalarMappable is an improvement over the approach presented in my related answer: creating over 20 unique legend colors using matplotlib

这篇关于使用颜色图在 matplotlib 中设置线条颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆