如何用不同的 bins pandas 做子图直方图?

how to do subplot histogram with different bins pandas?

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' object has no attribute 'hist';

你能解决这个问题吗?

这就是 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])