4

I am looping over a list of DataFrame column names to create barplots using matplotlib.pyplot in a Jupyter Notebook. Each iteration, I'm using the columns to group the bars. Like so:

%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();

The semicolon (';') should suppress text output but when I run the code I get, after the 1st run:

enter image description here

If I run a similar snippet outside of a for loop, it works as expected - the following successfully suppresses output:

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

How do I suppress this text output when looping?


Note:

In a previous version of this question, I used the following code to which some of the comments refer, yet I changed it to the above to better show the issue.

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();
7
  • I cannot reproduce this. When running the above, there is no text output. But I guess you should use sns.boxplot( ..., ax=ax) to plot to the axes you create in the line above. Commented Mar 11, 2018 at 10:29
  • @ImportanceOfBeingErnest, thanks for suggestion, but that didn't work. I wonder why you can't reproduce it. Maybe it's version-specific. Commented Mar 11, 2018 at 10:53
  • 1
    My suggestion has nothing to do with this issue, it's just in general that you should tell boxplot which axes to use if you created that axes beforehands - in this case it will not break anything if you don't do it, in other cases it would. Concerning the issue: Yes, post a minimal reproducible example, tell the versions you are using and best include a screenshot as well. For me, it looks like this. Commented Mar 11, 2018 at 11:01
  • I can also not reproduce this. I just get plots in the output in the same way as the screenshot in @ImportanceOfBeingErnest's comment Commented Mar 11, 2018 at 12:15
  • Thanks for the responses. I edited my post as suggested but in doing so also answered my own question, which I also posted. Commented Mar 11, 2018 at 13:36

3 Answers 3

7

I discovered what what causing this behaviour. I ran my notebook with the following:

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

(documented here)

This had the effect of not suppressing matplotlib output when plotting in a loop. However, as mentioned in the original post, it did suppress output as expected when not within a loop. In any case, I fixed the issue by 'undoing' my code above like this:

InteractiveShell.ast_node_interactivity = "last_expr"

I'm not sure why this would happen.

Sign up to request clarification or add additional context in comments.

1 Comment

Setting it to "none" helped resolve my error
0

@voyager's answer worked for me, but only if I put

InteractiveShell.ast_node_interactivity = "last_expr"

in the cell preceding the cell with the matplotlib annotate loop.

Alternative: I wrapped the plot code containing the annotate loop into a plot function. If you call this function, the repeated 'Text' output remains within the function, no longer requiring a change to the InteractiveShell settings:

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

Comments

0

Try replacing plt.show() with plt.close().

It worked for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.