缓慢的matplotlib绘图

问题描述 投票:0回答:1

我有MultiIndexed pandas Series,我试图在自己的子图中绘制每个索引,但它运行得非常慢。

为了完成子绘图,我在MultiIndex的外层使用for循环,并使用内部索引级别作为x坐标绘制Series。

def plot_series( data ):
    # create 16 subplots, corresponding to the 16 outer index levels
    fig, axs = plt.subplots( 4, 4 )

    for oi in data.index.get_level_values( 'outer_index' ):
        # calculate subplot to use
        row = int( oi/ 4 )
        col = int( oi - row* 4 )

        ax = axs[ row, col ]
        data.xs( oi ).plot( use_index = True, ax = ax )

    plt.show()

每个外部索引级别都有1000个数据点,但绘图需要几分钟才能完成。

有没有办法加快绘图速度?

数据

num_out = 16
num_in  = 1000

data = pd.Series( 
    data = np.random.rand( num_out* num_in ), 
    index = pd.MultiIndex.from_product( [ np.arange( num_out ), np.arange( num_in ) ], names = [ 'outer_index', 'inner_index' ] ) 
)
python pandas matplotlib
1个回答
2
投票

而不是循环通过data.index.get_level_values( 'outer_index' ),你可以使用data.groupby(level='outer_index')iterate through the grouped object使用:

for name, group in grouped:
   #do stuff 

这消除了使用data.xs( oi )创建切片数据框的瓶颈。

def plot_series(data):
   grouped = data.groupby(level='outer_index')

   fig, axs = plt.subplots( 4, 4 )
   for name, group in grouped:
      row = int( name/ 4 )
      col = int( name - row* 4 )
      ax = axs[ row, col ]
      group.plot( use_index = True, ax = ax )

      plt.show()



num_out = 16
num_in  = 1000

data = pd.Series( 
    data = np.random.rand( num_out* num_in ), 
    index = pd.MultiIndex.from_product( [ np.arange( num_out ), np.arange( num_in ) ], names = [ 'outer_index', 'inner_index' ] ) 
)

plot_series(data)

使用timeit你可以看到这种方法更快:

%timeit plot_series(data)
795 ms ± 252 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
© www.soinside.com 2019 - 2024. All rights reserved.