【问题标题】:Getting error when plotting a figure with sublpots using axes in matplotlib使用 matplotlib 中的轴绘制带有 sublpots 的图形时出错
【发布时间】:2019-06-29 14:53:29
【问题描述】:

我尝试使用以下代码绘制子图。但我得到了'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 正在抛出

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    你的情节中有几个问题:

    • 您定义了两次不需要的图形。我将它们合二为一。
    • 您使用range(4) 循环了4 次,并使用axes[i] 访问子图。这是错误的,原因如下:您的轴是二维的,因此您需要 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()
    

    【讨论】:

    • 甚至可以删除列表理解,因为这也不是真正需要的?
    猜你喜欢
    • 2020-09-17
    • 2018-07-20
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多