【问题标题】:how to do subplot histogram with different bins pandas?如何用不同的熊猫箱做子图直方图?
【发布时间】:2020-01-05 15:56:49
【问题描述】:
x=pd.DataFrame(np.random.randn(400)) 
fig, axs = plt.subplots(2, 2, sharey=True, tight_layout=True, figsize=(10,5)); 
for idx in range(3):
    axs[idx].hist(x, bins=20)
    axs[idx].hist(x, bins=40)
    axs[idx].hist(x, bins=60)  
    axs[idx].hist(x, bins=100) 

当我运行上面的代码时;我收到此错误

AttributeError: 'numpy.ndarray' 对象没有属性 'hist';

你能解决这个问题吗?

【问题讨论】:

    标签: python pandas numpy matplotlib histogram


    【解决方案1】:

    这就是axs 是:

    array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7fb9261a4a10>,
            <matplotlib.axes._subplots.AxesSubplot object at 0x7fb9260fc510>],
           [<matplotlib.axes._subplots.AxesSubplot object at 0x7fb926130b10>,
            <matplotlib.axes._subplots.AxesSubplot object at 0x7fb9260f1190>]],
          dtype=object)
    

    所以你想要这样的东西:

    x=pd.DataFrame(np.random.randn(400)) 
    
    fig, axs = plt.subplots(2, 2, sharey=True, tight_layout=True, figsize=(10,5));     
    axs[0, 0].hist(x, bins=20)
    axs[0, 1].hist(x, bins=40)
    axs[1, 0].hist(x, bins=60)
    axs[1, 1].hist(x, bins=100)
    

    或者你可以使用这样的for循环:

    b = [20, 40, 60, 100]
    for i, ax in enumerate(axs.flatten()):
        ax.hist(x, bins=b[i])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-14
      • 2018-07-05
      • 2014-11-05
      • 2017-09-09
      • 2017-09-24
      • 2020-10-10
      • 2018-12-05
      • 2020-10-19
      相关资源
      最近更新 更多