【问题标题】:Plot multiple curves with matplotlib.pyplot.fill使用 matplotlib.pyplot.fill 绘制多条曲线
【发布时间】:2015-01-17 00:09:52
【问题描述】:

我正在尝试从包含要绘制的多个“曲线”的一对 numpy 数组在 matplotlib 中创建一个“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)) 中,它会将所有数据视为一条曲线,因此当曲线位于自身之上时,alpha 值不会堆叠。

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

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

有什么想法吗?

如果我解释得不够清楚,请告诉我。谢谢!

【问题讨论】:

  • 你的曲线数字数组是什么样的? indices = np.array([0, 0, 0, 1, 1, 1])?

标签: python numpy matplotlib


【解决方案1】:

您需要将您的系列拆分为多个数组并调用绘图函数。这些图将绘制在同一图中。您要么需要每个系列的长度来拆分系列,要么使用标记进行拆分(正如您所说的“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()

【讨论】:

    【解决方案2】:

    使用各种 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 的输入。

    【讨论】:

      猜你喜欢
      • 2019-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 2019-02-27
      • 2019-10-17
      • 1970-01-01
      相关资源
      最近更新 更多