【问题标题】:Python: Plot many lists of lists of lines at once with Matplotlib dynamicallyPython:使用 Matplotlib 动态绘制多个行列表
【发布时间】:2017-09-30 05:09:29
【问题描述】:

希望清理一些我目前非常混乱的代码。目标是在一个图上绘制多条线,但数据的结构可以不同。

数据可以以几种不同的方式排列..

lats[set][point]
lons[set][point]

lat2[collection][set][point]
lon2[collection][set][point]

甚至只是一个常规的 xs 和 ys 列表,

我会将相应的“集合”插入 plt.plot(x,y),因为它是 xs 或 ys 的列表。我希望能够拥有尽可能多的列表,这取决于我正在绘制的数据。目前我有一些基于类型排序的复杂检查,代码的基础如下。

def plotter(xs,ys):
    for x,y in zip(xs,ys):
        if type(x[0]) in (list, tuple):
            plotter(x,y)
        else:
            plt.plot(x,y)

开始变得复杂的是尝试为不同深度的列表合并样式。

我一直在尝试使用 matplotlib.collections,但我还没有完全弄清楚如何正确使用它。任何帮助将不胜感激

【问题讨论】:

    标签: python list matplotlib dynamic collections


    【解决方案1】:

    一种解决方案是为包含实际数据的数据数组生成所有可能的索引组合。下面是一些示例代码,可能看起来很复杂,但主要是生成和绘制数据。

    有 3 个数据集(如您所建议的),具有以下形式:

    lat1 -> 点集

    lat2 -> 点集的集合

    lat3 -> 点

    代码如下:

    import matplotlib.pyplot as plt
    import numpy as np
    import itertools
    
    # First data type
    lat1 = np.array([np.linspace(0,180,100) for i in range(5)])
    lon1 = np.array([10+5*np.random.random(100) for i in range(5)])
    # lat1.shape = (5,100)
    # [set][point]
    
    
    # Second data type
    lat2 = np.array([np.linspace(0,180,100) for i in range(5*3)]).reshape((3,5,100))
    lon2 = np.array([30+10*np.random.random(100) for i in range(5*3)]).reshape((3,5,100))
    # lat2.shape = (3,5,100)
    # [collection][set][point]
    
    
    # Third data type
    lat3 = np.linspace(0,180,100)
    lon3 = 50+5*np.random.random(100)
    # lat3.shape = (100,)
    # [point]
    
    
    def plotter(xs,ys,ax,**kwargs):
        # Get number of dimensions
        ndim = xs.ndim
    
        # Iterate over each dimension, generating all indices
        if ndim>1:
            indices = [np.arange(0,i,1) for i in xs.shape[:-1]]
            comb = list(itertools.product(*indices))
        else:
            # This is to deal with one dimensional data (i.e. just a list)
            comb = [slice(0, xs.shape[0])]
    
        for c in comb:
            xx = xs[c]
            yy = ys[c]
            ax.plot(xx, yy, **kwargs)
    
        return ax
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plotter(lat1, lon1, ax, c='r', label='Type 1')
    plotter(lat2, lon2, ax, c='b', label='Type 2')
    plotter(lat3, lon3, ax, c='g', label='Type 3')
    
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
    ax.legend(fontsize=8,bbox_to_anchor=(1,1))
    
    ax.set_ylim(0,60)
    ax.set_xlim(0,180)
    
    fig.show()
    

    给出下图:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 2014-05-28
      相关资源
      最近更新 更多