[英]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]
等 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.