I have a requirement to create multiple plots, one such plot’s code is here.
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({'Label': ['a', 'b', 'c', 'd', 'e', 'f'],
'Val': [np.random.rand() for _ in range(6)],
})
sns.set_style('whitegrid')
plt.figure(figsize=(6, 4))
sns.barplot(df, x='Label', y='Val', color='steelblue')
plt.xlabel('Bin', fontsize=9)
plt.ylabel('Value', fontsize=9)
plt.title('Trend', fontsize=11)
plt.tight_layout()
all_plots = dict()
buffer = BytesIO()
plt.savefig(buffer, format='png', bbox_inches='tight')
buffer.seek(0)
all_plots['p1'] = buffer
I do not want to print these plots when running the codes in Jupyter, but to save them in another ‘object’ which I can use later to save the images to an excel file.
However, running above code prints the plot, how do I turn-off the “printing”?
3
You can use plt.close()
Or use %%capture at the start of your cell.
Even %%capture myplot and next cell use myplot() to display the plot.
2
Expanding on the first part of rehaqds excellent answer to include how you’d link this to your other object:
As rehaqds
covers, you can use plt.close()
to not have an open plot object when Jupyter hits the end of the cell, and so it won’t display it. But how do you use that later?
You’d probably want to assign the plot figure to a variable so you can use it later. In fact, that let’s you assign it to another object or display it later.
Example adapted from your code
For using .figure
to assign that or display it later you need to assign the plot to a variable, like so. (For more information see here and here and here and here.)
In your case it would look like this in a cell near the start:
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({'Label': ['a', 'b', 'c', 'd', 'e', 'f'],
'Val': [np.random.rand() for _ in range(6)],
})
sns.set_style('whitegrid')
p = plt.figure(figsize=(6, 4))
sns.barplot(df, x='Label', y='Val', color='steelblue')
plt.xlabel('Bin', fontsize=9)
plt.ylabel('Value', fontsize=9)
plt.title('Trend', fontsize=11)
plt.tight_layout()
plt.close()
Besides the addition of plt.close()
suggested by rehaqds to close the plot object you created, the other change p = plt.figure(figsize=(6, 4))
(besides making the code an actual minimal reproducible example, see under ‘Help others reproduce the problem’ here) gives us a handle to invoke later.
If you just wanted to redisplay, it in a later cell, you can put p.figure
in a cell and see the plot, or use display(p.figure)
if it isn’t the last expression in your cell. In your case, you want to assign it to an object. So it would happen like the following in a later cell:
all_plots = dict()
all_plots[1]= p.figure
With that other object assigned, you can also use all_plots[1]
in a cell, or the related display(all_plots[1])
.
I believe that is what the OP actually wanted.
For sake of completeness here is the code for a cell for the second part of rehaqds’ suggestions:
%%capture mycapplot
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({'Label': ['a', 'b', 'c', 'd', 'e', 'f'],
'Val': [np.random.rand() for _ in range(6)],
})
sns.set_style('whitegrid')
plt.figure(figsize=(6, 4))
sns.barplot(df, x='Label', y='Val', color='steelblue')
plt.xlabel('Bin', fontsize=9)
plt.ylabel('Value', fontsize=9)
plt.title('Trend', fontsize=11)
plt.tight_layout()
You can then in other cells use mycapplot.show()
to display it later mycapplot.show(), based on my answer here that includes more context and references. Or mycapplot()
as rehaqds points out.
However, using type(mycapplot)
you can see that mycapplot
is a IPython.utils.capture.CapturedIO
object and not a matplotlib plot figure as you seem to want to store for later saving the figure object. In other words, it is more along the lines of Jupyter output, i.e., an image in the .ipynb
code, at this point and not a matplotlib plot. It seems downstream of that.