How to fix 'numpy.ndarray' object has no attribute 'get_figure' when plotting subplots

前端 未结 1 593
深忆病人
深忆病人 2020-12-12 01:45

I have written the following code to plot 6 pie charts in different subplots, but I get an error. This code works correctly if I use it to plot only 2 charts, but produces a

1条回答
  •  醉梦人生
    2020-12-12 02:09

    • The issue is plt.subplots(2, 3, figsize=(24, 10)) creates two groups of 3 subplots, not one group of six subplots.
    array([[, , ],
           [, , ]], dtype=object)
    
    • Unpack all of the subplot arrays from axes, using axes.ravel().
      • numpy.ravel, which returns a flattened array.
      • A list comprehension will also work, axe = [sub for x in axes for sub in x]
    • Assign each plot to one of the subplots in axe.
    • How to resolve AttributeError: 'numpy.ndarray' object has no attribute 'get_figure' when plotting subplots is a similar issue.
    import pandas as pd
    import numpy as np
    
    # sinusoidal sample data
    sample_length = range(1, 6+1)
    rads = np.arange(0, 2*np.pi, 0.01)
    data = np.array([np.sin(t*rads) for t in sample_length])
    df = pd.DataFrame(data.T, index=pd.Series(rads.tolist(), name='radians'), columns=[f'freq: {i}x' for i in sample_length])
    
    # crate the figure and axes
    fig, axes = plt.subplots(2, 3, figsize=(24, 10))
    
    # unpack all the axes subplots
    axe = axes.ravel()
    
    # assign the plot to each subplot in axe
    for i, c in enumerate(df.columns):
        df[c].plot(ax=axe[i])
    

    0 讨论(0)
提交回复
热议问题