首页 > 解决方案 > 如何在使用颜色图作为图例的同时创建多个 matplotlib 图?

问题描述

我有一组这样的数据 (x1, y1, z1), (x2, y2, z2) 其中 x$ 和 y$ 是数组,而 z$ 是浮点数

我想在一个窗口中绘制类似的东西,同时根据 z$ 排序图。理想情况下,我想根据 z$ 显示具有变化的颜色渐变的不同图。

plt.plot(x1, y1) #color of line based on z1
plt.plot(x2, y2) #color of line based on z2
plt.plot(x3, y3) #color of line based on z3
plt.plot(x4, y4) #color of line based on z4
plt.plot(x5, y5) #color of line based on z5

我添加了这个图表作为我想要做的一个例子在此处输入图像描述

标签: pythonmatplotlib

解决方案


事实证明这有点棘手,尤其是获取渐变。请参阅此 SO 问题(和答案)。我从中借用了彩虹函数(对 matplotlib 进行了修改): 给我画一个彩虹

#include numpy as np
#include math

def rainbow():
    """use as a generator, have to divide each output by 255 for color in matplotlib"""
    r, g, b = 255, 0, 0
    for g in range(256):
        yield r/255, g/255, b/255,
    for r in range(255, -1, -1):
        yield r/255, g/255, b/255,
    for b in range(256):
        yield r/255, g/255, b/255,
    for g in range(255, -1, -1):
        yield r/255, g/255, b/255,
    for r in range(256):
        yield r/255, g/255, b/255,
    for b in range(255, -1, -1):
        yield r/255, g/255, b/255,

def map_colors(data):
    """Data must be in form ((x1, y1, z1), (x2,y2,z2), ...) with z being the 
    color index identifier, x1 and y1 arrays for 2D line, tuples should be 
    sorted by z-value"""
    zvals = []
    for mytuple in data:
        zvals.append(mytuple[2])
    #note this range (10,1500) covers the (mostly) full rainbow (no violet) but a 
    #tighter gradient can be obtained with, for example (400, 800, len(zvals))
    color_index = [math.floor(x) for x in np.linspace(10, 1500, len(zvals))]
    foo = list(rainbow())
    return [foo[x] for x in color_index]

这是主要的一点;要使用它,只需在另一个函数中调用它,如下所示:

def colorizer(dataset):
    #sort all the plot tuples by the z-value first
    data = sorted(dataset, key=lambda x: x[2])
    #get the r,g,b color indices in sorted order:
    colorset = map_colors(data)
    # generic setup function for matplotlib
    mykwargs = { 'nrows':1, 'ncols':1, 'figsize':(8,6), 'dpi':144,
                'facecolor':'#66ff66' }
    fig, ax = plt.subplots(**mykwargs)
    for i in range(len(data)):
        ax.plot(data[i][0], data[i][1], color=colorset[i])
    plt.show()

这是一个数据生成器函数:

def make_data(n):
    """demo function for generating n exponential plots"""
    power = 1.5
    xvals = np.linspace(1,2,100)
    result = []
    for x in range(n):
        temp = [i**power for i in xvals]
        result.append((tuple(xvals), tuple(temp), round(power, 2)))
        power += 0.1
    return tuple(result)

所以如果我运行这个:

foo = make_data(25)
colorizer(foo)

在此处输入图像描述


推荐阅读