用 matplotlib.pyplot.fill 绘制多条曲线

Plot multiple curves with matplotlib.pyplot.fill

我正在尝试在 matplotlib 中从一对包含多个要绘制的 'curves' 的 numpy 数组创建一个“fill”图形。 numpy 数组的形式为:

xarray([[   0],    #curve 1
        [ 100],    #curve 1
        [ 200],    #curve 1
        [   0],    #curve 2
        [ 100],    #curve 2
        [ 200]])   #curve 2

yarray([[ 11],     #curve 1
        [ 22],     #curve 1
        [ 22],     #curve 1
        [ 19],     #curve 2
        [ 12],     #curve 2
        [  0]])    #curve 2

对于此示例代码,其中有两条曲线(即 x = 0-200 两次)。实际数组有大约 300 条曲线,所有曲线都从 x = 0 开始,尽管我可以在必要时对它们进行编号(使用另一个包含曲线编号的数组)。每个 xy 对中的点数也不同。

我想用 ~0.01 的 alpha 值(即几乎透明)绘制它们,以便大多数曲线下方的区域显示最彩色。

但是,如果我将 x 和 y 数组放入填充函数 (plt.fill(xarray, yarray, alpha=0.01)),它会将所有数据视为一条曲线,因此当曲线位于本身。

我不确定如何将 x 和 y 数组更改为 plt.fill 函数可接受的逗号分隔数组列表。使最终结果等同于我手动编写的东西:

plt.fill(x1, y1, x2, y2, ... yn, xn, alpha=0.01)

有什么想法吗?

如果我对其中的任何解释不够充分,请告诉我。谢谢!

您需要将系列拆分为多个数组并调用 plot 函数。这些图将绘制在同一图中。您要么需要每个系列的长度来拆分系列,要么使用标记拆分(正如您所说的“0”是(总是?)串联系列的第一个元素。

import numpy as np
import matplotlib.pyplot as plt

xarray = np.array([[   0],    #curve 1
                   [ 100],    #curve 1
                   [ 200],    #curve 1
                   [   0],    #curve 2
                   [ 100],    #curve 2
                   [ 200]])   #curve 2

yarray = np.array([[ 11],     #curve 1
                   [ 22],     #curve 1
                   [ 22],     #curve 1
                   [ 19],     #curve 2
                   [ 12],     #curve 2
                   [  0]])    #curve 2

# can the value "0" can be used separate xy pairs?
indices = np.argwhere(xarray[:,0] == 0)
for i in range(len(indices)):
    try:
        i0 = indices[i]
        i1 = indices[i+1]
    except:
        i0 = indices[i]
        i1 = len(xarray[:,0])
    plt.fill(xarray[i0:i1,0], yarray[i0:i1,0])
plt.show()

通过使用各种 numpy 例程进行一些摆弄,您可以尝试如下操作:

import numpy as np
from matplotlib import pyplot as plt

x = np.array([[   0], [ 100], [ 200],
              [   0], [ 100], [ 200], 
              [0], [100], [200], [300]])
y = np.array([[ 11], [ 22], [ 22],
              [ 19], [ 12], [  0],
              [11], [33], [11], [22]])
indices = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 2])

split = np.where(np.diff(indices))[0] + 1
x = np.squeeze(x)
y = np.squeeze(y)
x = np.split(x, split)
y = np.split(y, split)

xy = np.vstack((x, y))
xy = xy.T.flatten()

plt.figure()
plt.fill(*xy, alpha=0.01)
plt.show()

所有 xy 的杂耍都是为了让两个数组很好地排列成一个数组,然后您可以将其与 *arg 方法一起用作输入至 pyplot.fill.