代码之家  ›  专栏  ›  技术社区  ›  voyager

如何在Jupyter笔记本的for循环中抑制matplotlib输出?

  •  3
  • voyager  · 技术社区  · 8 年前

    我正在遍历数据框列名列表,以使用matplotlib创建条形图。Jupyter笔记本中的pyplot。每次迭代,我都使用列来对条进行分组。像这样:

    %matplotlib inline
    
    import pandas as pd
    from matplotlib import pyplot as plt
    
    
    # Run all output interactively
    from IPython.core.interactiveshell import InteractiveShell
    InteractiveShell.ast_node_interactivity = "all"
    
    
    df = pd.DataFrame({'col1': ['A', 'B', 'C'], 'col2': ['X', 'Y', 'Z'], 'col3': [10, 20, 30]})
    
    #This DOES NOT suppress output
    cols_to_plot = ['col1', 'col2']
    for col in cols_to_plot:
        fig, ax = plt.subplots()
        ax.bar(df[col], df['col3'])
        plt.show();
    

    分号(“;”)应该抑制文本输出,但当我运行得到的代码时,在第一次运行之后:

    enter image description here

    如果我在 for 循环,它按预期工作-以下操作成功抑制输出:

    # This DOES suppress output
    fig, ax = plt.subplots()
    ax.bar(df['col1'], df['col3'])
    plt.show();
    

    循环时如何抑制此文本输出?


    注:

    在这个问题的前一个版本中,我使用了一些注释引用的以下代码,但我将其更改为上面的代码,以更好地显示问题。

    cols_to_boxplot = ['country', 'province']
    for col in cols_to_boxplot:
        fig, ax = plt.subplots(figsize = (15, 10))
        sns.boxplot(y=wine['log_price'], x=wine[col])
        labels = ax.get_xticklabels()
        ax.set_xticklabels(labels, rotation=90);
        ax.set_title('log_price vs {0}'.format(col))
        plt.show();
    
    2 回复  |  直到 8 年前
        1
  •  6
  •   voyager    8 年前

    我发现了导致这种行为的原因。我在笔记本上运行了以下内容:

    from IPython.core.interactiveshell import InteractiveShell
    InteractiveShell.ast_node_interactivity = "all"
    

    ( documented here )

    这样做的效果是,在循环中打印时,不会抑制matplotlib输出。然而,正如原帖中所述 在以下情况下按预期抑制输出 在一个循环中。在任何情况下,我都通过如下方式“撤消”上面的代码来修复此问题:

    InteractiveShell.ast_node_interactivity = "last_expr"
    

    我不知道为什么会这样。

        2
  •  0
  •   Arend    4 年前

    @旅行者的回答对我有用,但前提是我

    InteractiveShell.ast_node_interactivity = "last_expr"
    

    在单元格中 之前的 具有matplotlib注释循环的单元格。

    备选方案:我将包含注释循环的绘图代码包装到 绘图功能 。 如果调用此函数,则会保留重复的“文本”输出 在内部 该功能不再需要更改InteractiveShell设置:

    def plot_with_loop(df):
       ...
       ax = df.plot();
    
       for i in range(len(df)):
            # next line generates 'Text' output when not called contained in function
            ax.annotate(...); 
        
    
    plot_with_loop(df)  # no 'Text' output
    
    推荐文章