Issue
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:
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();
Solution
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"
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.
Answered By - voyager
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.