簡體   English   中英

pyplot子圖因seaborn而失敗

[英]pyplot subplots fails with seaborn

在嘗試並排繪制兩個帶有 seaborn 的直方圖時,我收到以下錯誤:

我的代碼:

fig, axs = plt.subplots(1, 2)
sns.distplot(MAPE_per_stock , ax = axs[0,0])
sns.distplot(MAPE_per_stock[start_test:], ax = axs[0, 1])

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-212-9c4fad36d97d> in <module>
      1 fig, axs = plt.subplots(1, 2)
----> 2 sns.distplot(MAPE_per_stock , ax = axs[0,0])
      3 sns.distplot(MAPE_per_stock[start_test:], ax = axs[0, 1])

IndexError: too many indices for array

是什么引發了異常,我應該如何更正代碼?

import matplotlib.pyplot as plt

fig, axs = plt.subplots(1, 2)

查看您創建的axs

axs.shape

out: (2,)

因此,一個沿一個軸具有兩個元素的數組。 可以使用 axs axs[0]axs[1]各個元素:

axs[0]
<matplotlib.axes._subplots.AxesSubplot at 0x1965b6bc5f8>

由於只有一個方向對數據進行排序,因此指定兩個位置會導致您遇到的錯誤:

axs[0,1]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-3-aaadfc217757> in <module>
----> 1 axs[0,1]

IndexError: too many indices for array

請注意,如果您創建一個 2 x 2 的網格:

fig, axs = plt.subplots(2, 2)

您實際上創建了一個 2 by2 數組,您可以使用問題中的方案對其進行索引。

axs.shape
out: (2,2)

axs[1,1]
out: <matplotlib.axes._subplots.AxesSubplot at 0x1965bcd1860>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM