簡體   English   中英

使用Matplotlib中的軸繪制帶有子點的圖形時出現錯誤

[英]Getting error when plotting a figure with sublpots using axes in matplotlib

我試圖使用下面的代碼繪制子圖。但是我得到了'AttributeError: 'numpy.ndarray' object has no attribute 'boxplot'

但是更改plt.subplots(1,2)它正在繪制帶有indexerror的箱形圖。

import matplotlib.pyplot as plt
import seaborn as sns

fig = plt.Figure(figsize=(10,5))

x = [i for i in range(100)]


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

for i in range(4):
    sns.boxplot(x, ax=axes[i])

plt.show();

我期望應該繪制四個子圖,但是拋出AttributeError

您的情節中的幾個問題:

  • 您正在定義該圖兩次,不需要。 我將它們合並為一個。
  • 您使用range(4)並使用axes[i]進行了4次循環,以訪問子圖。 由於以下原因,這是錯誤的:您的軸是2維的,因此需要2個索引才能訪問它。 每個維度的長度為2,因為您有2行和2列,因此沿每個軸只能使用的索引是0和1。 對於前。 axes[0,1]axes[1,0]
  • 正如@DavidG指出的那樣,您不需要列表理解。 您可以直接使用range(100)

解決方案是展開/展平使您的2d軸對象,然后直接在其上進行迭代,這將為您提供一個單獨的子圖,一次一次。 子圖的順序將是逐行的。


完整的工作代碼

import matplotlib.pyplot as plt
import seaborn as sns

x = range(100)

fig , axes = plt.subplots(2,2, figsize=(10,5))

for ax_ in axes.flatten():
    sns.boxplot(x, ax=ax_)

plt.show()

在此處輸入圖片說明

暫無
暫無

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

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