Home Articles

使用Colormaps在matplotlib中设置线条的颜色

Asked
Viewed 949 times
57

如何使用色彩图(例如 jet )在运行时使用标量值设置matplotlib中一行的颜色?我在这里尝试了几种不同的方法,我觉得我很难过 . values[] 是一个被排除的标量数组 . 曲线是一组1-d数组,标签是文本字符串数组 . 每个阵列具有相同的长度 .

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

4 Answers

  • 73

    您收到的错误是由于您如何定义 jet . 您正在创建名为'jet'的基类 Colormap ,但这与获取'jet'色彩映射的默认定义非常不同 . 永远不应该直接创建这个基类,只应实例化子类 .

    您在示例中发现的是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()
    

    导致:

    enter image description here

    使用 ScalarMappable 是对我相关答案中提出的方法的改进:creating over 20 unique legend colors using matplotlib

  • 45

    来自 matplotlib 的线条样式,标记和定性颜色的组合:

    import itertools
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    N = 8*4+10
    l_styles = ['-','--','-.',':']
    m_styles = ['','.','o','^','*']
    colormap = mpl.cm.Dark2.colors   # Qualitative colormap
    for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, colormap)):
        plt.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=4);
    

    enter image description here

  • 7

    我认为使用numpy的linspace和matplotlib的cm-type对象包含我认为更简单的方法是有益的 . 上述解决方案可能适用于旧版本 . 我使用的是python 3.4.3,matplotlib 1.4.3和numpy 1.9.3 . ,我的解决方案如下 .

    import matplotlib.pyplot as plt
    
    from matplotlib import cm
    from numpy import linspace
    
    start = 0.0
    stop = 1.0
    number_of_lines= 1000
    cm_subsection = linspace(start, stop, number_of_lines) 
    
    colors = [ cm.jet(x) for x in cm_subsection ]
    
    for i, color in enumerate(colors):
        plt.axhline(i, color=color)
    
    plt.ylabel('Line Number')
    plt.show()
    

    这会产生1000条色彩鲜艳的线条,这些线条跨越整个cm.jet色彩图,如下图所示 . 如果您运行此脚本,您会发现可以放大各个行 .

    cm.jet between 0.0 and 1.0 with 1000 graduations

    现在说我希望我的1000线颜色只能跨越400到600行之间的绿色部分 . 我只是将我的开始和停止值更改为0.4和0.6,这导致仅使用0.4和0.4之间的cm.jet颜色映射的20% . 0.6 .

    cm.jet between 0.4 and 0.6 with 1000 graduations

    因此,在一行摘要中,您可以相应地从matplotlib.cm色彩映射创建rgba颜色列表:

    colors = [ cm.jet(x) for x in linspace(start, stop, number_of_lines) ]
    

    在这种情况下,我使用名为jet的常用调用 Map ,但您可以通过调用以下内容找到matplotlib版本中可用的完整颜色映射列表:

    >>> from matplotlib import cm
    >>> dir(cm)
    
  • 0

    你可以像我从我删除的帐户中写的那样(禁止发布新帖子:(有) . 它相当简单,漂亮 .

    我通常使用这3个中的第3个,我也不会检查1和2版本 .

    from matplotlib.pyplot import cm
    import numpy as np
    
    #variable n should be number of curves to plot (I skipped this earlier thinking that it is obvious when looking at picture - sorry my bad mistake xD): n=len(array_of_curves_to_plot)
    #version 1:
    
    color=cm.rainbow(np.linspace(0,1,n))
    for i,c in zip(range(n),color):
       ax1.plot(x, y,c=c)
    
    #or version 2: - faster and better:
    
    color=iter(cm.rainbow(np.linspace(0,1,n)))
    c=next(color)
    plt.plot(x,y,c=c)
    
    #or version 3:
    
    color=iter(cm.rainbow(np.linspace(0,1,n)))
    for i in range(n):
       c=next(color)
       ax1.plot(x, y,c=c)
    

    3的例子:

    Ship RAO of Roll vs Ikeda damping in function of Roll amplitude A44

Related